示例#1
0
 def shopify_request_token(self, params):
     for item in self:
         if item.api_status == 'draft':
             # request mode (work)
             url = 'https://%s/admin/oauth/access_token' % item.url
             payload = {
                 'client_id': str(item.api_key),
                 'client_secret': str(item.api_secret),
                 'code': str(params['code']),
             }
             headers = {'Content-Type': 'application/json'}
             response = requests.post(url,
                                      headers=headers,
                                      data=json.dumps(payload))
             if response.status_code != 200:
                 _logger.info(response.text)
             else:
                 response_json = json.loads(response.text)
                 if 'access_token' in response_json:
                     item.shopify_access_token = str(
                         response_json['access_token'])
                     # session
                     session = shopify.Session(item.url, '2020-01',
                                               item.shopify_access_token)
                     shopify.ShopifyResource.activate_session(session)
                     # api_status
                     item.api_status = 'valid'
示例#2
0
def creat_a_product(**kwargs):
    session = shopify.Session(shop_url, api_version, access_token)
    shopify.ShopifyResource.activate_session(session)

    variants = []
    images = []
    new_product = shopify.Product()

    for key, value in kwargs.items():
        if key == 'variants':
            for item in value:
                variant = shopify.Variant(item)
                variants.append(variant)
            value = variants
        elif key == 'images':
            for item in value:
                image = shopify.Image()
                with open(item, "rb") as f:
                    filename = item.split("/")[-1:][0]
                    encoded = f.read()
                    image.attach_image(encoded, filename=filename)
                    images.append(image)
            value = images

        setattr(new_product, key, value)
    new_product.save()
    print(new_product.id)
    print(new_product.to_dict())
示例#3
0
    def post(self, request, **kwargs):
        context = self.get_context_data(**kwargs)
        form = ShopForm(request.POST)

        if form.is_valid():
            shop = form.cleaned_data['shop_name']
            state = str(uuid.uuid4())
            session = shopify.Session(
                'https://%s.%s%s' %
                (shop, settings.SHOPIFY_URL, settings.SHOPIFY_AUTHORIZE_SUFIX))

            session.setup(api_key=settings.SHOPIFY_API_KEY,
                          secret=settings.SHOPIFY_SECRET)
            permission_url = session.create_permission_url(
                settings.SHOPIFY_SCOPES,
                request.build_absolute_uri(
                    reverse('core:shopify_callback'))) + '&state=' + state
            try:
                response = requests.head(permission_url)
                if response.status_code == 404:
                    form.add_error('shop_name', 'The shop cannot be reached.')
                else:
                    request.session['state'] = state
                    user = request.user
                    user.shop_name = shop
                    user.save()
                    return redirect(permission_url)
            except Exception:
                form.add_error('shop_name', 'The shop name used is not valid.')
        context['form'] = form
        return render(request, self.template_name, context)
示例#4
0
def sync_shopify_products(shop_url, access_token):
    logger.info("Sync Shopify Orders")

    session = shopify.Session(shop_url, settings.API_VERSION, access_token)
    shopify.ShopifyResource.activate_session(session)

    shopify_products = shopify.Product.find()

    not_found_products = []
    for product in shopify_products:
        try:
            ShopifyProduct.objects.get(product_id=product.id)
        except ShopifyProduct.DoesNotExist:
            not_found_product = ShopifyProduct(
                title=product.title,
                vendor=product.vendor,
                product_id=product.id,
                status=product.status,
                product_type=product.product_type,
            )
            not_found_products.append(not_found_product)

    ShopifyProduct.objects.bulk_create(not_found_products)

    logger.info("Products synced successfully!")
    return {'msg': "Products synced successfully!"}
示例#5
0
def create_webhook(stores_obj):
    """
    Create a shop webhook and add to store.
    """
    try:
        session = shopify.Session(stores_obj.store_name, stores_obj.permanent_token)
        shopify.ShopifyResource.activate_session(session)
        topic = 'app/uninstalled'

        new_webhook = shopify.Webhook()
        new_webhook.address = settings.APP_URL + '/webhooks/'
        new_webhook.topic = topic

        # [shopify.Webhook.delete(x.id) for x in shopify.Webhook.find()]

        if new_webhook.save():
            Webhooks.objects.update_or_create(store__store_name=stores_obj.store_name,
                                              topic=topic,
                                              defaults={'webhook_id': new_webhook.attributes['id'],
                                                        'store': stores_obj,
                                                        'topic': topic})
        else:
            logger.error('Warning for {}. Webhook {} not saved properly!'.format(stores_obj.store_name, topic))

    except Exception as e:
        logger.error('Exception caught for {}. {}'.format(stores_obj.store_name, e))
示例#6
0
 def setUp(self):
     super(GraphQLTest, self).setUp()
     shopify.ApiVersion.define_known_versions()
     shopify_session = shopify.Session("this-is-my-test-show.myshopify.com",
                                       "unstable", "token")
     shopify.ShopifyResource.activate_session(shopify_session)
     client = shopify.GraphQL()
     self.fake(
         "graphql",
         method="POST",
         code=201,
         headers={
             "X-Shopify-Access-Token": "token",
             "Accept": "application/json",
             "Content-Type": "application/json",
         },
     )
     query = """
         {
             shop {
                 name
                 id
             }
         }
     """
     self.result = client.execute(query)
示例#7
0
def get_access_token(request):

    shop_url = "https://{}:{}@{}/admin".format(settings.SHOPIFY_API_KEY,
                                               settings.SHOPIFY_API_PASSWORD,
                                               settings.SHOPIFY_STORE_DOMAIN)
    shopify.ShopifyResource.set_site(shop_url)

    shopify.Session.setup(api_key=settings.SHOPIFY_API_KEY,
                          secret=settings.SHOPIFY_API_PASSWORD)

    session = shopify.Session(settings.SHOPIFY_STORE_URL)

    scope = [
        "read_products",
        "write_products",
        "read_orders",
        "write_orders",
        "read_draft_orders",
        "write_draft_orders",
        "read_inventory",
        "write_inventory",
        "read_fulfillments",
        "write_fulfillments",
        "read_shipping",
        "write_shipping",
        "read_checkouts",
        "write_checkouts",
    ]

    permission_url = session.create_permission_url(
        scope, settings.SHOPIFY_ACCESS_REDIRECT_URL)

    return HttpResponseRedirect(permission_url)
示例#8
0
    def activateSession(self):
        if self.authToken == None:
            raise Exception(
                "Can't activate a shopify session without an authToken")

        session = shopify.Session(self.myshopifyDomain, self.authToken)
        shopify.ShopifyResource.activate_session(session)
示例#9
0
def authenticate(request, *args, **kwargs):
    shop = request.REQUEST.get('shop')

    if settings.SHOPIFY_APP_DEV_MODE:
        return finalize(request,
                        token='00000000000000000000000000000000',
                        *args,
                        **kwargs)

    if shop:
        redirect_uri = request.build_absolute_uri(
            reverse('shopify_auth.views.finalize'))
        scope = settings.SHOPIFY_APP_API_SCOPE
        permission_url = shopify.Session(shop.strip()).create_permission_url(
            scope, redirect_uri)

        if settings.SHOPIFY_APP_IS_EMBEDDED:
            # Embedded Apps should use a Javascript redirect.
            return render(request, "shopify_auth/iframe_redirect.html",
                          {'redirect_uri': permission_url})
        else:
            # Non-Embedded Apps should use a standard redirect.
            return HttpResponseRedirect(permission_url)

    return_address = get_return_address(request)
    return HttpResponseRedirect(return_address)
示例#10
0
def _new_session(shop_url):
    shopify_api_version = apps.get_app_config("shopify_app").SHOPIFY_API_VERSION
    shopify_api_key = apps.get_app_config("shopify_app").SHOPIFY_API_KEY
    shopify_api_secret = apps.get_app_config("shopify_app").SHOPIFY_API_SECRET

    shopify.Session.setup(api_key=shopify_api_key, secret=shopify_api_secret)
    return shopify.Session(shop_url, shopify_api_version)
示例#11
0
 def try_connect(self, logger: AirbyteLogger, config: dict):
     session = shopify.Session(f"{config['shop']}.myshopify.com", "2021-01",
                               config["api_key"])
     shopify.ShopifyResource.activate_session(session)
     # try to read the name of the shop, which should be available with any level of permissions
     shopify.GraphQL().execute("{ shop { name id } }")
     shopify.ShopifyResource.clear_session()
示例#12
0
def finalize(request):
	shop_url = request.GET.get('shop')
	print('Inside finalizeeee')
	try:
	    shopify_session = shopify.Session(shop_url)
	    print(request.GET)
	    params = {
		"shop": shop_url,
		"code": request.GET['code'],
		"timestamp": request.GET['timestamp'],
		"hmac": request.GET['hmac'],
	    }
	    	
	    request.session['shopify'] = {
		"shop_url": shop_url,
		"access_token": shopify_session.request_token(params)
	    }

	except Exception:
	    print('Could not login')
	    messages.error(request,"Could not log in to shopify store.")
	    return redirect(reverse('login'))

	messages.info(request,"Logged in to Shopify Store.")

	response = redirect(_return_address(request))
	request.session.pop('return_to', 1)
	return response
示例#13
0
def authenticate(request, *args, **kwargs):
    shop = request.POST.get('shop')

    if shop:
        from shopify_auth import views as shopify_auth_views
        redirect_uri = request.build_absolute_uri(
            reverse(shopify_auth_views.finalize))
        #redirect_uri = request.build_absolute_uri(reverse(shopify_auth.views.finalize))
        scope = settings.SHOPIFY_APP_API_SCOPE
        print(redirect_uri)
        redirect_uri = redirect_uri[:-1]
        temp_url = shopify.Session(shop.strip()).create_permission_url(
            scope, redirect_uri)

        permission_url = temp_url

        if settings.SHOPIFY_APP_IS_EMBEDDED:
            # Embedded Apps should use a Javascript redirect.
            return render(request, "shopify_auth/iframe_redirect.html",
                          {'redirect_uri': permission_url})
        else:
            # Non-Embedded Apps should use a standard redirect.
            return HttpResponseRedirect(permission_url)
    else:
        shop = request.GET.get('shop')
        if shop:
            return finalize(request, *args, **kwargs)

    return_address = get_return_address(request)
    return HttpResponseRedirect(return_address)
示例#14
0
    def action_post(self):
        rec = super(SocialPostInherit, self).action_post()
        shops = self.env['shopify_app.shop'].sudo().search([('id', '>', 0)])
        for shop in shops:
            # get the offline access code
            domain = shop['url']
            app = self.env['shopify.module.name'].sudo().search([
                '&', ('shopify_shop_id', '=', shop.id),
                ('app_name', '=', 'blog post')
            ])
            token = app.code

            session = shopify.Session(domain, '2020-01', token)
            shopify.ShopifyResource.activate_session(session)
            article = shopify.Article({
                "author": self.env.user.name,
                "blog_id": int(self.blog_id),
                "body_html": str(self.message),
                "created_at": str(self.create_date),
                "published_at": str(datetime.now()),
                # "summary_html": self.get_image(),
                "title": str(self.title),
                # "updated_at": "2012-07-06T13:57:51-04:00",
                "user_id": '',
                "tags": self.get_tag_name(),
                # "image": {
                #     "created_at": str(self.create_date),
                #     "alt": str(self.get_image()),
                #     "src": 'https://cdn.shopify.com/s/files/1/0456/3356/8929/articles/'+str(self.get_image())
                # }
            })
            article.save()
        return rec
 def get_credential(self, channel, id, environment):
     """Get Credential."""
     if channel == 'analytics':
         credential = self._analytics_get_credential(id)
     if channel == 'facebook':
         credential = {}
         credential['access_token'] = self._facebook_get_access_token(id)
         credential['app_id'] = self._facebook_get_client_id(
             self.client, environment)
         credential['app_secret'] = self._facebook_get_client_secret(
             self.client, environment)
     if channel == 'adwords':
         credential = {}
         credential['client_id'] = self._adwords_get_client_id(
             self.client, environment)
         credential['client_secret'] = self._adwords_get_client_secret(
             self.client, environment)
         credential['developer_token'] = self._adwords_get_developer_token(
             self.client, environment)
         credential['refresh_token'] = self._adwords_get_refresh_token(id)
     if channel == 'shopify':
         credential = {}
         shop_url = f"{id}.myshopify.com"
         access_token = self._shopify_get_access_token(id)
         session = shopify.Session(shop_url, SHOPIFY_API_VERSION,
                                   access_token)
         credential['session'] = session
     return credential
示例#16
0
    def get_blog(self):
        current_app = DefaultConfig()
        shops = self.env['shopify_app.shop'].sudo().search([('id', '>', 0)])
        for shop in shops:
            # get the offline access code
            domain = shop['url']
            app = self.env['shopify.module.name'].sudo().search([
                '&', ('shopify_shop_id', '=', shop.id),
                ('app_name', '=', 'blog post')
            ])
            token = app.code

            session = shopify.Session(domain, '2020-01', token)
            shopify.ShopifyResource.activate_session(session)
        url = 'https://magenestdev.myshopify.com/admin/api/2020-07/blogs.json'
        headers = {
            'Content-Type': 'application/json',
            'client_id': current_app.SHOPIFY_API_KEY,
            'client_secret': current_app.SHOPIFY_SHARED_SECRET,
            'X-Shopify-Access-Token': token
        }
        response = requests.get(url, headers=headers)
        data = response.json()
        list_blogs = []
        for i in range(0, len(data['blogs'])):
            list_blogs.extend([(str(data['blogs'][i]['id']),
                                data['blogs'][i]['title'])])
        return list_blogs
示例#17
0
def authenticate(request, *args, **kwargs):
    shop = request.POST.get('shop', request.GET.get('shop'))

    if settings.SHOPIFY_APP_DEV_MODE:
        return finalize(request,
                        token='00000000000000000000000000000000',
                        *args,
                        **kwargs)

    if shop:
        # Store return adress so merchant gets where they intended to.
        return_address_parameter = request.GET.get(auth.REDIRECT_FIELD_NAME)
        if return_address_parameter:
            request.session[
                SESSION_REDIRECT_FIELD_NAME] = return_address_parameter

        redirect_uri = request.build_absolute_uri(reverse(finalize))
        scope = settings.SHOPIFY_APP_API_SCOPE
        permission_url = shopify.Session(
            shop.strip(),
            getattr(settings, 'SHOPIFY_APP_API_VERSION',
                    'unstable')).create_permission_url(scope, redirect_uri)

        if settings.SHOPIFY_APP_IS_EMBEDDED:
            # Embedded Apps should use a Javascript redirect.
            return render(request, "shopify_auth/iframe_redirect.html", {
                'shop': shop,
                'redirect_uri': permission_url
            })
        else:
            # Non-Embedded Apps should use a standard redirect.
            return HttpResponseRedirect(permission_url)

    return_address = get_return_address(request)
    return HttpResponseRedirect(return_address)
示例#18
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     if hasattr(request, 'session') and 'shopify' in request.session:
         print request.session['shopify']['shop_url']
         shopify_session = shopify.Session(
             request.session['shopify']['shop_url'])
         shopify_session.token = request.session['shopify']['access_token']
         shopify.ShopifyResource.activate_session(shopify_session)
示例#19
0
    def get(self, request, **kwargs):
        shop = request.GET.get('shop', '')
        if shop != '':
            request.session['shop_name'] = shop
            shop_obj = Shop.objects.filter(name=shop)
            if shop_obj:
                return redirect(reverse('core:dashboard'))

            state = str(uuid.uuid4())
            session = shopify.Session(
                'https://%s.%s%s' %
                (shop, settings.SHOPIFY_URL, settings.SHOPIFY_AUTHORIZE_SUFIX))

            session.setup(api_key=settings.SHOPIFY_API_KEY,
                          secret=settings.SHOPIFY_SECRET)
            permission_url = session.create_permission_url(
                settings.SHOPIFY_SCOPES,
                request.build_absolute_uri(
                    reverse('core:shopify_callback'))) + '&state=' + state

            try:
                response = requests.head(permission_url)
                if response.status_code == 404:
                    return HttpResponseForbidden()
                else:
                    request.session['state'] = state
                    return redirect(permission_url)
            except Exception:
                return HttpResponseForbidden()
            return render(request, self.template_name, context)
        else:
            return HttpResponseForbidden()
示例#20
0
 def getStore(self):
     shopify.Session.setup(api_key=self.api_key, secret=self.secret_key)
     session = shopify.Session(self.shop_url, self.api_version,
                               self.access_token)
     shopify.ShopifyResource.activate_session(session)
     shop = shopify.Shop.current()
     shopify.ShopifyResource.clear_session()
     return shop
示例#21
0
    def test_raise_error_if_hmac_is_invalid(self):
        shopify.Session.secret = "secret"
        params = {"code": "any-code", "timestamp": time.time()}
        params["hmac"] = "a94a110d86d2452e92a4a64275b128e9273be3037f2c339eb3e2af4cfb8a3828"

        with self.assertRaises(shopify.ValidationException):
            session = shopify.Session("http://localhost.myshopify.com", "unstable")
            session = session.request_token(params)
示例#22
0
    def test_raise_error_if_hmac_is_invalid(self):
        shopify.Session.secret='secret'
        params = {'code': 'any-code', 'timestamp': time.time()}
        params['hmac'] = 'a94a110d86d2452e92a4a64275b128e9273be3037f2c339eb3e2af4cfb8a3828'

        with self.assertRaises(shopify.ValidationException):
            session = shopify.Session('http://localhost.myshopify.com')
            session = session.request_token(params)
示例#23
0
def _delete_products():
    shop_session = sfy.Session(session['shop_url'], '2019-04', session['token'])
    # activate the shopify session to use resources.
    sfy.ShopifyResource.activate_session(shop_session)
    products = Product.query.all()
    for p in products:
        delete_products(p.gid)
    return(jsonify('ok')) #this makes the browser happy on the final call, no 500 error
 def test_raise_error_if_params_passed_but_signature_omitted(self):
     with self.assertRaises(shopify.ValidationException):
         session = shopify.Session("testshop.myshopify.com")
         token = session.request_token({
             'code': 'any_code',
             'foo': 'bar',
             'timestamp': '1234'
         })
示例#25
0
def _delete_customers():
    shop_session = sfy.Session(session['shop_url'], '2019-04', session['token'])
    # activate the shopify session to use resources.
    sfy.ShopifyResource.activate_session(shop_session)
    customers = Customer.query.all()
    for c in customers:
        delete_customer(c.gid)
    return(jsonify('ok')) #this makes the browser happy on the final call, no 500 error
示例#26
0
def delete_a_customer(customer_id):
    session = shopify.Session(shop_url, api_version, access_token)
    shopify.ShopifyResource.activate_session(session)
    try:
        customer = shopify.Customer().find(customer_id)
        customer.destroy()
    except:
        print("Failed to delete")
示例#27
0
def initialize_shopify_client():
    api_key = Context.config['api_key']
    shop = Context.config['shop']
    version = '2021-04'
    session = shopify.Session(shop, version, api_key)
    shopify.ShopifyResource.activate_session(session)
    # Shop.current() makes a call for shop details with provided shop and api_key
    return shopify.Shop.current().attributes
示例#28
0
 def test_raise_error_if_params_passed_but_signature_omitted(self):
     with self.assertRaises(shopify.ValidationException):
         session = shopify.Session("testshop.myshopify.com", "unstable")
         token = session.request_token({
             "code": "any_code",
             "foo": "bar",
             "timestamp": "1234"
         })
 def _session_from_config(cls, config):
     session = shopify.Session(
         config.get("domain"),
         config.get("api_version", cls._default_api_version))
     session.protocol = config.get("protocol", "https")
     session.api_key = config.get("api_key")
     session.token = config.get("password")
     return session
示例#30
0
 def init_api_shopify(self):
     for item in self:
         # session
         session = shopify.Session(item.url, '2020-01',
                                   item.shopify_access_token)
         shopify.ShopifyResource.activate_session(session)
     # return
     return session