class nlbase: def __init__(self, pub, priv, shopurl): self.pub = pub self.priv = priv self.url = shopurl def connect(self): self.wcapi = API(url=self.url, consumer_key=self.pub, consumer_secret=self.priv, wp_api=True, version="wc/v3") return [True, {}, None] def inputnl(self): headers = { 'Authorization': "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1NTk2NDA0NjgsImV4cCI6MTU1OTY0NDA2OCwicm9sZXMiOlsiUk9MRV9BUEkiXSwidXNlcm5hbWUiOiJhcGkifQ.Zv7v_nDWiHeK-bLHkT3p0GGQ03BaMj5pt-nFWaZZyjkRfQQKjdqNyKXjlZ-GsufPTy9I6LDilP5bGOI_ggKL8AmK5RymEDXp8BAm7Q96mj1fINkj8upu4nx60Zwd3CqCjvZIAC7unV4IsQLA4Q2_Gj2WaFnaeyF8WVxQ91FyAzmOSPD7LmHjUiDkluXNMglukpgYXb0XCOLiEiXLmUZuBqB9s3B4pGeBTFmzHWlXXVvUNIXnJZPua_2LxoeRimPDezTZgyxFn9LMfyjjG__6phgP3xJYAMDkFyf3exovM8D0oj94ZxlRY-zeixcwGf4xVVw69iqTaQtwidE5TS2vc0SYIE1INFn0eNUFk_hLkxYogACFtF3fg3jBqk5j1E7u70L8GQzRuBYpcKnut5nzQTvBDzllp9bKd4L-I0Wu1h9efZWsTz0y6rQITecAEA2nUYAT5UXVkyrWDhrf5E3Yw5uzLMqF-6aEIeDdu4pid4N1yQphjcKCiMqHoGzqldb0wJQUMKbzBszTZ1js7VMFh9HjhYSyifCA3bGzyiy1GKpIRr3gf21UITCH96aZxOVMrSZUGIpWPr9w9dqpSpi69OI-OmlhkYOoVgCSibzh6-Tbq3xz3pQz4TmJMIJTYXh-IuQEjH8r7ZfcYDq3YZ729f9-ZIU1xSLLe8diiyMrQro" } d = requests.get("http://api2.nleurope.com/api/v1/product", headers=headers).text datas = json.loads(d) for d in datas: try: proddata = { "image": str(d[0]["productImage"]), "title": str(d[0]["technicalSheet"]["FR"]["title"]), "flavor": str(d[0]["technicalSheet"]["FR"]["flavor"]), "price": str(d[0]["technicalSheet"]["031"]["pk7ht"]), "prep": str(d[0]["technicalSheet"]["031"]["preparation"]), "ing": str(d[0]["technicalSheet"]["031"]["ingredientList"]) } data = { "name": proddata["title"], "type": "simple", "regular_price": proddata["price"], "description": proddata["flavor"] + proddata["prep"] + proddata["ing"], "short_description": proddata["flavor"], "status": "private", "categories": [], "images": [{ "src": proddata["image"] }] } try: self.wcapi.post("products", data) except: return [ False, "Wrong Crendential for '" + str(self.url) + "'", 401 ] except: print("error") return [True, {}, 200]
def test_woocommerce_connection(self): message = "" woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=True, version="wc/v2", timeout=30, query_string_auth=True, # verify_ssl = False, ) try: woocommerce_api = woocommerce.get('system_status') except Exception as e: raise UserError(_("Error:" + str(e))) if 'message' in woocommerce_api.json(): message = "Connection Error" + str( woocommerce_api.status_code) + " : " + str( woocommerce_api.text) raise UserError(_(message)) else: self.state = 'validate' message = "Connection Successful!!" return self.display_message(message)
def get_customer_data(): wcapi = API(url=os.getenv("URL"), consumer_key=os.getenv("CONSUMER_KEY"), consumer_secret=os.getenv("CONSUMER_SECRET"), version="wc/v3") r = wcapi.get("orders") print(r.json()) json_array = r.json() store_list = [] for item in json_array: if item['status'] == 'completed': email = item['billing']['email'] surname = item['billing']['first_name'] lastname = item['billing']['last_name'] phone = item['billing']['phone'] address = item['billing']['address_1'] + " " + item['billing'][ 'address_2'] city = item['billing']['city'] postcode = item['billing']['postcode'] state = item['billing']['state'] customer = Customer(email, surname, lastname, phone, address, city, state, postcode) print(customer.surname, customer.lastname, customer.phone, customer.address, customer.state, customer.city, customer.postcode) return customer
def connect(self): self.wcapi = API(url=self.url, consumer_key=self.pub, consumer_secret=self.priv, wp_api=True, version="wc/v3") return [True, {}, None]
def get_request_request(path, settings=None, params=None): if not settings: settings = get_woocommerce_settings() wcapi = API( url=settings["woocommerce_url"], consumer_key=settings["api_key"], consumer_secret=settings["api_secret"], verify_ssl=settings["verify_ssl"], wp_api=True, version="wc/v3", timeout=1000, ) r = wcapi.get(path, params=params) # r.raise_for_status() # manually raise for status to get more info from error (message details) if r.status_code != requests.codes.ok: make_woocommerce_log( title="WooCommerce get error {0}".format(r.status_code), status="Error", method="get_request", message="{0}: {1}".format(r.url, r.json()), request_data="not defined", exception=True, ) return r
def connect_woocommerce(self): message = "" woocommerce = API( url=self.woocommerce_url, consumer_key=self.woocommerce_consumer_key, consumer_secret=self.woocommerce_secret_key, wp_api=True, version="wc/v2", timeout=40, query_string_auth=True, # verify_ssl = False, ) try: woocommerce_api = woocommerce.get('system_status').json() except Exception as e: raise UserError(_("Error:"+str(e))) if 'message' in woocommerce_api: message = "Connection Error" + \ str(woocommerce_api['data']['status']) + \ " : "+str(woocommerce_api["message"]) raise UserError(_(message)) else: self.state = 'validate' message = "Connection Successful!!" return True, message
def get_woocommerce_connection(self): if self.api_version == 'legacyv3': woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=False, version="v3", timeout=50, ) else: woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=True, version="wc/v3", timeout=50, query_string_auth=True, ) date = datetime.now().date() date = date + timedelta(days=5) date = str(date) try: # woocommerce_api=woocommerce.get('products?filter[created_at_min]='+date) woocommerce_api = woocommerce.get('system_status') except Exception as e: raise osv.except_osv(_('Error'), _("Error:" + str(e))) if woocommerce_api.json().has_key('message'): message = str(woocommerce_api.text) + ", Status Code:" + str( woocommerce_api.status_code) else: return woocommerce raise osv.except_osv(_('Error'), _(message))
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 woocommerce_export_api_config(self): if self.api_version == 'legacyv3': woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=False, version="v3", timeout=150, # verify_ssl = False, ) else: woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=True, version="wc/v3", timeout=50, query_string_auth=True, ) try: # woocommerce_api=woocommerce.get('products?per_page=1') woocommerce_api = woocommerce.get('system_status') except Exception as e: raise osv.except_osv(_('Error'), _("Error:" + str(e))) # _logger.error('########### Valor de woocomerce export api: %s', woocommerce_api.json()) if woocommerce_api.json().has_key('message'): message = "Connection Error" + str( woocommerce_api.status_code) + " : " + str( woocommerce_api.text) raise osv.except_osv(_('Error'), _(message)) else: return woocommerce
class REQ: def __init__(self): adm_consumer_key = 'ck_f5fcf679cc65d438ba8188e867610e18a6486ee5' adm_consumer_secret = 'cs_4c312c0392d86938a4469c432ba15aa78977bb3f' self.wcapi = API(url="http://127.0.0.1/ak_store/", consumer_key=adm_consumer_key, consumer_secret=adm_consumer_secret, wp_api=True, version="wc/v2") # def test_api(self): # print self.wcapi.get("").json() def post(self, endpoint, data): result = self.wcapi.post(endpoint, data) resp_code = result.status_code resp_body = result.json() resp_url = result.url return [resp_code, resp_body, resp_url] def get(self, endpoint): result = self.wcapi.get(endpoint) resp_code = result.response_code resp_body = result.json() resp_url = result.url return [resp_code, resp_body, resp_url] # test1 = REQ() # test1.test_api()
class BasicAuth: def __init__(self): admin_consumer_key = "ck_4c5db02305903c89717481b801f510a50c769cf0" admin_consumer_secret = "cs_be0444f22ccc2358bb98193aa39279ce33b78aa8" self.wcapi = API(url="http://127.0.0.1/sreenu_store", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, version="v3") def test_api(self): print(self.wcapi.get("").json()) def post_method(self, endpoint, data): result = self.wcapi.post(endpoint, data) rs_response = result.status_code rs_body = result.json() rs_url = result.url return rs_response, rs_body, rs_url def get_method(self, endpoint): result = self.wcapi.get(endpoint) rs_response = result.status_code rs_body = result.json() rs_url = result.url return rs_response, rs_body, rs_url
def test_connection(self): location = self.location cons_key = self.consumer_key sec_key = self.consumer_secret version = self.version or 'v3' msg = str() try: wcapi = API( url=location, # Your store URL consumer_key=cons_key, # Your consumer key consumer_secret=sec_key, # Your consumer secret version=version, # WooCommerce WP REST API version query_string_auth=True # Force Basic Authentication as query # string true and using under HTTPS ) r = wcapi.get("products") if r.status_code == 404: msg = "(Enter Valid url)" val = r.json() except: raise Warning(_("Sorry, Could not reach WooCommerce site! %s")\ % (msg)) msg = '' if 'errors' in r.json(): msg = val['errors'][0]['message'] + '\n' + \ val['errors'][0]['code'] raise Warning(_(msg)) else: raise Warning(_('Test Success')) return True
def put_request(path, data): settings = get_woocommerce_settings() wcapi = API(url=settings['woocommerce_url'], consumer_key=settings['api_key'], consumer_secret=settings['api_secret'], verify_ssl=settings['verify_ssl'], wp_api=True, version="wc/v3", timeout=5000) #frappe.log_error("{0} data: {1}".format(path, data)) r = wcapi.put(path, data) #r.raise_for_status() # manually raise for status to get more info from error (message details) if r.status_code != requests.codes.ok: make_woocommerce_log(title="WooCommerce put error {0}".format( r.status_code), status="Error", method="put_request", message="{0}: {1}".format(r.url, r.json()), request_data=data, exception=True) return r.json()
def get_woocommerce_connection(self): _logger.info( "==================== Now In Woocomerce Connection to check connection ===================" ) woocommerce = API( url=self.url, consumer_key=self.consumer_key, consumer_secret=self.secret_key, wp_api=True, version="wc/v2", timeout=30, query_string_auth=True, # verify_ssl = False, ) try: woocommerce_api = woocommerce.get('system_status') except Exception as e: raise UserError(_("Error:" + str(e))) if 'message' in woocommerce_api.json(): message = "Connection Error" + str( woocommerce_api.status_code) + " : " + str( woocommerce_api.text) raise UserError(_(message)) else: return woocommerce
def get(self, request, format=None): try: # Create a WooCommerce API instance wcapi = API(url=settings.WOOCOMMERCE_URL, consumer_key=settings.CONSUMER_KEY, consumer_secret=settings.CONSUMER_SECRET, wc_api=True, version="wc/v2") # Get list of attributes in WooCommerce attributes_in_ecommerce = wcapi.get( "products/attributes?per_page=100").json() attributes = AttributeSerializer(data=attributes_in_ecommerce, many=True) if attributes.is_valid(): attributes.save() for attribute in attributes.validated_data: terms_in_ecommerce = wcapi.get( f"products/attributes/{attribute['uuid']}/terms?per_page=100" ).json() terms = AttributeTermSerializer( data=terms_in_ecommerce, many=True, context={'attribute_id': attribute['uuid']}) if terms.is_valid(): terms.save() else: print(terms.errors) return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST)
class REQ(): def __init__(self): admin_consumer_key = "ck_82f82456dfe3b95b2b9dc83c56411bb5277807bd" admin_consumer_secret = "cs_5af4b6bdfef28ce5337d6a189ef342eb8545079e" self.wcapi = API(url="http://127.0.0.1/hbstore/", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, wp_api=True, version="wc/v1") def testAPI(self): print(self.wcapi.get("").json()) def post(self, endpoint, data): result = self.wcapi.post(endpoint, data) res_code = result.status_code res_body = result.json() res_url = result.url return [res_code, res_body, res_url] def get(self, endpoint): result = self.wcapi.get(endpoint) res_code = result.response_code res_body = result.json() res_url = result.url return [res_code, res_body, res_url] # # obj = REQ() # obj.testAPI()
def Woocommerce(URL, INVOICE_ID, CONSUMER_KEY, CONSUMER_SECRET, VERSION): wcapi = API(url=URL, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, version=VERSION) for attribute in wcapi.get("orders").json(): if attribute['status'] == 'processing': for i in wcapi.get("payment_gateways").json(): if i['id'] == 'paypal': PAYPAL = i['settings']['invoice_prefix']['value'] INVOICE = f"{INVOICE_ID}-{attribute['number']}" ShippingInfo = attribute['shipping'] NAME = f"{ShippingInfo['first_name']} {ShippingInfo['last_name']}" if ShippingInfo['address_2'] != None: ADDRESS = f"{ShippingInfo['address_1']} {ShippingInfo['address_2']}" else: ADDRESS = f"{ShippingInfo['address_1']}" CITY = ShippingInfo['city'] STATE = ShippingInfo['state'] ZIPCODE = ShippingInfo['postcode'] TRANSACTION = attribute['transaction_id'] PHONE = attribute['billing']['phone'] for variant in attribute['line_items']: SKU = variant['sku'] QUANTITY = variant['quantity'] ORDERS.append([ PAYPAL, TRANSACTION, INVOICE, NAME, PHONE, ADDRESS, CITY, STATE, ZIPCODE, SKU, QUANTITY, 'Build Stock Later' ]) return ORDERS
def searchbySKU(sku): # Obtengo las claves api_keys = wc_gsbase_api.getApiKeys("secret_keys.json") # Crea conexion API con WooCommerce if bool(api_keys): wcapi = API( url="https://camanwi.com", # Your store URL consumer_key=api_keys['WOOCOMMERCE_KEY'], # Your consumer key consumer_secret=api_keys[ 'WOOCOMMERCE_SECRET'], # Your consumer secret wp_api=True, # Enable the WP REST API integration version="wc/v3", # WooCommerce WP REST API version, timeout=15) else: print("No Keys Available") exit() # Consigue lista de todos los productos (puede que sean solo los 10 ultimos por la pagination) my_json = (wcapi.get("products?per_page=50").json()) # Busca el producto con el sku requerido my_products = {} encontrado = False for attribute in my_json: if attribute['sku'] == sku: print('Producto Padre ID: ', attribute['id'], 'SKU: ', sku) # Busco las variaciones del producto. my_variations_id = (attribute['variations']) print('Productos hijos ID: ', attribute['variations']) encontrado = True my_variations_sku = [] try: # Extraigo los detalles de cada variacion a traves de su ID. for id in my_variations_id: my_product = (wcapi.get("products/" + str(id)).json()) my_products.update({id: my_product}) my_variations_sku.append(my_product["sku"]) resultado = ('Productos hijos SKU: ', my_variations_sku) # Si encuentra el producto lo guarda en un json. except UnboundLocalError as e: print(e) pass if encontrado: with open('Retrieved Products Temp.json', 'w') as json_file: json.dump(my_products, json_file) return resultado # Si no lo encuentra else: resultado = ("No se han encontrado productos hijos para el producto " + sku) return resultado
def __init__(self): admin_consumer_key = "ck_b8cca2d3ba8e0d7b08c830254b59e1f005df5bd4" admin_consumer_secret = "cs_b48bd72801b20cf8df76bee3864d21368f0ef444" self.wcapi = API(url="http://127.0.0.1/testapi", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, version="v3")
def __init__(self): admin_consumer_key = 'ck_e5bf8b09f7dddc049037c01bb6cd540695363b75' admin_consumer_secret = 'cs_2543d5b7ed833e6cf83ae4c3e8f2e5f0ccf5538a' self.wcapi = API(url="http://127.0.0.1/wp", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, version="wc/v3")
def __init__(self): self.env = os.environ.get('ENV', 'test') self.base_url = Woo_API_HOSTS[self.env] self.wcapi = API( url=self.base_url, consumer_key='ck_0085a54be0a5de70ef8378e0f25cbc5e25965e0d', consumer_secret='cs_17f2fb28b85a3e9cb7254cc31ac25ebbac90d703', version="wc/v3")
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 __init__(self): admin_consumer_key = "ck_4c5db02305903c89717481b801f510a50c769cf0" admin_consumer_secret = "cs_be0444f22ccc2358bb98193aa39279ce33b78aa8" self.wcapi = API(url="http://127.0.0.1/sreenu_store", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, version="v3")
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 __init__(self): self.wcapi = API(url=os.environ.get("wc_endpoint", None), consumer_key=os.environ.get("wc_consumer_key", None), consumer_secret=os.environ.get( "wc_consumer_secret", None), wp_api=True, verify_ssl=False, version="wc/v2", timeout=30)
def __init__(self): admin_consumer_key = "ck_82f82456dfe3b95b2b9dc83c56411bb5277807bd" admin_consumer_secret = "cs_5af4b6bdfef28ce5337d6a189ef342eb8545079e" self.wcapi = API(url="http://127.0.0.1/hbstore/", consumer_key=admin_consumer_key, consumer_secret=admin_consumer_secret, wp_api=True, version="wc/v1")
def __init__(self): creds_helper = CredentialsHelper() wc_reds = creds_helper.get_wc_api_keys() self.wcapi = API(url="http://mystore.local", consumer_key=wc_reds['wc_key'], consumer_secret=wc_reds['wc_secret'], version="wc/v3")
def __init__(self): adm_consumer_key = 'ck_f5fcf679cc65d438ba8188e867610e18a6486ee5' adm_consumer_secret = 'cs_4c312c0392d86938a4469c432ba15aa78977bb3f' self.wcapi = API(url="http://127.0.0.1/ak_store/", consumer_key=adm_consumer_key, consumer_secret=adm_consumer_secret, wp_api=True, version="wc/v2")
def grab_orders_woocommerce(): wcapi = API(url="https://pulselabz.com", consumer_key="ck_a14883eff094abe7652196f03533c18b9c05eb0b", consumer_secret="cs_47027dbf997bd9f53155f7251ed5b2cab27ac323", wp_api=True, version="wc/v1") orders = wcapi.get("orders?status=processing&per_page=10") for order in orders.json(): load_order_wc(order)
def __init__(self): wc_creds = CredentialsUtility.get_wc_api_keys() self.env = os.environ.get('ENV', 'test') self.base_url = WOO_API_HOSTS[self.env] self.wcapi = API(url=self.base_url, consumer_key=wc_creds['wc_key'], consumer_secret=wc_creds['wc_secret'], version="wc/v3")
def __init__(self, invoice): self.url = settings.woocommerce['url'] self.key = settings.woocommerce['key'] self.secret = settings.woocommerce['secret'] self.version = 'v2' self.api = API(self.url, self.key, self.secret) self.order = None self.invoice = invoice self.items = []
class WooCommerce(object): def __init__(self, url, consumer_key, consumer_secret): self.wcapi = API(url=url, consumer_key=consumer_key, consumer_secret=consumer_secret) def get_api(self): return self.wcapi def open_products(self): result = self.wcapi.get('products?filter[limit]=1000') if result.status_code == 200: return result.json()['products'] def get_products(self, q, limit=1000): result = self.wcapi.get('products?filter[q]={q}&filter[limit]={limit}'.format(q=q, limit=1000)) if result.status_code == 200: return result.json()['products'] def post_product(self, data): if len(self.get_products(q=data['product']['title'])) == 0: result = self.wcapi.post('products', data=data) if result.statu_code == 200: return result.json() else: return "The Products is already exists" def get_tags(self): result = self.wcapi.get('products/tags') if result.status_code == 200: return result.json()['product_tags'] def get_categories(self): result = self.wcapi.get('products/categories') if result.status_code == 200: return result.json()['product_categories'] def save(self, filename, type='csv'): if type == 'csv': products = self.get_products() keys = products[0].keys() with open(filename, 'wb') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(products)
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" )
class WPWoocommerce: def __init__(self, invoice): self.url = settings.woocommerce['url'] self.key = settings.woocommerce['key'] self.secret = settings.woocommerce['secret'] self.version = 'v2' self.api = API(self.url, self.key, self.secret) self.order = None self.invoice = invoice self.items = [] def getorder(self, id): self.order = self.api.get('orders/' + str(id)).json()['order'] def get_billing_address(self): data = self.order['billing_address'] name = data['first_name'] + ' ' + data['last_name'] street = data['address_1'] + ' ' + data['address_2'] client = Person(data['company'], name, street, data['postcode'], data['city']) return client
#uri, headers, body = client.sign(root_url) # # #client = oauthlib.oauth1.Client(consumer_key, client_secret=consumer_secret, # resource_owner_key) # # #print uri #print headers #print body root_url = "http://westmontptsa.org/wp" from woocommerce import API wcapi = API (url=root_url, consumer_key = consumer_key, consumer_secret = consumer_secret) #products = wcapi.get("products") #print products.json() orders = wcapi.get("orders?filter[meta]=true") import pprint all_orders = orders.json()["orders"] pp = pprint.PrettyPrinter(indent=4) for order in all_orders: #print order.keys() try: meta = order["order_meta"] #u'Payer PayPal address' #u'Payment type' student_id = meta[u'Student ID']
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]
from woocommerce import API from urlparse import urlparse, parse_qs from random import randint import os wcapi = API( url=os.environ['URL'], consumer_key=os.environ['CONSUMER_KEY'], consumer_secret=os.environ['CONSUMER_SECRET'] ) # request first product page r = wcapi.get('products') # figure out how many pages there are total last_url = r.links['last']['url'] url_object = urlparse(last_url) queries = parse_qs(url_object.query) page_count = queries['page'][0] # was a string, need to convert to int # pick a random page number to pull up and get those 10 products page = randint(1, int(page_count)) r = wcapi.get('products?page=' + str(page)).json() # choose one of the 10 products in the list of products and return its url product_number = randint(0, 9) url = r['products'][product_number]['permalink'] print url
def __init__(self, url, consumer_key, consumer_secret): self.wcapi = API(url=url, consumer_key=consumer_key, consumer_secret=consumer_secret)
import json from woocommerce import API as WCAPI from pprint import pprint dir_parent = os.path.dirname(os.path.dirname(sys.argv[0])) if dir_parent: os.chdir(dir_parent) dir_conf = 'conf' path_conf_wc = os.path.join(dir_conf, 'wc_api.yaml') with open(path_conf_wc) as file_conf_wc: conf_wc = yaml.load(file_conf_wc) for key in ['consumer_key', 'consumer_secret', 'url']: assert key in conf_wc, key wcapi = WCAPI( **conf_wc ) r = wcapi.get("products?filter[meta]=true") links_str = r.headers.get('link') print links_str for link_str in links_str.split(', '): print repr(link_str) response_json = r.json() if 'products' in response_json: for product in response_json['products']: print product.get('id'), product.get('managing_stock'), product.get('stock_quantity'), product.get('in_stock'), product.get('product_meta', {}).get('MYOB SKU')
from woocommerce import API import pprint import json wcapi = API( url="https://www.ameryn.com/", consumer_key="ck_bc1ac58b5dc9099c8df1789f811afa2d", consumer_secret="cs_7199c23290742677aed84294861ed73b", version='v2', verify_ssl=True ) print wcapi #order = wcapi.get('recording_orders/3050').json() recording_orders = wcapi.get('orders?status=recording&filter[limit]=100').json()['orders'] #print json.dumps(order, indent=4) for each_order in recording_orders: print each_order['id'], '-', each_order['status'], '-', each_order['billing_address']['email'], '-', '$' + each_order['total'] print '{0} recording_orders, ${1}'.format(str(len(recording_orders)), sum([float(each_order['total']) for each_order in recording_orders])) #print [order['id'] for order in wcapi.get('recording_orders?status=recording&fields=id&filter[limit]=100').json()['recording_orders']] all_orders = wcapi.get('orders?filter[limit]=2000').json()['orders'] all_order_totals = [float(each_order['total']) for each_order in all_orders] print all_order_totals print '{0} orders, ${1}'.format(str(len(all_orders)), sum(all_order_totals)) print 'Creating new text file' with open('order_totals.txt', 'w') as txt: txt.writelines([str(each) for each in all_order_totals])
#!/usr/bin/env python #coding=utf8 import pika import sys from woocommerce import API import json # use woocommerce lib # install: pip install woocommerce wcapi = API( url = "http://120.55.166.84/Woo", consumer_key = "ck_74e4287363f65b85f445cb763f24a8f382c401a2", consumer_secret = "cs_f5700e2af5d238fae1bc784467bb7f8111f191d7", timeout = 30 ) r = wcapi.get("products") j = json.loads(r.text) products = j['products'] for p in products: print p['title'] connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') message = ' '.join(sys.argv[1:]) or p['title'] channel.basic_publish(exchange='', routing_key='hello', body=message) print " [x] Sent %r" % (message,) connection.close()