order fulfillment in shopify with shopify API and python

87 Views Asked by At

please I want to update some orders in the store of shopify partner using API.

what i want is to change the status of the order from "unfulfilled" to "fulfilled" and to to update or to post the tracking information including the tracking number and the name of the carrier company (shipping company). Also, i want to include the link where the order can be tracked.

I want to do this using python.

any suggestions please, thank you so much for your suggestion and codes.

Best Regards,

here is the code i used.

    `import shopify
     import json

    `# Initialize Shopify API with your credentials
     shop_url = 'xxxxxxxx.myshopify.com'
     api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
     password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
     shopify.ShopifyResource.set_site(f'https://{api_key}:{password}@{shop_url}/admin')

    # Load the orders from the JSON file
    with open('PEBestellungen.json', 'r') as file:
    order_list = json.load(file)

    # Process each order and update fulfillment status
    for order_data in order_list:
    # Use the correct key 'id' to access the order ID
    order_id = order_data['id']
    
    # Update order fulfillment status
    # Example: Set fulfillment status to 'fulfilled'
    order = shopify.Order.find(order_id)
    
    # Check if the order is already fulfilled or partially fulfilled
    if order.fulfillment_status is None or order.fulfillment_status == 'partial':
        # Create a fulfillment for the entire order
        fulfillment = shopify.Fulfillment.create({
            'order_id': order_id,
            # You need to specify the location ID here if required
            'tracking_numbers': ['AAXXXXXXXXXBE'],  # Replace with actual tracking numbers
            'tracking_company': 'XXXXXXX',  # Replace with actual carrier information
            'notify_customer': True  # Set to False if you don't want to notify the customer
        })
        fulfillment.save()

     print("Order fulfillment status and tracking information updated successfully.")
``

and this is the output i receive when i run the above code : 

--------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:286, in Connection._open(self, method, path, headers, data)
    285 try:
--> 286     http_response = self._handle_error(self._urlopen(request))
    287 except urllib.error.HTTPError as err:

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:316, in Connection._urlopen(self, request)
    315 if _urllib_has_timeout():
--> 316   return urllib.request.urlopen(request, timeout=self.timeout)
    317 else:

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:216, in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    215     opener = _opener
--> 216 return opener.open(url, data, timeout)

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:525, in OpenerDirector.open(self, fullurl, data, timeout)
    524     meth = getattr(processor, meth_name)
--> 525     response = meth(req, response)
    527 return response

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:634, in HTTPErrorProcessor.http_response(self, request, response)
    633 if not (200 <= code < 300):
--> 634     response = self.parent.error(
    635         'http', request, response, code, msg, hdrs)
    637 return response

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:563, in OpenerDirector.error(self, proto, *args)
    562 args = (dict, 'default', 'http_error_default') + orig_args
--> 563 return self._call_chain(*args)

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:496, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
    495 func = getattr(handler, meth_name)
--> 496 result = func(*args)
    497 if result is not None:

File ~\AppData\Local\anaconda3\Lib\urllib\request.py:643, in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs)
    642 def http_error_default(self, req, fp, code, msg, hdrs):
--> 643     raise HTTPError(req.full_url, code, msg, hdrs, fp)

HTTPError: HTTP Error 401: Unauthorized

During handling of the above exception, another exception occurred:

UnauthorizedAccess                        Traceback (most recent call last)
Cell In[7], line 21
     17 order_id = order_data['id']
     19 # Update order fulfillment status
     20 # Example: Set fulfillment status to 'fulfilled'
---> 21 order = shopify.Order.find(order_id)
     23 # Check if the order is already fulfilled or partially fulfilled
     24 if order.fulfillment_status is None or order.fulfillment_status == 'partial':
     25     # Create a fulfillment for the entire order

File ~\AppData\Local\anaconda3\Lib\site-packages\shopify\base.py:196, in ShopifyResource.find(cls, id_, from_, **kwargs)
    193 @classmethod
    194 def find(cls, id_=None, from_=None, **kwargs):
    195     """Checks the resulting collection for pagination metadata."""
--> 196     collection = super(ShopifyResource, cls).find(id_=id_, from_=from_, **kwargs)
    197     if isinstance(collection, Collection) and "headers" in collection.metadata:
    198         return PaginatedCollection(collection, metadata={"resource_class": cls}, **kwargs)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\activeresource.py:384, in ActiveResource.find(cls, id_, from_, **kwargs)
    370 """Core method for finding resources.
    371 
    372 Args:
   (...)
    381     Error: On any other errors.
    382 """
    383 if id_:
--> 384     return cls._find_single(id_, **kwargs)
    386 return cls._find_every(from_=from_, **kwargs)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\activeresource.py:487, in ActiveResource._find_single(cls, id_, **kwargs)
    485 prefix_options, query_options = cls._split_options(kwargs)
    486 path = cls._element_path(id_, prefix_options, query_options)
--> 487 return cls._build_object(cls.connection.get_formatted(path, cls.headers),
    488                          prefix_options)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:340, in Connection.get_formatted(self, path, headers)
    331 def get_formatted(self, path, headers=None):
    332     """Perform an HTTP get request and return the formatted response.
    333 
    334     Args:
   (...)
    338         The resource as a dict.
    339     """
--> 340     return self.format.decode(self.get(path, headers).body)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:329, in Connection.get(self, path, headers)
    320 def get(self, path, headers=None):
    321     """Perform an HTTP get request.
    322 
    323     Args:
   (...)
    327         A Response object.
    328     """
--> 329     return self._open('GET', path, headers=headers)

File ~\AppData\Local\anaconda3\Lib\site-packages\shopify\base.py:23, in ShopifyConnection._open(self, *args, **kwargs)
     21 self.response = None
     22 try:
---> 23     self.response = super(ShopifyConnection, self)._open(*args, **kwargs)
     24 except pyactiveresource.connection.ConnectionError as err:
     25     self.response = err.response

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:288, in Connection._open(self, method, path, headers, data)
    286     http_response = self._handle_error(self._urlopen(request))
    287 except urllib.error.HTTPError as err:
--> 288     http_response = self._handle_error(err)
    289 except urllib.error.URLError as err:
    290     raise Error(err, url)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyactiveresource\connection.py:415, in Connection._handle_error(self, err)
    413     raise BadRequest(err)
    414 elif err.code == 401:
--> 415     raise UnauthorizedAccess(err)
    416 elif err.code == 403:
    417     raise ForbiddenAccess(err)

UnauthorizedAccess: Response(code=401, body="b'{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}'", headers={'Date': 'Mon, 29 Jan 2024 15:15:13 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'X-Sorting-Hat-PodId': '263', 'X-Sorting-Hat-ShopId': '42745987235', 'referrer-policy': 'origin-when-cross-origin', 'x-frame-options': 'DENY', 'x-shopid': '42745987235', 'x-shardid': '263', 'www-authenticate': 'Basic Realm="Shopify API Authentication"', 'strict-transport-security': 'max-age=7889238', 'server-timing': 'processing;dur=119', 'x-shopify-stage': 'production', 'content-security-policy': "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; frame-ancestors 'none'; img-src 'self' data: blob: https:; script-src..................................................................................

0

There are 0 best solutions below