Skip to content

Instantly share code, notes, and snippets.

@hmarquardt
Last active September 16, 2021 22:40
Show Gist options
  • Save hmarquardt/a48448c8b04670611761 to your computer and use it in GitHub Desktop.
Save hmarquardt/a48448c8b04670611761 to your computer and use it in GitHub Desktop.
Fetch orders script using the Python EbaySDK (https://github.com/timotheus/ebaysdk-python). This uses v1.0 of the SDK, I've not yet migrated to v2.0 -- Added here because finding example code was hard when I needed to solve this problem. Basically fetch and insert into our local Oracle database. Not a completely working example. ebay.yaml is req…
# -*- coding: utf-8 -*-
'''
Hank Marquardt
May 26, 2014
Magic -- not really documented properly by *ebay*, the IncludeItemSpecifics is needed to get UPC back in feed
api.execute('GetItem',{'ItemID': '321394881000','DetailLevel': 'ReturnAll','IncludeItemSpecifics': 'True'})
'''
import os
import sys
import datetime
import cx_Oracle
from optparse import OptionParser
sys.path.insert(0, '%s/../' % os.path.dirname(__file__))
from common import dump
import ebaysdk
from ebaysdk.utils import getNodeText
from ebaysdk.exception import ConnectionError
from ebaysdk.trading import Connection as Trading
version = 1.0
def init_options():
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("-d", "--debug",
action="store_true", dest="debug", default=False,
help="Enabled debugging [default: %default]")
(opts, args) = parser.parse_args()
return opts, args
def getUPCFromItem(ItemID):
api.execute('GetItem',{'ItemID': ItemID, 'DetailLevel': 'ReturnAll','IncludeItemSpecifics': 'True'})
item = api.response_dict()
for attribute in item.Item.ItemSpecifics.NameValueList:
if attribute.Name == 'UPC':
return attribute.Value
return False
def checkDuplicate(orderID):
cursor.execute('select order_number from amz_order_header where order_number = :ord_no', ord_no = orderID)
if cursor.fetchone():
return True
return False
def processItems(items):
rtnItems = []
if isinstance(items.Transaction,list):
# Multiple items I hope are in array, guess we'll find out eventually
print "Array Process"
for item in items.Transaction:
localItem = {}
localItem['item_no'] = getUPCFromItem(item.Item.ItemID)[6:11]
localItem['qty_ord'] = item.QuantityPurchased
localItem['listprice'] = item.TransactionPrice.value
localItem['sellprice'] = item.TransactionPrice.value
localItem['sellcurr'] = ''
rtnItems.append(localItem)
else:
localItem = {}
localItem['item_no'] = getUPCFromItem(items.Transaction.Item.ItemID)[6:11]
localItem['qty_ord'] = items.Transaction.QuantityPurchased
localItem['listprice'] = items.Transaction.TransactionPrice.value
localItem['sellprice'] = items.Transaction.TransactionPrice.value
localItem['sellcurr'] = ''
rtnItems.append(localItem)
return rtnItems
def processOrder(order):
ordHdr = {}
ordHdr['ord_no'] = order.OrderID
# ordHdr['purchase_date'] = order.CreatedTime[0:10]
ordHdr['ship_customer'] = order.ShippingAddress.Name.upper()
ordHdr['ship_address1'] = order.ShippingAddress.Street1.upper()
ordHdr['ship_address2'] = order.ShippingAddress.Street2.upper() if isinstance(order.ShippingAddress.Street2,str) else ''
ordHdr['ship_address3'] = ''
ordHdr['ship_city'] = order.ShippingAddress.CityName.upper()
ordHdr['ship_state'] = order.ShippingAddress.StateOrProvince.upper()
ordHdr['ship_zip'] = order.ShippingAddress.PostalCode.upper()
ordHdr['ship_country'] = order.ShippingAddress.Country.upper()
ordHdr['ship_phone'] = order.ShippingAddress.Phone if isinstance(order.ShippingAddress.Phone,str) else ''
ordHdr['payment'] = order.MonetaryDetails.Payments.Payment.PaymentAmount.value
ordHdr['ship_handle'] = '0.00'
ordHdr['payment_curr'] = 'USD'
ordHdr['lstatus'] = 'A'
ordHdr['ship_method'] = ''
ordHdr['err_flag'] = ''
ordItems = processItems(order.TransactionArray)
for item in ordItems:
print "Item Data:"
item['ord_no'] = ordHdr['ord_no']
print item
sql = '''
insert into amz_order_line (order_number, item_id, qty, item_list_price, item_selling_price,
selling_price_cur_code, created_by,create_date,last_updated_by,last_update_date) values (
:ord_no,:item_no,:qty_ord,:listprice,:sellprice,:sellcurr,'EBYIMPORT',SYSDATE,'EBYIMPORT',
SYSDATE)
'''
cursor.execute(sql,item)
for datum in item:
print "%s:\t\t%s" % (datum,item[datum])
sql = '''
insert into amz_order_header (order_number,purchase_date, shipping_and_handling, ship_customer,
ship_address1, ship_address2, ship_address3, ship_city, ship_state, ship_country,
ship_postal_code, ship_phone_number, payment_amount, payment_currency, created_by,
create_date,last_updated_by, last_update_date, order_status,ship_method,error_flag,lead_source_code) values (
:ord_no,SYSDATE,:ship_handle,:ship_customer,:ship_address1,:ship_address2,:ship_address3,:ship_city,
:ship_state,:ship_country,:ship_zip,:ship_phone,:payment,:payment_curr,'EBYIMPORT',
SYSDATE,'EBYIMPORT',SYSDATE,:lstatus,:ship_method,:err_flag,'EBAY')
'''
print ordHdr
cursor.execute(sql,ordHdr)
for datum in ordHdr:
print "%s:\t\t%s" % (datum, ordHdr[datum])
tycus.commit()
def getOrders(opts):
try:
global api
api = Trading(debug=opts.debug,config_file = 'ebay.yaml', warnings=True, timeout=20)
global tycus, cursor
tycus = cx_Oracle.connect('<PUT YOUR ORACLE CREDENTIALS HERE>')
cursor = tycus.cursor()
cursor.execute("alter session set nls_date_format='YYYY-MM-DD'")
# Time set to GMT with the +5 offset
currentTime = datetime.datetime.now()+datetime.timedelta(hours = 5)
startTime = currentTime + datetime.timedelta(hours = -2)
api.execute('GetOrders', {'CreateTimeFrom': str(startTime)[0:19], 'CreateTimeTo': str(currentTime)[0:19],
'DetailLevel': 'ReturnAll', 'OrderStatus': 'Completed'})
orders = api.response_dict()
if int(orders.ReturnedOrderCountActual) > 0:
print "There are %s orders to process" % orders.ReturnedOrderCountActual
if isinstance(orders.OrderArray.Order,list):
for order in orders.OrderArray.Order:
if not checkDuplicate(order.OrderID):
print order.OrderID
processOrder(order)
else:
print "Order %s already processed and in amz_ tables" % order.OrderID
else:
order = orders.OrderArray.Order
if not checkDuplicate(order.OrderID):
print order.OrderID
processOrder(order)
else:
print "Order %s already processed and in amz_ tables" % order.OrderID
cursor.close()
tycus.close()
except ConnectionError as e:
print e
if __name__ == "__main__":
(opts, args) = init_options()
print("Ty Ebay fetch order script ver %s" % version )
getOrders(opts)
@Dhairya40
Copy link

Thanks it help full for me. Can please tell me example how to change the order status?

@hmarquardt
Copy link
Author

Dhairya40 -- I'm afraid I don't work with eBay in my current role and this code is from 2013 -- it's likely the API has changed since. I don't think I'm going to be much help here. Quick review of this page: https://developer.ebay.com/Devzone/post-order/index.html seems to suggest (to me!) that you don't manipulate status directly, but rather it's change is a consequence of some other action ... "providing shipping info", "issuing refund", "disputing claim" ... hope that's some help anyway.

@Dhairya40
Copy link

Dhairya40 commented Apr 4, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment