def listorders(start_date, end_date, filepath, start_date_str, end_date_str): app_path = os.getcwd() os.chdir(os.getcwd()) pageno = 1 localfilename = filepath + filesep + 'orders_' + start_date_str + str( pageno) + '.xml' x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=merchant_id, auth_token=auth_token) orders = x.list_orders(marketplaceids=marketplaceId, created_after=start_date) writetofile(orders, localfilename) nexttoken = getnexttoken(orders) pageno = pageno + 1 print(nexttoken) while True: if nexttoken is None: break else: time.sleep(60) orders = listordersbynexttoken(nexttoken) localfilename = filepath + filesep + 'orders_' + start_date_str + str( pageno) + '.xml' pageno = pageno + 1 writetofile(orders, localfilename) nexttoken = getnexttoken(orders) print(nexttoken)
def listordersbynexttoken(nexttoken): x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=merchant_id, auth_token=auth_token) orders = x.list_orders_by_next_token(nexttoken) return orders
def __init__(self, mws_access_key, mws_secret_key, mws_seller_id, region): marketplaceid = {"CA" : "A2EUQ1WTGCTBG2","US" : "ATVPDKIKX0DER","DE" : "A1PA6795UKMFR9","ES" : "A1RKKUPIHCS9HS","FR" : "A13V1IB3VIYZZH",\ "IN" : "A21TJRUUN4KGV","IT" : "APJ6JRA9NG5V4","UK" : "A1F83G8C2ARO7P","JP" : "A1VC38T7YXB528","CN" : "AAHKV2X7AFYLW"} self.mws_access_key = mws_access_key self.mws_secret_key = mws_secret_key self.mws_seller_id = mws_seller_id self.region = region self.marketplaceid = marketplaceid[self.region.upper()] self.order_client = mws.Orders(access_key=self.mws_access_key, secret_key=self.mws_secret_key, account_id=self.mws_seller_id)
def get_amazon_order_api(self): """ Create an instance of Order api :return: order api instance """ return mws.Orders( access_key=self.amazon_access_key, secret_key=self.amazon_secret_key, account_id=self.amazon_merchant_id, )
def listorderitems(orderids, filepath): for orderid in orderids: x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=merchant_id, auth_token=auth_token) orderitem = x.list_order_items(orderid) localfilename = filepath + filesep + 'orderitem_' + str( orderid) + '.xml' writetofile(orderitem, localfilename) time.sleep(3)
def __init__(self, settings): # Import settings self.settings = settings # Connect to Postgres self.engine = create_engine('postgresql://{}:{}@{}:{}/{}'.format( psql['user'], psql['password'], psql['host'], psql['port'], psql['database'])) self.Base = declarative_base() Session = sessionmaker(bind=self.engine) self.session = Session() # Connect to Amazon API self.api = mws.Orders(self.settings['ACCESS_KEY'], self.settings['SECRET_KEY'], self.settings['SELLER_ID'], region='CA') self.order_dict = {}
def run(mws_credentials, start_date, end_date): """Connect to MWS API and retrieve orders between start_date and end_date.""" # Connect to API orders_api = mws.Orders( access_key=mws_credentials['MWS_ACCESS_KEY'], secret_key=mws_credentials['MWS_SECRET_KEY'], account_id=mws_credentials['MWS_ACCOUNT_ID'], region='FR', ) # Get MWS Orders orders = get_mws_orders( orders_api=orders_api, marketplace=mws_credentials['MWS_MARKETPLACE_IDS'], created_after=start_date, created_before=end_date ) return orders
def get_orders(): x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=merchant_id, region=region) orders = x.list_orders( marketplaceids=[market_place_id], created_after='2014-08-04T11:00:00Z', created_before='2014-08-04T13:00:00Z' ) #, lastupdatedafter, lastupdatedbefore, orderstatus, fulfillment_channels, payment_methods, buyer_email, seller_orderid, max_results) response_data = orders.original print response_data od = orders.parsed orders = od.Orders.Order if not isinstance(orders, list): orders = [orders] for order in orders: print order.ShipmentServiceLevelCategory
import os import time from datetime import datetime, timedelta from functools import partial import iso8601 from mws import mws from pymongo import MongoClient from .orders import generate_orders, set_order_items from .utils import make_ratelimit_aware orders_api = mws.Orders( os.environ["AWS_ACCESS_KEY"], os.environ["MWS_SECRET_KEY"], os.environ["MWS_SELLERID"], region=os.environ["REGION"], ) MARKETPLACEIDS = os.environ["MARKETPLACEIDS"].split(",") START_DATE = None END_DATE = None if "START_DATE" in os.environ: START_DATE = iso8601.parse_date(os.environ["START_DATE"]).isoformat() if "END_DATE" in os.environ: END_DATE = iso8601.parse_date(os.environ["END_DATE"]).isoformat() else: DAYS_AGO = 1 if "DAYS_AGO" not in os.environ else int( os.environ["DAYS_AGO"]) START_DATE = (datetime.now() - timedelta(days=DAYS_AGO)).isoformat()
def main(event, context): """ Checks for new orders """ orders_api = mws.Orders(access_key=MWS_ACCESS_KEY, secret_key=MWS_SECRET_KEY, account_id=MWS_SELLER_ID, region=MWS_REGION) logger.info('INFO: connected to MWS API') service_status = orders_api.get_service_status() if service_status.parsed.Status != 'GREEN': logger.error('ERROR: MWS API looks to be down') sys.exit() # updated 1 day ago today = datetime.now() - timedelta(days=1) updated_after = '{}-{:02d}-{:02d}T08:00:00'.format(today.year, today.month, today.day) res = orders_api.list_orders(marketplaceids=MARKETPLACES, lastupdatedafter=updated_after) # new order/s found if len(res.parsed['Orders']) > 0: logger.info('INFO: found new order/s') # more than one order returns a list of dicts if type(res.parsed['Orders']['Order']) is list: for order in res.parsed['Orders']['Order']: logger.info('INFO: new order {}'.format( order['AmazonOrderId']['value'])) # ignore cancelled orders if order['OrderStatus']['value'] != 'Canceled': order_items = orders_api.list_order_items( amazon_order_id=order['AmazonOrderId']['value']) try: res = table.put_item( Item=dynamodb_payload(order, order_items), ConditionExpression='attribute_not_exists(order_id)' ) except botocore.exceptions.ClientError as e: if e.response['Error'][ 'Code'] != 'ConditionalCheckFailedException': logger.info( 'INFO: order_id already added. Skipping insert...' ) else: # just one order returns dict order = res.parsed['Orders']['Order'] logger.info('INFO: new order {}'.format( order['AmazonOrderId']['value'])) # ignore canceled orders if order['OrderStatus']['value'] != 'Canceled': order_items = orders_api.list_order_items( amazon_order_id=order['AmazonOrderId']['value']) try: table.put_item( Item=dynamodb_payload(order, order_items), ConditionExpression='attribute_not_exists(order_id)') except botocore.exceptions.ClientError as e: if e.response['Error'][ 'Code'] != 'ConditionalCheckFailedException': logger.info( 'INFO: order_id already added. Skipping insert...')
def main(event, context): """ This function testing """ item_count = 0 #logger.info(event) #logger.info(context) try: orders_api = mws.Orders(os.environ['MWS_ACCESS_KEY'], os.environ['MWS_SECRET_KEY'], event['seller_id'], event['region'], auth_token=event['auth_token']) logger.info("SUCCESS: orders_api") service_status = orders_api.get_service_status() logger.info("SUCCESS: service_status") if (service_status.parsed.Status != 'GREEN'): logger.error("ERROR: MWS API is having problems") sys.exit() else: logger.info("SUCCESS: MWS API is GREEN") # updated 8h ago updated_after = to_amazon_timestamp(datetime.now() - timedelta(hours=8)) response = orders_api.list_orders( marketplaceids=event['marketplaceids'], lastupdatedafter=updated_after, max_results='25') xml_data = xmltodict.parse( response.original, process_namespaces=True, namespaces={ 'https://mws.amazonservices.com/Orders/2013-09-01': None, '@xmlns': None }) data = xml_data.get("ListOrdersResponse", {}).get("ListOrdersResult", {}) orders = [] orders.extend(data.get("Orders", {}).get("Order", [])) with conn.cursor() as db: for order in orders: item_count += 1 logger.debug("GOT ORDER %s", (order['SellerOrderId'])) number_of_rows = db.execute( 'SELECT `id`, `syncronized`, `failed` FROM `orders` WHERE `seller_id` = %s AND `seller_order_id` = %s AND `order_status` = %s', (event['seller_id'], order['SellerOrderId'], order['OrderStatus'])) db_order = db.fetchone() if (db_order == None and number_of_rows == 0): db.execute( 'INSERT INTO `orders` (`seller_id`, `seller_order_id`, `order_status`, `payload`, `created_at`, `updated_at`) values (%s, %s, %s, %s, NOW(), NOW());', (event['seller_id'], order['SellerOrderId'], order['OrderStatus'], json.dumps(order))) id = db.lastrowid logger.info("SUCCESS: NEW ORDER %s", (id)) call_webhook(id, url=event.get('url')) elif (db_order != None and db_order[1] == 0 and db_order[2] <= 3): logger.info("SUCCESS: EXISTING ORDER %d BUT NOT SYNCED", (db_order[0])) call_webhook(db_order[0], url=event.get('url')) else: logger.info("SUCCESS: EXISTING ORDER %d", (db_order[0])) logger.info("SUCCESS: COMPLETED CYCLE") except Exception as e: logger.error(sys.exc_info()[-1].tb_lineno) logger.error(type(e).__name__) logger.error(e) finally: return "Added %d items to MySQL table" % (item_count)