class REQ(): def __init__(self): consumer_admin_key = "ck_7e00fe275804399bba0baf6af01832ac7e1adb5f" consumer_admin_secret = "cs_634013c0b6d035d47629da55faf2adf37cde4329" self.wcapi = API(url="http://127.0.0.1/akstore", consumer_key=consumer_admin_key, consumer_secret=consumer_admin_secret, version="v3") def test_api(self): print(self.wcapi.get("").json()) def post(self, endpoint, data): result = self.wcapi.post(endpoint, data) rs_code = result.status_code rs_body = result.json() rs_url = result.url return (rs_code, rs_body, rs_url) def get(self, endpoint): result = self.wcapi.get(endpoint) rs_code = result.status_code rs_body = result.json() rs_url = result.url return (rs_code, rs_body, rs_url) def wc_cust_delete(self, id): result = self.wcapi.delete("customers/" + str(id) + "?force=true") return (result).json() def wc_product_delete(self, id): result = self.wcapi.delete("products/" + str(id) + "?force=true") return (result).json()
def main(): #connecting to your woocommerce REST API wcapi = API( url="https://your_wordpress_domain.com", consumer_key="ck_5e55eb1f8b3po06e47f16bdd733980dc9196a7a6",# your WooCommerce API key this one won't work consumer_secret="cs_4aa7999999262fa19224451945ed7f58fa6ac494",# your WooCommerce API secret this one won't work wp_api=True, query_string_auth=True, version="wc/v3" ) # for performance we load all the products in a list products = [] for x in range(4): p = wcapi.get(f"products?per_page=300&offset={300*x}").json() products.extend(p) # We in each product and use the search engine to find if any updates in the prices for x,product in enumerate(products): name = product['name'] price = product['regular_price'] n_name, n_price, score = get_new_name_and_price(name) try: score = int(score) except: score = 0 if n_name == None or score < 13: wcapi.delete(f"products/{product['id']}", params={"force": True}).json() print(f'{x} / {score} - Deleted {name} ~ {n_name}') if score < 13 and n_name != None: data = { "regular_price": str(n_price), "name": n_name, "status": "publish", } wcapi.post(f"products", data).json() print(f'Created new version of {n_name}') else: try: if float(price) != float(n_price): data = { "regular_price": str(n_price), "name": n_name, "status": "publish", } wcapi.put(f"products/{product['id']}", data).json() print(f'{x} / {score} - Updated {name} ~ {price}') print(f'{x} / {score} - Updated {n_name} ~ {n_price}') else: print('Pass') except Exception as e: print(e)
def delete_request(path, settings=None): if not settings: settings = get_woocommerce_settings() wcapi = API(url=settings['woocommerce_url'], consumer_key=settings['api_key'], consumer_secret=settings['password'], wp_api=True, version="wc/v3") r = wcapi.delete(path) r.raise_for_status() return r.json()
table = at.get(TABLE_NAME, filter_by_formula= None) ### Record: dict for each entry in Table for idx, record in enumerate(table['records']): print("Parsing entry {} of {}".format(idx+1, len(table["records"]))) #TODO filter by time, don't update everything edit_time = record['fields']['Last modified time'] timestamp = dateutil.parser.parse(edit_time) last_update_time = datetime.now() #if timestamp < last_update_time: #delete the old version of the product woocommerce_ID = record['fields']['woocommerce_ID'] wcapi.delete(f"products/{woocommerce_ID}", params={"force": True}).json() product = airtable_record_to_json(at, record) response = wcapi.post("products", product).json() print(product['name']) #def update(self, table_name, record_id, data): # if check_string(table_name) and check_string(record_id): # url = posixpath.join(table_name, record_id) # payload = create_payload(data) # return self.__request('PATCH', url, # # self.headers.update({'Content-type': 'application/json'}) # r = requests.request(method, # posixpath.join(self.base_url, url), # params=params,
class WooCommerceShim(Database): """ Contains various methods for interacting with the WooCommerce API. These methods will do things such as adding new products, and removing sold products. """ def __init__(self, *args, **kwargs): super(WooCommerceShim, self).__init__(*args, **kwargs) # Setup logging self.log = logging.getLogger(__name__) self.log.setLevel(os.environ.get('log_level', 'INFO')) self.log.addHandler(LOG_HANDLER) self.api = WCAPI(url=os.environ.get('woo_url', False), consumer_key=os.environ.get('woo_key', False), consumer_secret=os.environ.get('woo_secret', False)) self.wp_api = WPAPI(url=os.environ.get('woo_url', False), api='wp-json', version='wp/v2', wp_user=os.environ.get('wordpress_user', False), wp_pass=os.environ.get('wordpress_app_password', False), basic_auth=True, user_auth=True, consumer_key=False, consumer_secret=False) mapping_path = os.environ.get( 'category_mapping', 'database/ebay-to-woo-commerce-category-map.json') try: with open(mapping_path, 'r') as mapping_file: self.category_mapping = json.load(mapping_file) except IOError: self.category_mapping = None def __does_image_exist_on_woocommerce(self, slug): """ Searches the Wordpress media library for any files that have a URL `slug` that matches the one provided Returns True if the file exists, and False otherwise This method is unreliable! Duplicates are basically guarenteed to happen... """ self.log.info('Checking if a file has a slug matching: %s' % (slug)) result = self.wp_api.get('/media?slug=%s' % (slug)).json() if len(result) == 0: return False return True def __divide_into_chunks(self, iterable, chunk_size=100): """ Used to make bulk requests via the API, which limits the amount of products to change at once to 100 `iterable` is something that can be iterated over, be it a list or a range. When a range, you must wrap the output of this method in `list()` `chunk_size` is optional, and defines how many products to change per request. The default of 100 is the maximum that the API will allow Returns the `iterable` containing as many items as are in the `chunk_size` """ for i in range(0, len(iterable), chunk_size): yield iterable[i:i + chunk_size] def __search_map(self, value, field): """ Uses List Comprehension to search for the `value` in the `field`. Normal usage would be similar to `self.__search_map(ebay_category_id, 'ebay_ids')` Returns an integer, which is the first matching Woo Commerce ID for the selected `value` (in the case that one ebay category is mapped to multiple woo commerce categories) When a matching category can't be found, this method will call itself to search for the "Uncategorized" `value` on the "wc-name" `field` """ try: mapped = [ key for key in self.category_mapping if value in key[field] ] return int(mapped[0]['wc-id']) except IndexError: # Couldn't find it, return the uncategorized id return self.__search_map('Uncategorized', 'wc-name') def does_product_exist(self, item_id): """ Determines if the product with the `item_id` has already been uploaded to WooCommerce, by checking for the truthyness of `post_id` """ data = self.db_get_product_data(item_id) if data.get('post_id') is not None: return True return False def get_mapped_category_id(self, ebay_category_id): """ Determines if the user provided a category mapping, and if so returns an integer, which is the Woo Commerce category id that is mapped to the `ebay_category_id` (or the Uncategorized category id if a mapping can not be found) In the case that the user has not provided a category mapping, this method returns None """ if self.category_mapping is not None: return self.__search_map(ebay_category_id, 'ebay_ids') return None def download_product_images_from_ebay(self, item_id): """ Downloads all of the images for a provided `item_id` and returns a dictionary containing the image name, mime type, and bytes-like object for the raw images The image URLs come from the database table `item_metadata`, which is populated when `self.__get_item_metadata()` runs """ count = 0 return_images = list() image_urls = self.db_get_product_image_urls(item_id) image_urls_count = len(image_urls) if image_urls_count > 0: self.log.info("Found %d image URLs for: %s" % (image_urls_count, item_id)) for image in image_urls: url = image.get('value', '') if image.get('post_id') is not None: self.log.warning( "We've already uploaded %s, skipping download" % (url)) continue self.log.info("Downloading %s" % (url)) req = requests.get(url) if req.content: mime_type = req.headers.get('Content-Type', '') slug = '%s-%d' % (item_id, count) extension = mime_type.split('/')[1] filename = '%s.%s' % (slug, extension) if 'image' not in mime_type: msg = "%d didn't get an image somehow. Content type was: %s" self.log.error(msg % (item_id, mime_type)) continue return_images.append( Image(slug=slug, ebay_url=url, name=filename, mime_type=mime_type, data=req.content)) # self.log.info("Image %s downloaded" % (filename)) if count < image_urls_count: self.log.debug( "Waiting a quarter second until next download") time.sleep(0.25) else: self.log.error( "No content returned. Is %s reachable in a browser?" % (url)) count += 1 else: self.log.warning("No Image URLs found for item: %s" % (item_id)) return return_images def upload_image_to_woocommerce(self, image, post_id): """ Uploads the provided `image` to wordpress, and returns the response `image` is a dictionary containing the following keys: `name` - This is the destination file name, including extension `type` - This is the MIMETYPE of the image, usually derived from the extension `data` - This is a bytes-like object representing the entire image. We get this from dowloading an image directly from Ebay's servers and temporarily storing it in memory `post_id` is the post in which to attach the image to. This is returned in the response from `self.create_product()` Returns either a string containing the URL the image can be found at, or False if the image fails to be uploaded """ self.log.info("Uploading %s to wordpress" % (image.name)) endpoint = '/media?post=%d' % (post_id) headers = { 'cache-control': 'no-cache', 'content-disposition': 'attachment; filename=%s' % (image.name), 'content-type': '%s' % (image.mime_type) } # Don't upload a duplicate image if it was uploaded in the past if self.__does_image_exist_on_woocommerce(image.slug): self.log.warning( "Image %s already exists on wordpress. Not uploading again" % (image.name)) return None, None # Upload the image response = self.wp_api.post(endpoint, image.data, headers=headers) try: image_id = response.json().get('id') url = response.json().get('guid', dict).get('raw') self.log.debug("Uploaded %s to %s" % (image.name, url)) return image_id, url except AttributeError: self.log.error('Could not upload %s' % image.name) return None, None def upload_product_images(self, item_id): """ With the provided `item_id`, the database is searched for the post id (set during `create_product`) When the post_id is found, it will be used to download the images for that product from ebay, and then upload the images """ post_id = self.db_woo_get_post_id(item_id) gallery = [] if post_id is not None: for image in self.download_product_images_from_ebay(item_id): image_id, url = self.upload_image_to_woocommerce( image, post_id) if image_id and url: self.db_metadata_uploaded(image_id, item_id) gallery.append({'id': image_id}) # Add the images to the gallery self.api.put('products/%d' % (post_id), {'images': gallery}).json() else: self.log.warning('The product %d has not yet been uploaded' % (item_id)) return self def create_product(self, item_id): """ Pulls the product related to the `item_id` out of the database and uploads it to WooCommerce Returns the result as JSON """ attributes = list() attributes_to_upload = list() self.log.info('Creating a WooCommerce product from ebay id: %s' % (item_id)) if self.does_product_exist(item_id): self.log.warning( 'Product with item id %d already exists, skipping' % (item_id)) return self product = self.db_get_product_data(item_id) attributes = self.db_get_all_product_metadata(item_id) # Strip out any pictures attributes = [ attribute for attribute in attributes if attribute['key'] != 'picture_url' ] # Format the attributes in a way that WooCommerce is expecting for index, attribute in enumerate(attributes): attributes_to_upload.append({ 'name': attribute['key'], 'options': [attribute['value']], 'visible': True, 'variation': True, 'position': index, }) upload_data = { 'name': product['title'], 'type': 'simple', 'status': 'publish', 'short_description': product['condition_description'], 'description': DEFAULT_DESCRIPTION, 'sku': product['sku'], # 'attributes': attributes_to_upload, # 'default_attributes': attributes_to_upload, } # Add the category id category_id = self.get_mapped_category_id(product.get( 'category_id', 0)) if category_id is not None: upload_data['categories'] = [{'id': category_id}] res = self.api.post('products', upload_data).json() self.log.debug(res) if res.get('id', False): self.db_product_uploaded(res['id'], item_id) else: # Invalid or duplicate sku if res.get('code') == 'product_invalid_sku': if res.get('data') and res['data'].get('resource_id'): new_post_id = res['data']['resource_id'] self.log.warning( 'The SKU for %s already exists for %s. Updating.' % (new_post_id, item_id)) self.db_product_uploaded(new_post_id, item_id) else: self.log.error('Unable to retrive product_id') self.log.debug(res) self.log.debug(upload_data) return self def delete_product_images(self, item_id): """ With the provided `item_id`, an API request will be made to WooCommerce to identify all images associted with it. Then, it will delete each of those images. """ # This feature has not been implemented. # Delete media through wordpress directly pass def delete_product(self, item_id): """ With the provided `item_id`, an API request will be made to WooCommerce to force delete the item The `item_id` is supplied by the queue, which gets them from `db.db_get_inactive_uploaded_item_ids()` When an item is force deleted, it will not appear in the "Trash" Returns the response as a dictionary or None if there is no post id """ post_id = self.db_woo_get_post_id(item_id) if post_id is not None: self.log.info('Deleting %d from WooCommerce' % (item_id)) try: response = self.api.delete('products/%d' % (post_id), params={ 'force': True }).json() except TypeError: self.log.error("Got unexpected response type: %s" % (str(response))) return None self.delete_product_images(post_id) status_code = response.get('data', dict).get('staus', 500) if status_code == 404: self.log.warning("Product was already deleted") elif status_code < 300 and status_code > 199: self.log.info('Product deleted') else: self.log.debug(response) return response return None def delete_all_products_in_range(self, id_range, chunk_size=100): """ With a provided `id_range`, which is expected to be a `range` or `list` type, multiple bulk requests will be made to the Woo Commerce API to delete those items. When `id_range` is of type(range), your ending ID needs to be the last ID to delete + 1 Returns None """ self.log.info('Deleting products from %d to %d' % (id_range[0], id_range[-1])) # The API says that it supports chunks up to 100 items, but in testing # it would always time out, even if it successfully deleted the items # with any chunk size greater than or equal to 50 for chunk in self.__divide_into_chunks(id_range, chunk_size): post_ids = list(chunk) data = {'delete': post_ids} self.api.post('products/batch', data) self.log.info('Deleted ids %s' % (post_ids)) for post_id in post_ids: self.delete_product_images(post_id) def try_command(self, command, data): """ Wrapper for running methods. Verifies that we support the method, raising a NameError if not and then runs the method specified in the `command` argument in a try, except statement `command` is a string that is inside `__available_commands` `data` is dependent on the type of command that is being ran. In most instances, it is an integer containing the ebay ItemID. With the `delete_all_products` command, it is either a range or a list containing the post ids for existing products """ __available_commands = [ 'create_product', 'delete_product', 'upload_images', 'delete_all_products', ] err_msg = "Command %s is unrecognized. Supported commands are: %s" % ( command, ', '.join(__available_commands)) if command not in __available_commands: self.log.exception(err_msg) raise NameError(err_msg) try: if command == 'create_product': return self.create_product(data) elif command == 'delete_product': return self.delete_product(data) elif command == 'upload_images': return self.upload_product_images(data) elif command == 'delete_all_products': return self.delete_all_products_in_range(data) else: self.log.exception(err_msg) raise NameError(err_msg) # The several kinds of timeout exceptions that are normally returned by the API except (timeout, ReadTimeoutError, requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): self.log.warning( 'The Previous request Timed Out. Waiting 5s before retrying') time.sleep(5) self.try_command(command, data)
class WooApiHandler: def __init__(self): self.wcapi = API( # WC Office url=cred.url, consumer_key=cred.consumer_key, consumer_secret=cred.consumer_secret, version=cred.version, timeout=cred.timeout) self.products_uploaded = 0 self.products_updated = 0 self.PRODUCT_UPLOAD_BATCH_SIZE = 30 self.PRODUCT_DOWNLOAD_BATCH_SIZE = 100 def get_sub_categories(self, parent_id): """CHANGE WOO PAGE""" params = {"per_page": "100", "parent": parent_id} get_sub_categories_response = self.wcapi.get("products/categories", params=params).json() remote_sub_categories = [] count = 0 for item in get_sub_categories_response: remote_sub_categories.append(self.create_remote_category(item)) count += 1 return remote_sub_categories def create_remote_category(self, item): #print(json.dumps(item, indent=4, sort_keys=True)) category = Category(html.unescape(item['name']), item['id']) category.parent_remote_id = item['parent'] if item['image']: category.image_id = item['image']['id'] else: category.image_id = None #category.print_category(1) return category def get_products(self): remote_products = [] count = 0 page = 1 while True: params = { "per_page": self.PRODUCT_DOWNLOAD_BATCH_SIZE, "page": page } get_products_response = self.wcapi.get("products", params=params).json() #TEST PRINT #print(json.dumps(get_products_response, indent=4, sort_keys=True)) for woo_product_item in get_products_response: remote_products.append( self.create_remote_product(woo_product_item)) count += 1 page += 1 print("DOWLOADED " + str(count) + " PRODUCTS") if len(get_products_response) < self.PRODUCT_DOWNLOAD_BATCH_SIZE: break print(str(count) + " TOTAL PRODUCTS ALREADY ON SITE") return remote_products def create_remote_product(self, woo_product_item): categories = [] for category in woo_product_item['categories']: categories.append(category['id']) remote_category_id = categories[0] remote_image_ids = [] for remote_image in woo_product_item['images']: remote_image_ids.append(remote_image['id']) product_out_price = float(woo_product_item['regular_price']) product_out_price = "{0:.2f}".format(product_out_price) remoteProduct = RemoteProduct( supplier_product_id=woo_product_item['sku'], remote_product_id=woo_product_item['id'], remote_category_id=remote_category_id, product_name=html.unescape(woo_product_item['name']), product_description=html.unescape(woo_product_item['description']), remote_image_ids=remote_image_ids, product_out_price=product_out_price) if woo_product_item['sale_price'] != "": product_discount_price = float(woo_product_item['sale_price']) product_discount_price = "{0:.2f}".format(product_discount_price) remoteProduct.product_discount_price = product_discount_price else: remoteProduct.product_discount_price = "0.0" return remoteProduct def add_category(self, name, pId): data = {"name": name, "display": "default", "parent": pId} response = self.wcapi.post("products/categories", data).json() # print(json.dumps(response, indent=4, sort_keys=True)) if "id" in response.keys(): print(" Uploaded: " + name + " ---> " + str(response['id'])) return response['id'] else: print("Not Uploaded") return "" def upload_products(self, products, update): """ When batch upload fails try to upload single products Raise batch size to 100 """ if update: self.print_title("updating products") else: self.print_title("uploading products") uploaded_products = [] while products: product_batch = [] for i in range(self.PRODUCT_UPLOAD_BATCH_SIZE): if products: product_batch.append(products.pop()) else: break data = {} create = [] for product in product_batch: if not product.supplier_product_id == "148902": if update: create.append(self.create_woo_update_product(product)) else: create.append(self.create_woo_product(product)) if update: data['update'] = create else: data['create'] = create #try: batch_upload_response = self.wcapi.post("products/batch", data).json() if "create" or "update" in batch_upload_response.keys(): uploaded_products.extend( self.create_remote_products(batch_upload_response)) else: print( json.dumps(batch_upload_response, indent=4, sort_keys=True)) #except: #print("An exception occurred") return uploaded_products def create_remote_products(self, batch_upload_response): #print(json.dumps(batch_upload_response, indent=4, sort_keys=True)) #print(batch_upload_response['create']) uploaded_products = [] if "create" in batch_upload_response.keys(): woo_products = batch_upload_response['create'] for woo_product in woo_products: uploaded_products.append( self.create_remote_product(woo_product)) self.products_uploaded += 1 #for uploaded_product in uploaded_products: # uploaded_product.print_remote_product() print(str(self.products_uploaded) + " TOTAL PRODUCTS UPLOADED") if "update" in batch_upload_response.keys(): woo_products = batch_upload_response['update'] for woo_product in woo_products: uploaded_products.append( self.create_remote_product(woo_product)) self.products_updated += 1 # for uploaded_product in uploaded_products: # uploaded_product.print_remote_product() print(str(self.products_updated) + " TOTAL PRODUCTS UPDATED") return uploaded_products def create_woo_update_product(self, product): woo_product = {} woo_product['id'] = product.remote_product_id if product.product_name: woo_product['name'] = product.product_name if product.product_description: woo_product['description'] = product.product_description woo_product['short_description'] = product.product_description woo_product['regular_price'] = product.product_out_price if float(product.product_discount_price) != 0.0: woo_product['sale_price'] = product.product_discount_price else: woo_product['sale_price'] = "" return woo_product def create_woo_product(self, product): woo_product = {} cat_id = product.remote_category_id # print(catId) woo_product['sku'] = product.supplier_product_id woo_product['categories'] = [{"id": cat_id}] woo_product['name'] = product.product_name woo_product['type'] = "simple" woo_product['regular_price'] = product.product_out_price if float(product.product_discount_price) != 0.0: woo_product['sale_price'] = product.product_discount_price else: woo_product['sale_price'] = "" woo_product['description'] = product.product_description woo_product['short_description'] = product.product_description woo_product['attributes'] = product.product_specification woo_product['images'] = product.product_images return woo_product def update_category_image(self, category, img_ref): data = {"image": {"id": img_ref}} request = "products/categories/" + str(category.remote_id) update_category_image_response = self.wcapi.put(request, data).json() #print(json.dumps(update_category_image_response, indent=4, sort_keys=True)) def update_category_display(self, category, level): if level == 1 or level == 2: data = {"display": "subcategories"} print(category.name + " ---> subcategories") else: data = {"display": "default"} print(category.name + " ---> default") request = "products/categories/" + str(category.remote_id) update_category_display_response = self.wcapi.put(request, data).json() def force_delete_all_products(self): params = {"per_page": "100"} response_get = self.wcapi.get("products", params=params).json() products_to_delete = [d['id'] for d in response_get] params = {"force": "True"} for p in products_to_delete: print(p) response_delete = self.wcapi.delete("products/" + str(p), params=params).json() def delete_all_products(self): count = 0 while True: params = {"per_page": "100"} response_get = self.wcapi.get("products", params=params).json() products_to_delete = [d['id'] for d in response_get] data = {'delete': products_to_delete} response_delete = self.wcapi.post("products/batch", data).json() count += len(products_to_delete) if len(products_to_delete) < 100: break else: print("Deleted products: " + str(count)) print("") print("Deleted products: " + str(count)) def delete_all_categories(self): count = 0 while True: params = {"per_page": "100"} response_get = self.wcapi.get("products/categories", params=params).json() categories_to_delete = [d['id'] for d in response_get] data = {'delete': categories_to_delete} response_delete = self.wcapi.post("products/categories/batch", data).json() count += len(categories_to_delete) if len(categories_to_delete) < 100: break else: print("Deleted categories: " + str(count)) print("") print("Deleted categories: " + str(count)) def print_title(self, title): print("") print("----------") print("") print(title.upper() + ":") print("")
class WooCommerceDataAccess: """ Class for integrating WooCommerce. Please refer to documentations. https://woocommerce.github.io/woocommerce-rest-api-docs/ """ def __init__(self, url, consumer_key, consumer_secret): self.wcapi = API( url=url, consumer_key=consumer_key, consumer_secret=consumer_secret, version="wc/v3", timeout=10 ) def get_all_products(self): """This API helps you to view all the products.""" page = 1 output = [] while True: try: products = self.wcapi.get("products", params={'per_page': 10, 'page': page}).json() page += 1 if len(products) == 0: break for product in products: if product["stock_quantity"] is None: product["stock_quantity"] = 0 output.append(product) except Exception: # db.create_logs("WooCommerce", "Error", f"Products timeout error, retrying in {RETRY_DELAY}s...") print(f"[WOOCOMMERCE] Timeout error, retrying in {RETRY_DELAY}s...") time.sleep(RETRY_DELAY) return output def get_product(self, id): """This API lets you retrieve and view a specific product by ID.""" try: return self.wcapi.get(f"products/{id}").json() except Exception as e: raise e def update_product(self, id, data): """This API lets you make changes to a product.""" try: self.wcapi.put(f"products/{id}", data).json() except Exception as e: raise e def delete_product(self, id): """This API helps you delete a product.""" try: self.wcapi.delete(f"products/{id}", params={"force": True}) except Exception as e: raise e def get_all_variations(self, product_id): """This API helps you to view all the product variations.""" page = 1 output = [] while True: try: variations = self.wcapi.get(f"products/{product_id}/variations", params={'per_page': 10, 'page': page}).json() page += 1 if len(variations) == 0: break for variation in variations: if variation["stock_quantity"] is None: variation["stock_quantity"] = 0 output.append(variation) except Exception: #output.clear() #db.create_logs("WooCommerce", "Error", f"Variations timeout error, retrying in {RETRY_DELAY}s...") print(f"[WOOCOMMERCE] Timeout error, retrying in {RETRY_DELAY}s...") time.sleep(RETRY_DELAY) return output def get_variation(self, product_id, id): """This API lets you retrieve and view a specific product variation by ID.""" try: return self.wcapi.get(f"products/{product_id}/variations/{id}").json() except Exception as e: raise e def update_variation(self, product_id, id, data): """This API lets you make changes to a product variation.""" try: self.wcapi.put(f"products/{product_id}/variations/{id}", data) except Exception as e: raise e def delete_variation(self, product_id, id): """This API helps you delete a product variation.""" try: self.wcapi.delete(f"products/{product_id}/variations/{id}", params={"force": True}) except Exception as e: raise e def get_all_orders(self, status): """This API helps you to view all the orders.""" page = 1 output = [] while True: try: orders = self.wcapi.get("orders", params={'per_page': 10, 'page': page, 'status': [status]}).json() page += 1 if len(orders) == 0: break for order in orders: output.append(order) except Exception: #output.clear() print(f"[WOOCOMMERCE] Timeout error, retrying in {RETRY_DELAY}s...") time.sleep(RETRY_DELAY) # Fetch english order (Wordpress plugin WPML) page = 1 while True: try: orders = self.wcapi.get("orders", params={'per_page': 10, 'page': page, 'status': [status], 'lang': 'en'}).json() page += 1 if len(orders) == 0: break for order in orders: output.append(order) except Exception: #output.clear() print(f"[WOOCOMMERCE] Timeout error, retrying in {RETRY_DELAY}s...") time.sleep(RETRY_DELAY) return output def get_order(self, id): """This API lets you retrieve and view a specific order.""" try: return self.wcapi.get(f"orders/{id}").json() except Exception as e: print(e) def update_order(self, id, data): """This API lets you make changes to an order.""" try: self.wcapi.put(f"orders/{id}", data) except Exception as e: raise e def delete_order(self, id): """This API helps you delete an order.""" try: self.wcapi.delete(f"orders/{id}", params={"force": True}).json() except Exception as e: raise e def get_all_customers(self): """This API helps you to view all the customers.""" try: return self.wcapi.get(f"customers").json() except Exception as e: raise e def get_customer(self, id): """This API lets you retrieve and view a specific customer by ID.""" try: return self.wcapi.get(f"customers/{id}").json() except Exception as e: raise e
class Wc: def __init__(self, url, consumer_key, consumer_secret): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(url, str) assert isinstance(consumer_key, str) assert isinstance(consumer_secret, str) self.wcapi = API( url=url, consumer_key=consumer_key, consumer_secret=consumer_secret, wp_api=True, version="wc/v2", verify_ssl=False, query_string_auth=True, timeout= 30, # requires especially for WooCommerce connects with Jetpack ) def getGeneralSetting(self): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") try: r = self.wcapi.get("settings/general") return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(str(exp)) logger.error(traceback.format_exc()) raise exp def getProductsList(self, items_per_page, page_no, category_id=None, tag_id=None): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(items_per_page, int) assert isinstance(page_no, int) url = "products?per_page={0}&page={1}".format(items_per_page, page_no) if category_id is not None: url += "&category=" + str(category_id) if tag_id is not None: url += "&tag=" + str(tag_id) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(str(exp)) logger.error(traceback.format_exc()) raise exp def getTagBySlug(self, tag_name): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(tag_name, str) url = "products/tags?slug={0}".format(tag_name) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(str(exp)) logger.error(traceback.format_exc()) raise exp def getProductDetail(self, product_id): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(product_id, str) url = "products/{0}".format(product_id) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getProductVariations(self, product_id, item_per_page, page_no): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(product_id, str) assert isinstance(item_per_page, int) assert isinstance(page_no, str) url = "products/{0}/variations?per_page={1}&page={2}".format( product_id, item_per_page, page_no) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getProductDetailByIds(self, product_ids): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(product_ids, list) url = "products?include=" + ",".join(product_ids) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getProductCategoriesList(self, items_per_page, page_no): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(items_per_page, int) assert isinstance(page_no, int) url = "products/categories?per_page={0}&page={1}".format( items_per_page, page_no) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def searchProductsByName(self, items_per_page, page_no, name): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(items_per_page, int) assert isinstance(page_no, int) kw_url = quote(name) # print("kw_url=" + kw_url) url = "products?search={0}&status=publish&per_page={1}&page={2}".format( kw_url, items_per_page, page_no) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def searchProductsByPriceRange(self, items_per_page, page_no, min_price, max_price): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(items_per_page, int) assert isinstance(page_no, int) assert min_price is not None or max_price is not None # print("kw_url=" + kw_url) # url = "products?search={0}&status=publish&per_page={1}&page={2}".format(kw_url, items_per_page, page_no) url = "products?" if min_price is not None: url += "min_price=" + min_price + "&" if max_price is not None: url += "max_price=" + max_price + "&" url += "status=publish&per_page={0}&page={1}".format( items_per_page, page_no) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def createOrder(self, iinfo, items): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert iinfo is not None assert items is not None assert iinfo["billing"] is not None assert iinfo["billing"]["first_name"] is not None assert iinfo["billing"]["last_name"] is not None assert iinfo["billing"]["email"] is not None assert iinfo["billing"]["phone"] is not None assert iinfo["billing"]["address1"] is not None # assert iinfo["billing"]["address2"] is not None assert iinfo["billing"]["city"] is not None assert iinfo["billing"]["state"] is not None # assert iinfo["billing"]["postal"] is not None assert iinfo["billing"]["country"] is not None assert iinfo["shipping"] is not None assert iinfo["shipping"]["first_name"] is not None assert iinfo["shipping"]["last_name"] is not None assert iinfo["shipping"]["address1"] is not None # assert iinfo["shipping"]["address2"] is not None assert iinfo["shipping"]["city"] is not None assert iinfo["shipping"]["state"] is not None # assert iinfo["shipping"]["postal"] is not None assert iinfo["shipping"]["country"] is not None assert isinstance(items, list) for item in items: assert item["product_id"] != 0 assert item["qty"] is not None assert item["unit_price"] is not None # map to WooCommerce order properties # http://woocommerce.github.io/woocommerce-rest-api-docs/#create-an-order postData = { "set_paid": False, "prices_include_tax": False, "billing": { "first_name": iinfo["billing"]["first_name"], "last_name": iinfo["billing"]["last_name"], "address_1": iinfo["billing"]["address1"], # "address_2": iinfo["billing"]["address2"], "city": iinfo["billing"]["city"], "state": iinfo["billing"]["state"], # "postcode": iinfo["billing"]["postal"], "country": iinfo["billing"]["country"], "email": iinfo["billing"]["email"], "phone": iinfo["billing"]["phone"] }, "shipping": { "first_name": iinfo["shipping"]["first_name"], "last_name": iinfo["shipping"]["last_name"], "address_1": iinfo["shipping"]["address1"], # "address_2": iinfo["shipping"]["address2"], "city": iinfo["shipping"]["city"], "state": iinfo["shipping"]["state"], # "postcode": iinfo["shipping"]["postal"], "country": iinfo["shipping"]["country"], "email": iinfo["shipping"]["email"], "phone": iinfo["shipping"]["phone"] }, "line_items": [] } if "postal" in iinfo["billing"]: postData["billing"]["postal"] = iinfo["billing"]["postal"] if "postal" in iinfo["shipping"]: postData["shipping"]["postal"] = iinfo["shipping"]["postal"] if "address2" in iinfo["billing"]: postData["billing"]["address_2"] = iinfo["billing"]["address2"] if "address2" in iinfo["shipping"]: postData["shipping"]["address_2"] = iinfo["shipping"]["address2"] for item in items: item_obj = { "product_id": item["product_id"], "quantity": int(item["qty"]), "price": float(item["unit_price"]) } postData["line_items"].append(item_obj) url = "orders" try: r = self.wcapi.post(url, postData) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getShippingSettings(self): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") result = [] r = self.wcapi.get("shipping/zones") ship_zones = json.loads(mod_misc.wcCorrectResp(r.text)) for zone in ship_zones: if "_links" in zone: del zone["_links"] r = self.wcapi.get("shipping/zones/" + str(zone["id"]) + "/locations") locations = json.loads(mod_misc.wcCorrectResp(r.text)) for loc in locations: if "_links" in loc: del loc["_links"] r = self.wcapi.get("shipping/zones/" + str(zone["id"]) + "/methods") methods = json.loads(mod_misc.wcCorrectResp(r.text)) methods2 = [] for method in methods: # print("method") # print(method) if method["enabled"]: methods2.append({ "id": method["id"], "title": method["title"], "method_id": method["method_id"], "method_title": method["method_title"], "settings": method["settings"] }) result.append({ "zone": zone, "locations": locations, "methods": methods2 }) return result def getShippingMethods(self): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") result = [] r = self.wcapi.get("shipping_methods") ship_methods = json.loads(mod_misc.wcCorrectResp(r.text)) return ship_methods def updateOrder(self, order_id, update_props): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert order_id is not None assert update_props is not None url = "orders/" + str(order_id) try: r = self.wcapi.put(url, update_props) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getOrder(self, order_id): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert order_id is not None url = "orders/" + str(order_id) try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def deleteOrder(self, order_id): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(order_id, str) url = "orders/" + order_id try: r = self.wcapi.delete(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getPaymentGateways(self): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") url = "payment_gateways" try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def getProductStock(self, product_id): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert isinstance(product_id, str) url = "products/" + product_id try: r = self.wcapi.get(url) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp def updateProductBatch(self, cmd_obj): logger.debug( str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()") assert cmd_obj is not None assert cmd_obj["update"] is not None url = "products/batch" try: r = self.wcapi.post(url, cmd_obj) return json.loads(mod_misc.wcCorrectResp(r.text)) except Exception as exp: logger.error(traceback.format_exc()) raise exp
class Request: def __init__(self): """ http://woocommerce.github.io/woocommerce-rest-api-docs/ """ consumer_key = config['CONNECTION']['consumer_key'] consumer_secret = config['CONNECTION']['consumer_secret'] self.wcapi = API( url=config['CONNECTION']['url'], consumer_key=consumer_key, consumer_secret=consumer_secret, wp_api=True, version="wc/v2" ) def post(self, endpoint, data): """ this method implements POST request to the provided endpoint with provided data in the body. :param endpoint: endpoinf for request :param data: json body :return: lis of elements - response_code, response_body, response_url """ response = self.wcapi.post(endpoint, data) response_code = response.status_code response_body = response.json() response_url = response.url return [response_code, response_body, response_url] def get(self, endpoint): """ this method implements GET request to the provided endpoint. :param endpoint: endpoint for request :return: lis of elements - response_code, response_body, response_url """ response = self.wcapi.get(endpoint) response_code = response.status_code response_body = response.json() response_url = response.url return [response_code, response_body, response_url] def delete(self, endpoint): """ this method implements DELETE request to the provided endpoint :param endpoint: endpoint for request :return: lis of elements - response_code, response_body, response_url """ response = self.wcapi.delete(endpoint) response_code = response.status_code response_body = response.json() response_url = response.url return [response_code, response_body, response_url] def put(self, endpoint, data): """ this method implements PUT request to the provided endpoint with provided data :param data: json body :param endpoint: endpoint for request :return: lis of elements - response_code, response_body, response_url """ response = self.wcapi.put(endpoint, data) response_code = response.status_code response_body = response.json() response_url = response.url return [response_code, response_body, response_url]
class Wooadd(Melif23): def __init__(self, url): Melif23.__init__(self, url) self.wcapi = API( url="https://full23.com", consumer_key="ck_6f0629136b2ced84eedac59bd698b85b85bbb08b", consumer_secret="cs_fb2db037cea70be81fd3ab1c65ff6be90a18960e", wp_api=True, version="wc/v1", verify_ssl=False ) def add_categories(self, category, parent=None): data = { "name": category, "parent": parent } # try: resp = self.wcapi.post("products/categories", data).json() try: return resp['id'] except KeyError: return resp['data'] except: pass def add_main_categories(self, category): return self.add_categories(category) def add_root_categories(self, categories): old_cat = None for cat in categories: r = self.add_categories(cat['name'], old_cat) old_cat = str(r) return old_cat def clean_store(self): while len(self.wcapi.get("products").json()) > 0: items = self.wcapi.get("products").json() for i in items: self.delete_item(i['id']) def delete_item(self, item): self.wcapi.delete("products/" + str(item) + "?force=true") def add_item(self, item): producto = self.get_item(item) cat_id = self.add_root_categories(producto['categories']['root']) data = { "name": producto['title'], "type": "simple", "regular_price": str(producto['price']), "description": "", "short_description": "", "categories": [ { "id": cat_id } ], "images": [ { "src": producto['image'], "position": 0 } ] } return (self.wcapi.post("products", data).json())
# ----------------------------------------------------------------------------- # Product list: # ----------------------------------------------------------------------------- #print(wcapi.get("products").json()) for product in wcapi.get("products").json(): print 'ID %s - SKU %s - Name %s' % ( product['id'], product['sku'], product['name'], ) # ----------------------------------------------------------------------------- # Product delete: # ----------------------------------------------------------------------------- print(wcapi.delete("products/%s" % product_id).json()) # ----------------------------------------------------------------------------- # Product list: # ----------------------------------------------------------------------------- #print(wcapi.get("products").json()) for product in wcapi.get("products").json(): print 'ID %s - SKU %s - Name %s' % ( product['id'], product['sku'], product['name'], ) # ----------------------------------------------------------------------------- #Batch update # -----------------------------------------------------------------------------
print("Parsing entry {} of {}".format(idx+1, len(table["records"]))) #filter by time, don't update everything ### Seems to be not completely perfect yet at_time = record['fields']['Last modified time'] last_update_time = dateutil.parser.parse(at_time) try: woocommerce_ID = record['fields']['woocommerce_ID'] wp_time = wcapi.get("products/{}".format(woocommerce_ID)).json()['date_modified_gmt'] timestamp = dateutil.parser.parse(wp_time +"+00:00") except: timestamp = datetime.now(timezone.utc) if timestamp < last_update_time: #delete the old version of the product wcapi.delete("products/{}".format(woocommerce_ID), params={"force": True}).json() product = airtable_record_to_json(at, record, metadata) response = wcapi.post("products", product).json() #def update(self, table_name, record_id, data): # if check_string(table_name) and check_string(record_id): # url = posixpath.join(table_name, record_id) # payload = create_payload(data) # return self.__request('PATCH', url, # # self.headers.update({'Content-type': 'application/json'}) # r = requests.request(method, # posixpath.join(self.base_url, url), # params=params, # data=payload,