Ejemplo n.º 1
0
def print_script_info(stores_obj):
    try:
        # Print how many script tags added already
        print(shopify.ScriptTag().count())

        # Loop through each script tag and print attributes of each
        for script_tag in shopify.ScriptTag().find():
            print(script_tag.attributes)
    except Exception as e:
        logger.error('Exception caught for {}. {}'.format(
            stores_obj.store_name, e))
Ejemplo n.º 2
0
def home(request, *args, **kwargs):
  shop_name = request.user.myshopify_domain
  print('++++++++++++++++++ activating webhook ++++++++++++++++++')
  webhook_shop_address = settings.APP_DOMAIN + '/app/uninstall_webhook_callback/'
  with request.user.session:
    webhook_status = 0
    webhook_shops = shopify.Webhook.find()
    if webhook_shops:
      for webhook_shop in webhook_shops:
        if webhook_shop.address == webhook_shop_address:
          webhook_status = 1
    if webhook_status == 0:
      print('++++++++++++++++++ saving webhook ++++++++++++++++++')
      webhook_shop = shopify.Webhook()
      webhook_shop.topic = 'app/uninstalled'
      webhook_shop.address = webhook_shop_address
      webhook_shop.format = 'json'
      webhook_shop.save()
      
    url = settings.APP_DOMAIN + settings.STATIC_URL + 'script/script.js'    
    shopify.ScriptTag(dict(event='onload', src=url)).save()


  items = Times.objects.filter(shop_name=shop_name).order_by('-id')
  item = {};
  if items:
    item = items[0]

  conf_items = TextConf.objects.filter(shop_name=shop_name).order_by('-id')
  conf_item = {};
  if conf_items:
    conf_item = conf_items[0]


  return render(request, "main_app/home.html", { "item": item, "conf": conf_item })
Ejemplo n.º 3
0
def delete_script_by_id(stores_obj, script_tag_id):
    try:
        script_tag_obj = (shopify.ScriptTag().find(script_tag_id))
        shopify.ScriptTag.delete(script_tag_obj.id)
    except Exception as e:
        logger.error('Exception caught for {}. {}'.format(
            stores_obj.store_name, e))
Ejemplo n.º 4
0
def createScriptTag():
    print '==> createScriptTag()'
    scripttag = shopify.ScriptTag()
    scripttag.event = 'onload'
    scripttag.src = settings.APP_DOMAINURL + '/scriptsrc/'
    scripttag.save()
    return scripttag
Ejemplo n.º 5
0
def add_script(stores_obj, script_name):
    # Development app url: https://protected-reef-37693.herokuapp.com
    # Production app url: https://socialproof-samurai.herokuapp.com

    # Add script tag to the shop
    src = '{}/static/js/{}'.format(settings.APP_URL, script_name)

    try:
        shopify.ScriptTag(dict(display_scope='all', event='onload',
                               src=src)).save()
    except Exception as e:
        logger.error('Exception caught for {}. {}'.format(
            stores_obj.store_name, e))
Ejemplo n.º 6
0
def modify_search_box(shop):
    customer = Customer.query.filter_by(shop=shop).first()
    if customer is not None:
        shopify.Session.setup(api_key=api_key, secret=api_secret_key)
        session = shopify.Session(customer.shop, customer.code)
        shopify.ShopifyResource.activate_session(session)
        sp = shopify.ScriptTag()
        sp.event = "onload"
        sp.src = "https://" + application.config['HOST'] + "/js/search_box.js"
        success = sp.save()
        if sp.errors:
            return str(sp.errors.full_messages())
        else:
            s = ScriptTag(sp.id, sp.display_scope, shop)
            db.session.add(s)
            db.session.commit()
            return True
    return False
Ejemplo n.º 7
0
def finalize():
    code = request.args.get('code')
    shop_name = request.args.get('shop')
    timestamp = request.args.get('timestamp')
    hmac = request.args.get('hmac')
    params = {
        'code': code,
        'timestamp': timestamp,
        'hmac': hmac,
        'shop': shop_name
    }
    api_version = app.config.get('SHOPIFY_API_VERSION')
    shopify.Session.setup(api_key=app.config['SHOPIFY_API_KEY'],
                          secret=app.config['SHOPIFY_API_SECRET'])
    session = shopify.Session(shop_name, api_version)
    token = session.request_token(params)

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except Merchant.DoesNotExist:
        merchant = Merchant()
        merchant.enable = False
        merchant.shop_name = shop_name

    merchant.token = token
    merchant.save()

    save_default_html(merchant)

    shop_short = shop_name.replace('.myshopify.com', '')

    need_webhooks = [
        {
            'url': 'https://{}/create_order/{}'.format(
                app.config.get('HOSTNAME'), shop_short),
            'topic': 'orders/create',
            'created': False
        },
        {
            'url': 'https://{}/uninstalled'.format(
                app.config.get('HOSTNAME')),
            'topic': 'app/uninstalled',
            'created': False
        },
    ]

    with shopify.Session.temp(shop_name, api_version, merchant.token):
        webhooks = shopify.Webhook.find()

        for webhook in webhooks:

            for need_webhook in need_webhooks:

                if webhook.topic == need_webhook.get('topic') and \
                        webhook.address == need_webhook.get('url'):
                    need_webhook.update({'created': True})

        for need_webhook in need_webhooks:

            if need_webhook.get('created'):
                continue

            app.logger.info('create webhook {}'.format(need_webhook.get('topic')))
            webhook = shopify.Webhook()
            webhook.topic = need_webhook.get('topic')
            webhook.address = need_webhook.get('url')
            webhook.format = 'json'
            webhook.save()
            pause_sdk(2)

        ecocart_script = shopify.ScriptTag()
        ecocart_script.event = 'onload'
        ecocart_script.src = 'https://{}/ecocart.js?shop_name={}'.format(
            app.config.get('HOSTNAME'), shop_name)
        ecocart_script.save()

    image_url = app.config.get('ECOCART_IMAGE_URL')
    e = Ecocart(image_url, merchant)
    e.install()

    if not app.config.get('CHARGE_ENABLE'):
        url = 'https://{}/admin/apps/{}'
        # редирект в админку
        return redirect(url.format(shop_name, app.config.get('SHOPIFY_API_KEY')))

    # подписка
    return_url = 'https://{}/activatecharge/{}'
    return_url = return_url.format(app.config.get('HOSTNAME'), shop_name)
    data_create = {
        'name': app.config.get('CHARGE_NAME'),
        'price': 0.5,
        'return_url': return_url,
        'test': app.config.get('CHARGE_TEST'),
    }
    url = create_application_charge(shop_name, token, data_create)

    return redirect(url)
Ejemplo n.º 8
0
    def finalize(self, **kw):
        shop_url = kw['shop']
        current_app = DefaultConfig()

        shopify.Session.setup(api_key=current_app.SHOPIFY_API_KEY,
                              secret=current_app.SHOPIFY_SHARED_SECRET)
        shopify_session = shopify.Session(shop_url, '2019-04')

        # todo : write it to another storage
        http.request.httprequest.session.shopify_obj = shopify_session

        token = shopify_session.request_token(kw)

        organizationEnv = http.request.env['shopify_app.shop']
        organization = organizationEnv.sudo().search([("url", "=", shop_url)])

        if organization['install_status'] == 'uninstalled':
            organization.write({'install_status': 'active'})

        if not organization:
            vals = {'url': shop_url, 'code': token}

            createdOrg = organization.sudo().create(vals)

            # Create company
            shopUrl = shop_url
            shopUrlemail = shop_url.split('.')[0] + '@gmail.com'
            companyModel = http.request.env['res.company']

            company = companyModel.sudo().search([("name", "=", shopUrl)])
            if not company:
                #create company
                vals = {
                    'logo': False,
                    'currency_id': 2,
                    'sequence': 10,
                    'favicon':
                    'AAABAAEAEBAAAAAAIAAGAgAAFgAAAIlQTkcNChoKAAAADUlIRFIAAAAQAAAAEAgGAAAAH/P/YQAAAc1JREFUeJyV0s+LzVEYBvDP+53vNUYzSZqFlbBgJUL5tWByJzaysZPJP2AhP+7SYhZXKZEtNRZKlqPUjEQTFmbhH5AosRPjTrr3zvdY3DO6ZiKe09k8z/u85+15T8i4c2xSraiRrBX24ih2YA3e4ileoJVSMjHbAAFT403tTtdgrbYbF3AcG5f1jK+YxbXFpYX5oYFhEzMNMVVvGh4c0mr/OIkb2OrveIfzA0U86i5VyojQav84gFvYnIu+4xXeoMQe7MMQtuDmUpU+R8R8iWFc7jO/x5XEdLAYRaGqqpHgNCaxKU95KaV0rsThHBi00AjxIKmcnekFNVVvLtRqa+52up0CtzGIekQcLHAE63ODl4npSjKRzTAx29DudiQe4nWmN2CsWBHam0K0UqpWR5eSIuIr5vvYbYXfV5VWO5eFtKy2++iiwIc+YmclrYsoVjWICJVqHXb20e8KzOmtDQ4F44F79eavqql6U/TOOA5l+huelYnn0dt5HSNoYjGFp/fGr3Xz+CXGsjaSGzzDXBl8wXXswii2436Ix3LiIfbhhN73ho/Zs1BCSulJRDTyC6O58Ey+K/EJFztL3bmyGBCn9l/9Y/L/gtVx/yd+Akefkiz2xrqJAAAAAElFTkSuQmCC',
                    'name': shopUrl,
                    'street': False,
                    'street2': False,
                    'city': False,
                    'state_id': False,
                    'zip': False,
                    'country_id': False,
                    'phone': False,
                    'email': False,
                    'website': False,
                    'vat': False,
                    'company_registry': False,
                    'parent_id': False
                }
                companyShop = companyModel.sudo().create(vals)
                companyId = companyShop.id
                # create user for the company
                user = http.request.env['res.users']

                userId = user.sudo().search([("login", "=", shopUrlemail)])
                if not userId:
                    vals = {
                        'is_published': False,
                        'company_ids': [[6, False, [companyId]]],
                        'company_id': companyId,
                        'active': True,
                        'lang': 'en_US',
                        'tz': 'Europe/Brussels',
                        'notification_type': 'email',
                        'odoobot_state': 'not_initialized',
                        'image_1920': False,
                        '__last_update': False,
                        'name': shopUrl,
                        'email': shopUrlemail,
                        'login': shopUrlemail,
                        'password': '******',
                        'action_id': False,
                        'alias_id': False,
                        'alias_contact': False,
                        'groups_id': [(6, 0, [1])]
                    }
                    createdUser = user.sudo().create(vals)
                    createdUserId = createdUser.id
                    # db = http.request.env.cr.dbname;
                    # uid = http.request.httprequest.session.authenticate(db, shopUrlemail, "token")
                    http.request.httprequest.session.shopify_token = token
                    http.request.httprequest.session.shopify_email = shopUrlemail

                    shopify.ShopifyResource.activate_session(shopify_session)
                    scrpt = shopify.ScriptTag(
                        dict(
                            event='onload',
                            src=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/static/src/js/shopify.js"
                        )).save()

                    # order create webhook
                    # orders / cancelled, orders / create, orders / fulfilled, orders / paid, orders / partially_fulfilled, orders / updated
                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="orders/create",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/order_create",
                            format="json")).save()

                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="orders/updated",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/order_update",
                            format="json")).save()

                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="orders/delete",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/order_delete",
                            format="json")).save()

                    # checkout

                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="checkouts/create",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_create",
                            format="json")).save()
                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="checkouts/update",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_update",
                            format="json")).save()
                    weekhooks_response = shopify.Webhook(
                        dict(
                            topic="checkouts/delete",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_delete",
                            format="json")).save()
                    # uninstall app webhook
                    weekhooks_uninstall_response = shopify.Webhook(
                        dict(
                            topic="app/uninstalled",
                            address=
                            "https://c90bcfbe8e36.ngrok.io/shopify_app/app_uninstalled",
                            format="json")).save()
            else:
                # never run into this block of code,log for further usage
                x = 1
        #authenticate user and route to home
        user = http.request.env['res.users']

        shopUrlemail = shop_url.split('.')[0] + '@gmail.com'
        user = user.sudo().search([("login", "=", shopUrlemail)])

        shopUrlemail = shop_url.split('.')[0] + '@gmail.com'
        http.request.httprequest.session.shopify_email = shopUrlemail

        shopify.ShopifyResource.activate_session(shopify_session)
        weekhooks = shopify.Webhook.find()

        #todo : remove
        products = shopify.Product.find(page=2, limit=1)
        productsp1 = shopify.Product.find(page=1, limit=1)

        checkout = shopify.Checkout.find()
        checkoutc = shopify.Checkout(prefix_options='count').find()
        # checkoutc = shopify.Checkout(query_options={'cou
        # nt': ''}).find();
        checkoutc = shopify.Checkout.get('count')
        checkoutsx = shopify.Checkout.find(updated_at_min='2020-06-19')

        x = 1
        if not weekhooks:
            # order create webhook
            # orders / cancelled, orders / create, orders / fulfilled, orders / paid, orders / partially_fulfilled, orders / updated
            weekhooks_response = shopify.Webhook(
                dict(topic="orders/create",
                     address=
                     "https://c90bcfbe8e36.ngrok.io/shopify_app/order_create",
                     format="json")).save()

            weekhooks_response = shopify.Webhook(
                dict(topic="orders/updated",
                     address=
                     "https://c90bcfbe8e36.ngrok.io/shopify_app/order_update",
                     format="json")).save()

            weekhooks_response = shopify.Webhook(
                dict(topic="orders/delete",
                     address=
                     "https://c90bcfbe8e36.ngrok.io/shopify_app/order_delete",
                     format="json")).save()

            # checkout

            weekhooks_response = shopify.Webhook(
                dict(
                    topic="checkouts/create",
                    address=
                    "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_create",
                    format="json")).save()
            weekhooks_response = shopify.Webhook(
                dict(
                    topic="checkouts/update",
                    address=
                    "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_update",
                    format="json")).save()
            weekhooks_response = shopify.Webhook(
                dict(
                    topic="checkouts/delete",
                    address=
                    "https://c90bcfbe8e36.ngrok.io/shopify_app/checkouts_delete",
                    format="json")).save()
            # uninstall app webhook
            # weekhooks_uninstall_response = shopify.Webhook(dict(topic="app/uninstalled",
            #                                                     address="https://c90bcfbe8e36.ngrok.io/shopify_app/app_uninstalled",
            #                                                     format="json")).save()

        if user:
            db = http.request.env.cr.dbname
            uid = http.request.httprequest.session.authenticate(
                db, shopUrlemail, 'token')
            http.request.httprequest.session.shopify_token = token
            redirect = werkzeug.utils.redirect(
                'https://c90bcfbe8e36.ngrok.io/shopify_app/home')
            return redirect