def _build_mws_orders(self): return mws.Orders( access_key=self.access_key, secret_key=self.secret_key, account_id=self.account_id, region=self.region, )
def __init__(self, access_key, secret_key, account_id, api_data): self.api_data = api_data self.client = self.api_data.client self.orders_api = mws.Orders( access_key=os.environ.get("MWS_ACCESS_KEY"), secret_key=os.environ.get("MWS_SECRET_KEY"), account_id=os.environ['MWS_ACCOUNT_ID'], region="DE", ) self.products_api = mws.Products( access_key=os.environ.get("MWS_ACCESS_KEY"), secret_key=os.environ.get("MWS_SECRET_KEY"), account_id=os.environ['MWS_ACCOUNT_ID'], region="DE", ) self.reports_api = mws.Reports( access_key=os.environ.get("MWS_ACCESS_KEY"), secret_key=os.environ.get("MWS_SECRET_KEY"), account_id=os.environ['MWS_ACCOUNT_ID'], region="DE", ) self.reports_api.get_report_request_list() self.orders_namespace = self.orders_api.NAMESPACE self.products_namespace = self.products_api.NAMESPACE self.reports_namespace = "{http://mws.amazonaws.com/doc/2009-01-01/}" self.orders = [] super().__init__()
def get_orders_api(self): return mws.Orders( access_key=self.config.get('access_key'), secret_key=self.config.get('secret_key'), account_id=self.config.get('seller_id'), region=self.config.get('region'), )
def setUp(self): self.api = mws.Orders( self.CREDENTIAL_ACCESS, self.CREDENTIAL_SECRET, self.CREDENTIAL_ACCOUNT, auth_token=self.CREDENTIAL_TOKEN ) self.api._test_request_params = True
def get(self,request): order_api = mws.Orders( access_key=settings.MWS_ACCESS_KEY, secret_key=settings.MWS_SECRET_KEY, account_id=settings.MWS_ACCOUNT_ID, region='IN', ) service_status = order_api.get_service_status() print(service_status.parsed) context = {'email': self.request.session['email']} return render(self.request,"reports/index.html",context)sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
def invoice_api(request): # calculate the spending of this month date = datetime.date.today() this_month = date.month this_year = date.year this_month_invoices = Invoices.objects.filter( invoice_date__month=this_month, invoice_date__year=date.year, organisation="Linco Care" ) total_cost_month = 0 for i in this_month_invoices: total_cost_month += i.invoice_value total_cost_month = "%0.2f" % total_cost_month # Spending of this year this_year_invoices = Invoices.objects.filter( invoice_date__year=date.year, organisation="Linco Care" ) total_cost_year = 0 for i in this_year_invoices: total_cost_year += i.invoice_value total_cost_year = "%0.2f" % total_cost_year # Amazon API import mws import os orders_api = mws.Orders( access_key=os.environ['MWS_ACCESS_KEY'], secret_key=os.environ['MWS_SECRET_KEY'], account_id=os.environ['MWS_ACCOUNT_ID'], region='UK', # if necessary ) service = orders_api.get_service_status() last_updated_after = '{}-{:02d}-01'.format(date.year, date.month) response = orders_api.list_orders( marketplaceids="A1F83G8C2ARO7P", lastupdatedafter=last_updated_after, max_results='100') response = response.parsed total_amazon_orders = response.Orders.Order[0].OrderTotal.Amount print(total_amazon_orders) data = { "total_cost_month": total_cost_month, "total_cost_year": total_cost_year, "this_month": this_month, "this_year": this_year, "Amazon": response, "total_amazon_orders": "total_amazon_orders" } return JsonResponse(data, encoder=JSONEncoder)
def __init__(self, account): """ Args: account: merchant account details """ self.report = None self.account = account self.orders_api = mws.Orders(account_id=account['merchant_id'], access_key=account['access_key'], secret_key=account['secret_key'], region=account['marketplace'], auth_token=account['mws_auth_token']) self.last_updated_after = ImportOrder.get_posted_after_date() self.last_updated_before = ImportOrder.get_posted_before() self.order_list = []
def main(): orders_api = mws.Orders(access_key=os.environ['MWS_ACCESS_KEY'], secret_key=os.environ['MWS_SECRET_KEY'], account_id=os.environ['MWS_ACCOUNT_ID']) marketplace_ca = 'A2EUQ1WTGCTBG2' response = orders_api.list_orders(marketplaceids=[marketplace_ca], created_after='2019-01-01').parsed print_orders(response) while ('NextToken' in response): try: next_token = response['NextToken']['value'] response = orders_api.list_orders_by_next_token(next_token).parsed print_orders(response) except: print( "503 Server Error: Service Unavailable to process url. Will try again..." ) time.sleep(1)
def main(): orders_api = mws.Orders(access_key=os.environ['MWS_ACCESS_KEY'], secret_key=os.environ['MWS_SECRET_KEY'], account_id=os.environ['MWS_ACCOUNT_ID']) marketplace_ca = 'A2EUQ1WTGCTBG2' marketplace_us = 'ATVPDKIKX0DER' print('Fetching Orders data...') response = orders_api.list_orders( marketplaceids=[marketplace_ca, marketplace_us], created_after='2017-01-01').parsed append_info(response) while ('NextToken' in response): try: next_token = response['NextToken']['value'] response = orders_api.list_orders_by_next_token(next_token).parsed append_address_info(response) except: print( "503 Server Error: Service Unavailable to process url. Will try again..." ) time.sleep(1) print('Done fetching Orders data...') df = pd.DataFrame(data, columns=[ 'AmazonOrderId', 'BuyerEmail', 'NumberOfItemsShipped', 'OrderStatus', 'Amount', 'PurchaseDate', 'ShipServiceLevel', 'IsPrime', 'City', 'Country', 'PostalCode', 'StateOrRegion' ]) print(df) file_name = 'orders_full_details.csv' print('Writing df into ' + file_name + ' ...') df.to_csv(file_name, encoding='utf-8', index=False) print('Writing complete...')
def test_get_service_status(): # we can get the service status without needing API credentials # this is a simple smoke test to check that the simplest API request can be successfully made orders_api = mws.Orders(access_key='', secret_key='', account_id='') r = orders_api.get_service_status() assert r.response.status_code == 200
def source(path): file_name = 'orders_report.txt' file_dir_name = (os.path.join(path, file_name)) MWS_MARKETPLACE_ID = os.environ.get('MWS_MARKETPLACE_ID') orders_api = mws.Orders( access_key=os.environ['MWS_ACCESS_KEY'], secret_key=os.environ['MWS_SECRET_KEY'], account_id=os.environ['MWS_ACCOUNT_ID']) service_status = orders_api.get_service_status() # Check connection different status types # print(service_status.original) # print(service_status.parsed) # print(service_status.response) last_ninety_days = (datetime.datetime.now() - datetime.timedelta(90)).isoformat() orders_list = orders_api.list_orders(created_after=last_ninety_days, marketplaceids=MWS_MARKETPLACE_ID, orderstatus='Unshipped') # View as XML orders_as_xml = orders_list.original # Write XML file with open('ListOrders.xml', 'w', encoding='utf-8') as f: f.write(orders_as_xml) # Build XML tree and start extracting info tree = ET.parse('ListOrders.xml') root = tree.getroot() # print(f'There are {len(root[0][0])} orders today.') orders_dict = {} list_of_dict = list() # Get a list with orders already in SOLD orders_in_sold = main() orders_file_head = 'order-id order-item-id purchase-date payments-date reporting-date promise-date ' \ 'days-past-promise buyer-email buyer-name buyer-phone-number sku product-name ' \ 'quantity-purchased quantity-shipped quantity-to-ship ship-service-level recipient-name ' \ 'ship-address-1 ship-address-2 ship-address-3 ship-city ship-state ship-postal-code ' \ 'ship-country is-business-order purchase-order-number price-designation\n' with open(file_dir_name, 'w', encoding='utf-8') as f: f.write(orders_file_head) # root[0][0] stands for ListOrdersResponse(root)->ListOrdersResult[0]->Orders[0][0] for order in root[0][0]: # print('\n\n\n============ NEXT ORDER ============\n') for each in order: orders_dict[reg_it(each.tag)] = each.text.strip() for sub_each in each: orders_dict[reg_it(sub_each.tag)] = sub_each.text.strip() # print(orders_dict) list_of_dict.append(dict(orders_dict)) orders_dict.clear() line_write = list() # Check if orders list is empty for item in list_of_dict: order_id = item.get('AmazonOrderId') if order_id in orders_in_sold: print(f'{order_id} already in SOLD') continue # print(f'{order_id} NEW!') line_write.append(order_id) # Get order item details orders_items = orders_api.list_order_items(amazon_order_id=order_id) order_items_as_xml = orders_items.original with open('ListOrderItems.xml', 'w', encoding='utf-8') as f: f.write(order_items_as_xml) tree = ET.parse('ListOrderItems.xml') root = tree.getroot() str_to_cut = '' for each in root[0]: str_to_cut = reg_it(each.tag), ': ', each.text, ':' for sub_each in each: str_to_cut += '\n\t', reg_it(sub_each.tag), ': ', sub_each.text, ':' for ss_each in sub_each: str_to_cut += '\n\t\t', reg_it(ss_each.tag), ': ', ss_each.text, ':' for sss_each in ss_each: str_to_cut += '\n\t\t\t', reg_it(sss_each.tag), ': ', sss_each.text, ':' # If zero items in the list, the 'join' will break str_to_cut = ''.join(str_to_cut) # print(str_to_cut) order_item_id = ';'.join(re.findall(r'OrderItemId: (\w+).*:', str_to_cut)) line_write.append(order_item_id) purchase_date = item.get('PurchaseDate') line_write.append(purchase_date) payments_date = item.get('LastUpdateDate') line_write.append(payments_date) reporting_date = item.get('LastUpdateDate') line_write.append(reporting_date) promise_date = item.get('LatestShipDate') line_write.append(promise_date) days_past_promise = '0' line_write.append(days_past_promise) buyer_email = item.get('BuyerEmail') line_write.append(buyer_email) buyer_name = item.get('BuyerName') line_write.append(buyer_name) buyer_phone_number = item.get('Phone') line_write.append(buyer_phone_number) sku = ';'.join(re.findall(r'SellerSKU: (\w+-\w+-\w+).*:', str_to_cut)) line_write.append(sku) product_name = ';'.join(re.findall(r'Title: (.+).*:', str_to_cut)) line_write.append(product_name) quantity_purchased = ';'.join(re.findall(r'QuantityOrdered: (\d).*:', str_to_cut)) line_write.append(quantity_purchased) quantity_shipped = ';'.join(re.findall(r'QuantityShipped: (\d).*:', str_to_cut)) line_write.append(quantity_shipped) if ';' in quantity_purchased: quantity_to_ship_list = list() quantity_purchased_list = quantity_purchased.split(';') quantity_shipped_list = quantity_shipped.split(';') for i in range(len(quantity_purchased_list)): quantity_to_ship_list.append(str(int(quantity_purchased_list[i])-int(quantity_shipped_list[i]))) quantity_to_ship = ';'.join(quantity_to_ship_list) else: quantity_to_ship = item.get('NumberOfItemsUnshipped') line_write.append(quantity_to_ship) ship_service_level = 'Standard' line_write.append(ship_service_level) recipient_name = item.get('Name') line_write.append(recipient_name) ship_address_1 = item.get('AddressLine1') line_write.append(ship_address_1) ship_address_2 = '' line_write.append(ship_address_2) ship_address_3 = '' line_write.append(ship_address_3) ship_city = item.get('City') line_write.append(ship_city) ship_state = item.get('StateOrRegion') line_write.append(ship_state) ship_postal_code = item.get('PostalCode') line_write.append(ship_postal_code) ship_country = item.get('CountryCode') line_write.append(ship_country) is_business_order = item.get('IsBusinessOrder') line_write.append(is_business_order) purchase_order_number = '' line_write.append(purchase_order_number) price_designation = '' line_write.append(price_designation) # IF YOU WANT TO ADD THE PRICE TO THE OUTPUT - UNCOMMENT # item_price = item.get('Amount') # line_write.append(item_price) # # item_tax = re.findall(r'ItemTax:\s+:\s+Amount: (\d+\.\d\d)', str_to_cut)[0] # line_write.append(item_tax) for i in range(len(line_write)): if line_write[i] is None: line_write[i] = '' line_w = ' '.join(line_write) print(line_w) line_w += '\n' with open(file_dir_name, 'a', encoding='utf-8') as f: f.write(line_w) line_write.clear() try: os.remove('ListOrders.xml') os.remove('ListOrderItems.xml') except Exception as ex: print(f'Could not delete .xml files: {ex}')
import mws, os, pprint orders_api = mws.Orders(access_key=os.environ['MWS_ACCESS_KEY'], secret_key=os.environ['MWS_SECRET_KEY'], account_id=os.environ['MWS_ACCOUNT_ID']) marketplace_ca = 'A2EUQ1WTGCTBG2' marketplace_us = 'ATVPDKIKX0DER' response = orders_api.list_orders( marketplaceids=[marketplace_ca, marketplace_us], created_after='2019-01-01').parsed pprint.pprint(response)
def Send_Request(): created_after = datetime.datetime.utcnow() - datetime.timedelta(hours=.3) created_before = datetime.datetime.utcnow() - datetime.timedelta(hours=.05) print(created_after) print(created_before) orders_api = mws.Orders(access_key=ACCESS_KEY, secret_key=SECRET_KEY, account_id=SELLER_ID, auth_token=MWS_AUTH_TOKEN) order_statuses = [ "PendingAvailability", "Unshipped", ] orders = orders_api.list_orders(marketplaceids=['ATVPDKIKX0DER'], orderstatus=None, created_after=created_after, created_before=created_before) request = "" sku = "" title = "" quantity = "" unit_price = Decimal("0") shipping = Decimal("0") tax = Decimal("0") order_id = "" date = "" shipping_service = "" city = "" postal_code = "" state = "" country = "" buyer_name = "" A1 = "" A2 = "" A3 = "" ss = ShipStation(key=api_key, secret=api_secret) if orders.parsed.Orders != {}: to_parse = False loops = 0 if (isinstance(orders.parsed.Orders.Order, list)): to_parse = True loops = len(orders.parsed.Orders.Order) #print("parsing") for i in range(loops): if (to_parse): for _ in dict_generator(orders.parsed.Orders.Order[i]): if "PurchaseDate" in _: date = _[-1] if ("ShippingAddress" in _ and "City" in _): city = _[-1] if ("ShippingAddress" in _ and "StateOrRegion" in _): state = _[-1] if ("ShippingAddress" in _ and "CountryCode" in _): country = _[-1] if ("ShippingAddress" in _ and "PostalCode" in _): postal_code = _[-1] if ("ShippingAddress" in _ and "Name" in _): buyer_name = _[-1] if ("ShippingAddress" in _ and "AddressLine1" in _): A1 = _[-1] if ("ShippingAddress" in _ and "AddressLine2" in _): A2 = _[-1] if ("ShippingAddress" in _ and "AddressLine3" in _): A3 = _[-1] if ("ShipmentServiceLevelCategory" in _): shipping_service = _[-1] #print(_) response = orders_api.list_order_items( orders.parsed.Orders.Order[i].AmazonOrderId) else: for _ in dict_generator(orders.parsed.Orders.Order): if "PurchaseDate" in _: date = _[-1] if ("ShippingAddress" in _ and "City" in _): city = _[-1] if ("ShippingAddress" in _ and "StateOrRegion" in _): state = _[-1] if ("ShippingAddress" in _ and "CountryCode" in _): country = _[-1] if ("ShippingAddress" in _ and "PostalCode" in _): postal_code = _[-1] if ("ShippingAddress" in _ and "Name" in _): buyer_name = _[-1] if ("ShippingAddress" in _ and "AddressLine1" in _): A1 = _[-1] if ("ShippingAddress" in _ and "AddressLine2" in _): A2 = _[-1] if ("ShippingAddress" in _ and "AddressLine3" in _): A3 = _[-1] if ("ShipmentServiceLevelCategory" in _): shipping_service = _[-1] #print(_) response = orders_api.list_order_items( orders.parsed.Orders.Order.AmazonOrderId) #print(date) for _ in dict_generator(response.parsed): if "CustomizedURL" in _: request = _[-1] if "Title" in _: title = _[-1] if "SellerSKU" in _: sku = _[-1] if ("ItemPrice" in _ and "Amount" in _): unit_price = _[-1] if ("ItemTax" in _ and "Amount" in _): tax = _[-1] if "AmazonOrderId" in _: order_id = _[-1] if ("ShippingPrice" in _ and "Amount" in _): shipping = _[-1] if ("QuantityOrdered" in _): quantity = _[-1] #print(_) initials = None name = None extra = None order_id = order_id if (request != ""): r = requests.get(request) z = zipfile.ZipFile(io.BytesIO(r.content)) jsonpath = "" for i in z.namelist(): if i.endswith(".json"): jsonpath = i z.extractall("Amazon-Shipstation/zips") f = open("Amazon-Shipstation/zips/" + jsonpath) #print(jsonpath) data = json.load(f) f.close() textfound = False fieldfound = False nextfield = "" custom = {} for _ in dict_generator(data): print(_) if fieldfound: custom[nextfield] = _[-1] fieldfound = False if textfound: nextfield = _[-1] fieldfound = True if _[-1] == "TextCustomization": textfound = True else: textfound = False notes = '' if 'Initial' in custom: initials = custom["Initial"] if 'Name' in custom: name = custom["Name"] if 'Name' in custom or 'Initial' in custom: notes = initials + ':' + name #extra= custom["extra"] order_check = ss.fetch_orders( parameters={'order_number': order_id}) #print("checked") if (order_check.json()['total'] == 0): ss_order = ShipStationOrder(order_number=order_id, amount_paid=unit_price, tax=tax, shipping=shipping, customer_notes=notes, internal_notes=None) ss_order.set_status('awaiting_shipment') shipping_address = ShipStationAddress( name=buyer_name, street1=A1, street2=A2, street3=A3, city=city, state=state, postal_code=postal_code, country=country) ss_order.set_shipping_address(shipping_address) billing_address = ShipStationAddress( name=buyer_name, street1=A1, street2=A2, street3=A3, city=city, state=state, postal_code=postal_code, country=country) ss_order.set_billing_address(billing_address) ss_item = ShipStationItem(sku=sku, name=title, quantity=quantity, unit_price=unit_price) ss_order.add_item(ss_item) ss_order.set_order_date(date=date) ss.add_order(ss_order) print("added order") textfound = False fieldfound = False nextfield = "" custom = {} request = "" sku = "" title = "" quantity = "" unit_price = Decimal("0") shipping = Decimal("0") tax = Decimal("0") order_id = "" date = "" shipping_service = "" city = "" postal_code = "" state = "" country = "" buyer_name = "" A1 = "" A2 = "" A3 = "" initials = None name = None extra = None #time.sleep(1) ss.submit_orders() print("Done")
from __future__ import absolute_import import mws from datetime import datetime, timedelta from . import config from . import util from . import queries orders_api = mws.Orders( access_key=config.access_key, secret_key=config.secret_key, account_id=config.seller_id, region='US' or config.country_code, ) yesterday = datetime.now() - timedelta(hours=24) def get_order_id(order): return order.get('AmazonOrderId').get('value') class Orders(object): def __init__(self, last_updated_after, marketplace_id): self.last_updated_after = last_updated_after self.marketplace_id = marketplace_id @property def orders(self): orders_ = orders_api.list_orders( marketplaceids=[self.marketplace_id], lastupdatedafter=self.last_updated_after,