Exemplo n.º 1
1
def revise_ebay_price(item_code, new_price, is_auction):
    """Given item_code and (inc vat) price, revise the listing on eBay"""


    #get the ebay id given the item_code
    ebay_id = frappe.get_value('Item', item_code, 'ebay_id')
    if ebay_id and item_code and new_price:

        try:
            new_price_inc = float(new_price)
            api_trading = Trading(config_file=PATH_TO_YAML, warnings=True, timeout=20)

            if is_auction:
                api_trading.execute('ReviseItem', {'Item':{'ItemID':ebay_id, \
                                'StartPrice':new_price_inc}})
            else:
                # ReviseInventoryStatus enables change to price and/or quantity of an active, fixed-price listing. 
                # The fixed-price listing is identified with the ItemID of the listing or the SKUvalue of the item
                api_trading.execute('ReviseInventoryStatus', {'InventoryStatus':{'ItemID':ebay_id, \
                                    'StartPrice':new_price_inc}})

        except ConnectionError:
            return ("Connection Error - possibly ebay.yaml file not found")

        except Exception:
            return ("Price sync. There was a problem using the eBay Api")
            #raise

        else:
            return ("Price sync success - eBay listing updated!")
    else:
        return ("Price Sync Error: There was a problem getting with the item_code, price or ebayid")
Exemplo n.º 2
0
def get_category_id(keyword):
    try:
        api = Trading()

        callData = {
            'DetailLevel': 'ReturnAll',
            'CategorySiteID': 0,
            'LevelLimit': 4,
        }

        r = api.execute('GetCategories', callData)
        categories = r.dict()
        most_similar_category = {}
        max_similarity = -1
        for category in categories['CategoryArray']['Category']:
            similarity_ratio = SequenceMatcher(None,keyword,category['CategoryName']).ratio()
            if(similarity_ratio > max_similarity):
                most_similar_category = category
                max_similarity = similarity_ratio

        print("Most similar category: "+most_similar_category['CategoryName']+" at "+str(max_similarity)+" similarity")
        return most_similar_category['CategoryID'] 
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 3
0
    def _get_ebay_balance(self, par):
        api = Trading(siteid=0, config_file=self.config, timeout=40)
        currency = ['GBP', 'USD']
        for cur in currency:
            response = None
            ret = None
            for _ in range(3):
                try:
                    par['Currency'] = cur
                    response = api.execute('GetAccount', par)
                    break
                except ConnectionError:
                    ret = {'currency': cur, 'balance': 0}
                    break
                except:
                    pass

            try:
                if response:
                    summary = response.reply.AccountSummary
                    ret = summary.CurrentBalance
                    yield ret
                else:
                    yield ret
            # to-do read time out exception
            except Exception as why:
                self.logger.error(why)
Exemplo n.º 4
0
def getAllListedItems():
    try:
        # Connect to API and select all active listings
        api = Trading(domain='api.sandbox.ebay.com', config_file='ebay.yaml')
        response = api.execute('GetMyeBaySelling', {'ActiveList': True})
        # Convert response into Python JSON object
        responseDictionary = json.loads(response.json())
        # Get the count of how many active listings have been returned
        responseCount = responseDictionary["ActiveList"]["PaginationResult"][
            "TotalNumberOfEntries"]
        responseCount = int(responseCount)
        item_id_list = []
        item_price_list = []

        if (responseCount == 1):
            item_id_list.append(responseDictionary["ActiveList"]["ItemArray"]
                                ["Item"]["ItemID"])
            item_price_list.append(
                responseDictionary["ActiveList"]["ItemArray"]["Item"]
                ["SellingStatus"]["CurrentPrice"]["value"])
        else:
            # Iterate through each returned listing starting from 0 counting up by responseCount e.g if responseCount = 4 then i = 0, 1, 2, 3
            for i in range(0, responseCount):
                itemID = responseDictionary["ActiveList"]["ItemArray"]["Item"][
                    int(i)]["ItemID"]
                itemPrice = responseDictionary["ActiveList"]["ItemArray"][
                    "Item"][int(i)]["SellingStatus"]["CurrentPrice"]["value"]
                item_id_list.append(itemID)
                item_price_list.append(itemPrice)

    except ConnectionError as e:
        print(e)
        print(e.response.content)

    return item_id_list, item_price_list
Exemplo n.º 5
0
    def upload_images(self):
        for filename in glob.glob('{}*.jpg'.format(self.img_dir)):
            try:
                api = Connection(config_file=config.yaml_location,
                                 domain="api.ebay.com",
                                 debug=config.debug,
                                 siteid=config.site_id)

                # pass in an open file
                # the Requests module will close the file
                files = {'file': ('EbayImage', open(filename, 'rb'))}

                picture_data = {
                    "WarningLevel": "High",
                    "PictureName": "Item_img"
                }

                res = api.execute('UploadSiteHostedPictures',
                                  picture_data,
                                  files=files).dict()
                self.image_url_arr.append(
                    res["SiteHostedPictureDetails"]["FullURL"])
            except ConnectionError as e:
                print(e)
                print(e.response.dict())
Exemplo n.º 6
0
def get_myebay_selling_request(page):
    """get_myebay_selling_request"""
    try:
        api_trading = Trading(config_file=PATH_TO_YAML, warnings=True, timeout=20)

        api_request = {
            "ActiveList": {
                "Include": True,
                "Pagination": {
                    "EntriesPerPage": 100,
                    "PageNumber": page
                    },
                "IncludeWatchCount": True
                },
            'DetailLevel': 'ReturnAll'
            }

        api_trading.execute('GetMyeBaySelling', api_request)
        products = api_trading.response.dict()

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
        raise e

    return products
Exemplo n.º 7
0
    def update_ebay_tracking_number(self, data):
        for item in data:

            api = Trading(config_file=self.config)
            params = {
                    "RequesterCredentials": {"eBayAuthToken": item['token']},
                    'OrderLineItemID': item['l_number'] + '-' + item['l_ebayitemtxnid'],
                    'Shipment':{
                        'ShipmentTrackingDetails': {
                            "ShipmentLineItem":{
                                'LineItem':{
                                    'ItemID': item['l_number'],
                                    'Quantity': int(item['l_qty']),
                                    'TransactionID': item['l_ebayitemtxnid']
                                }
                            },
                            'ShipmentTrackingNumber': item['trackNo'],
                            # 'ShipmentTrackingNumber': '1231appy',
                            'ShippingCarrierUsed': item['code'],
                        },
                        'ShippedTime':item['closingdate']
                    },
                }

            try:
                response = api.execute('CompleteSale', params)
                result = response.dict()
                if result['Ack'] == 'Success':
                    self.update_py_trade_status(item['nid'])
                    self.logger.error('success to fetch tracking number of order num {}'.format(item['nid']))
                else:
                    self.logger.error('failed to fetch tracking number of order num {}'.format(item['nid']))
            except Exception as e:
                self.logger.error('failed to fetch tracking number of order num {} cause of {}'.format(item['nid'], e))
Exemplo n.º 8
0
def get_eBay_details(site_id=default_site_id, detail_name=None):
    """Perform a GeteBayDetails call."""

    try:
        # Initialize TradingAPI; default timeout is 20.
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id,
                      warnings=True,
                      timeout=20)

        api_options = {}
        if detail_name is not None:
            api_options['DetailName'] = detail_name

        response = api.execute('GeteBayDetails', api_options)

    except ConnectionError as e:
        handle_ebay_error(e)

    response_dict = response.dict()
    test_for_message(response_dict)

    if six.PY2:
        # Convert all strings to unicode
        response_dict = convert_to_unicode(response_dict)

    return response_dict
Exemplo n.º 9
0
def get_categories(site_id=default_site_id):
    """Load the eBay categories for the categories cache."""

    try:
        # Initialize TradingAPI; default timeout is 20.
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id,
                      warnings=True,
                      timeout=60)

        response = api.execute('GetCategories', {
            'DetailLevel': 'ReturnAll',
            'ViewAllNodes': 'true'
        })

    except ConnectionError as e:
        handle_ebay_error(e)

    categories_data = response.dict()

    if six.PY2:
        # Convert all strings to unicode
        categories_data = convert_to_unicode(categories_data)

    # Process the remaining categories data
    cl = categories_data['CategoryArray']['Category']
    # Use one dictionary element per level, to store each Category against its
    # CategoryID. For simplicity don't use the first [0] level as CategoryLevel
    # is one-indexed.
    levels = []
    for cat in cl:
        cat['Children'] = []
        cat_level = int(cat['CategoryLevel'])
        while cat_level > len(levels) - 1:
            levels.append({})
        # Add the category to the relevant level dictionary
        levels[cat_level][cat['CategoryID']] = cat

    max_level = len(levels) - 1

    # Loop over all deeper levels; connect categories to their parents
    for parent_level, level_dict in enumerate(levels[2:], start=1):
        for cat in level_dict.values():
            parent = levels[parent_level][cat['CategoryParentID']]
            parent['Children'].append(cat)

    # Sort the Children list of each category according to its CategoryName
    for cat in cl:
        cat['Children'].sort(key=operator.itemgetter('CategoryName'))

    # Sort the top level list according to the CategoryName of the categories
    top_level = levels[1].values()
    top_level.sort(key=operator.itemgetter('CategoryName'))

    categories_data['TopLevel'] = top_level

    del categories_data['CategoryArray']

    # Return the new categories
    return categories_data, max_level
Exemplo n.º 10
0
def upload_picture_from_filesystem(filepath):
    try:
        api = Trading()

        # pass in an open file
        # the Requests module will close the file
        files = {'file': ('EbayImage', open(filepath, 'rb'))}

        pictureData = {
            "WarningLevel": "High",
            "PictureName": "gtr2"
        }

        r = api.execute('UploadSiteHostedPictures', pictureData, files=files)
        response_dict = r.dict()
        #print(response_dict['SiteHostedPictureDetails'])
        #print(response_dict['SiteHostedPictureDetails']['FullURL'])
        image_url = response_dict['SiteHostedPictureDetails']['FullURL']
        return image_url



    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 11
0
def set_store(args):
    try:
        api = Trading(debug=args.debug,
                      appid=app_id,
                      token=token_id,
                      certid=cert_id,
                      devid=dev_id,
                      warnings=True,
                      timeout=20,
                      siteid=site_id,
                      config_file=None)

        storeData = {
            "Store": {
                "CustomHeader": "HOW CAN I GET SOME HTML IN HERE?a?a?a?a",
                "CustomHeaderLayout": "CustomHeaderShown",
                "Theme": {
                    "ThemeID": "1",
                    "Name": "Fireworks",
                    "ColorScheme": {
                        "ColorSchemeID": "1",
                        "Name": "Fireworks - Orange",
                        "Color": {
                            "Primary": "A9A9A9",
                            "Secondary": "F4F4F4",
                            "Accent": "FD7714"
                        },
                        "Font": {
                            "NameFace": "Arial",
                            "NameSize": "M",
                            "NameColor": "FFFFFF",
                            "TitleFace": "Arial",
                            "TitleSize": "XS",
                            "TitleColor": "FFFFFF",
                            "DescFace": "Arial",
                            "DescSize": "XS",
                            "DescColor": "333333"
                        },
                        "MessageID": " IT CIRCLE CONSULT - MAFFAS - PYTHON ",
                        "Version": "837"
                    }
                }
            }
        }

        api.execute('SetStore', storeData)
        dump(api)
        f = open(
            'E:\\ITCIRCLECONSULT\\GITHUB\\maf-ebay\\maf-ebay-dev\\get-item\\' +
            file_name + '.xml', 'a')

        f.write(
            str(api.response.content)[2:-1]
        )  # write result, removes the b' from the start, from position [2] until the ' at the end [-1]

        f.close()  #close html

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 12
0
def categories(opts):

    try:
        api = Trading(debug=opts.debug,
                      config_file=opts.yaml,
                      appid=opts.appid,
                      domain=opts.domain,
                      certid=opts.certid,
                      devid=opts.devid,
                      warnings=True,
                      timeout=20,
                      siteid='0')

        callData = {
            'DetailLevel': 'ReturnAll',
            'CategorySiteID': 101,
            'LevelLimit': 4,
        }

        api.execute('GetCategories', callData)
        dump(api, full=False)

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 13
0
def get_order_transactions(order_id):
    
    order_trans = None
    order_trans = []
    
    try:
        
        api = Trading(config_file='/home/frappe/ebay.yaml', warnings=True, timeout=20)
        
        while True:
            
            api.execute('GetOrderTransactions', {'OrderID': order_id})
            order_trans_api = api.response.dict()
            
            #if int(order_trans_api['ReturnedOrderCountActual']) > 0:
            orders.extend(order_trans_api['TransactionArray']) #['OrderTransactions'])
                


    except ConnectionError as e:
        print(e)
        print(e.response.dict())
        raise e


    return order_trans
    
Exemplo n.º 14
0
def start():

    try:
        api = Trading(debug=False,
                      config_file="../sensitive_files/buying.yaml",
                      warnings=True,
                      timeout=20,
                      siteid="0")

    except ConnectionError as e:
        print(e)

    api.execute("GetOrders", {
        'NumberOfDays': '3',
        'OrderRole': 'Buyer'
    })

    if (api.response.dict()['ReturnedOrderCountActual'] == '0'):
        return

    transactions = []
    for order in api.response.dict()['OrderArray']['Order']:
        transactions.append(Transaction(api, order))

    insertAndUpdateRecords(transactions)
Exemplo n.º 15
0
def memberMessages(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True)

        now = datetime.datetime.now()

        memberData = {
            "WarningLevel": "High",
            "MailMessageType": "All",
            # "MessageStatus": "Unanswered",
            "StartCreationTime": now - datetime.timedelta(days=60),
            "EndCreationTime": now,
            "Pagination": {
                "EntriesPerPage": "5",
                "PageNumber": "1"
            }
        }

        api.execute('GetMemberMessages', memberData)

        dump(api)

        if api.response_dict().MemberMessage:
            messages = api.response_dict().MemberMessage.MemberMessageExchange

            if type(messages) != list:
                    messages = [ messages ]

            for m in messages:
                print("%s: %s" % (m.CreationDate, m.Question.Subject[:50]))

    except ConnectionError as e:
        print e
Exemplo n.º 16
0
def get_order2tracking(dev_credentials, access_token):
    """Trading API is used with dev credentials and access token of ebay business account.
    :return { order_id: tracking }"""
    api = Trading(
        # iaf_token='v^1.1#i^1#I^3#r^0#p^3#f^0#t^H4sIAAAAAAAAAOVYW2wUVRju9oaIQOROa8gySLyQ2Tkzs9eRXVjabXaxl6XbUiQgOTtzph06OzOdM9t2JdHaQNVogxh9QWwwkhgaQ9IADyR4IRIfNJJIIAZJvFREjBjRqDz44pnphW0VeiPaxH3Yyfzn/8//f99/mTMDukrnPtoT77k53zWn8HAX6Cp0udh5YG5pyboFRYVlJQUgT8F1uOvBruLuomvrMcyohlCPsKFrGLk7M6qGBUcYprKmJugQK1jQYAZhwRKFVLSmWuA8QDBM3dJFXaXcicowlUasFPJxkFwQSkOWSLWRPRt0si7xkk90/oDE+31kHeMsSmjYgpoVpjjAhmiWozm+gWUFLiAAzhP0hrZT7q3IxIquERUPoCJOuIJja+bFeudQIcbItMgmVCQRrUrVRROVsdqG9UzeXpFhHlIWtLJ47F2FLiH3Vqhm0Z3dYEdbSGVFEWFMMZEhD2M3FaIjwUwjfIdqny8tcQiIaRgEIpuW7gqVVbqZgdad47AlikTLjqqANEuxchMxSthI70aiNXxXS7ZIVLrty5YsVBVZQWaYim2KPtGYitVT7lQyaertioQkGykH/CGW54IhLxWBom5gb2DYxdA+wwSP81Gha5Ji04Xdtbq1CZF40XhW2DxWiFKdVmdGZcuOJV+PH2XPv91O51D+slaLZmcUZQgFbud2Yu5HiuFW+u9WOaAQHxKRHOSQn/NzEn+bcrB7fUolEbGzEk0mGTsW0tI5OgPNVmQZKhQRLRJ6sxlkKpLA+2SOD8qIlvwhmfaGZJlO+yQ/zcoIATIM0mIo+P+oDMsylXTWQqPVMX7BgUdSRtgUFCgLlt6KtIacgajxms64GS6JThymWizLEBimo6PD08F7dLOZ4QBgmW011SmxBWUgNaqrTKxMK05xiIhYYUWwSABhqpPUHnGuNVOR+lhVfSwV39VQ93isdqRux0QWGS+9DdIUEk1kzS50rblgs1qV2c3XbWuvbdoNE16/7u+ol9riuU2pdaC6HUqJpqeqcXKzGJ4ZeFKYKKmripj7dxlwen0CFnhTSkLTyqWQqhLBjIBiG+jsSrJtj8kG0FA8drt5RD3D6JAMa1u0y4nYPRklBhOCPEOjj+zsMRGUdE3NTcd4CjaK1k7mh27mpuNw1HgKNlAU9axmTcfdsOkULOSsKiuqao/I6TjMM59KmBpUc5Yi4mm5VDS72vAUTAyYcwBKCjbsXpmUJZGRp6qIPORJ5xywRoO9TYfavT65Lo0aRiKTyVowraKENLva1Qu8vJeb0RCy4c0yVFEVddboGNMNJhRbiYhO1lfSLB8MBvwiB2lvkA9AjvXOCHdNszLLYLMhf4gHIc5nm80IWyVqn205Dcg8nw6QY6BX4kkGORSkg96ARCMvecUVIe9Ns/KMMFeoCun8fzwUFj979T/FHtexhaTJohsnyDsU/+1NiBn7ESJS4PzYbtdJ0O0aKHS5AAPWsmvA6tKixuKi+8qwYpEJCWUPVpo18m5tIk8ryhlQMQtLXcor55+7mPfZ4/BOsGL0w8fcInZe3lcQ8MCtlRJ24fL5bIjlOJ5luQDgtoM1t1aL2WXFS47/ebkRFJ06J6Bl5qoFsh6sXNsE5o8quVwlBcXdroJUP2g79vFH8YUHfj82UK7wx2NvDijML6n+8h6l1y/vu4jLChsvgL4zizNx87TnyB8/9F38nLpwvngFs3TDj3uYt3pibe+cGGj0G3xw1eLNyxddufDiyl+P8Puv36j9Jvzh/T+XvHzoaerexTs61qdbvu+71r9xcOl315j4zkWvv/qeeqT3qLbyC+OhY4euHrrx7Wcb+luv+E9e2tsQ+fSrS6cf68Zle5Ibl+Dyg1Jf074vT74Pml/acurA/kuXadc91BsnBs1nrh8tHzhbcuC3K5+E46/dfHjtnvQjc87sMMJnBg+u5H9694POwXPrIBWf0/v2C0Xsvg1mX8nqvRXtz5d+HWk7W8uUPrlgKH1/AbCsHnGQEgAA',
        iaf_token=access_token,
        config_file=None,
        # appid='AlexMoss-Tracking-PRD-138876c2a-4837a214',
        appid=dev_credentials.appid,
        # certid='PRD-38876c2ad8b8-53bb-4b68-981a-92f9',
        certid=dev_credentials.certid,
        # devid='7f33b712-4d3a-42e8-847d-e4bd3ca34b1f',
        devid=dev_credentials.devid,
        # proxy_host= '5.79.66.2',
        # proxy_port= '13010',
        warnings=True)
    try:
        response_test = api.execute(
            'GetOrders', {
                'CreateTimeFrom': datetime.now() - timedelta(days=90),
                'CreateTimeTo': datetime.now()
            })

        def extract_tracking(order):
            return order.TransactionArray.Transaction[
                0].ShippingDetails.ShipmentTrackingDetails.ShipmentTrackingNumber

        order_id2tracking = {
            order.OrderID: extract_tracking(order)
            for order in response_test.reply.OrderArray
        }
        return order_id2tracking
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 17
0
def get_myebay_selling_request(page):
    """get_myebay_selling_request"""
    try:
        api_trading = Trading(config_file=PATH_TO_YAML,
                              warnings=True,
                              timeout=20)

        api_request = {
            "ActiveList": {
                "Include": True,
                "Pagination": {
                    "EntriesPerPage": 100,
                    "PageNumber": page
                },
                "IncludeWatchCount": True
            },
            'DetailLevel': 'ReturnAll'
        }

        api_trading.execute('GetMyeBaySelling', api_request)
        products = api_trading.response.dict()

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
        raise e

    return products
Exemplo n.º 18
0
def get_eBay_details(site_id=default_site_id, detail_name=None):
    """Perform a GeteBayDetails call."""

    try:
        # Initialize TradingAPI; default timeout is 20.
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id, warnings=True, timeout=20)

        api_options = {}
        if detail_name is not None:
            api_options['DetailName'] = detail_name

        response = api.execute('GeteBayDetails', api_options)

    except ConnectionError as e:
        handle_ebay_error(e)

    response_dict = response.dict()
    test_for_message(response_dict)

    if six.PY2:
        # Convert all strings to unicode
        response_dict = convert_to_unicode(response_dict)

    return response_dict
Exemplo n.º 19
0
def revise_ebay_price(item_code, new_price, is_auction):
    """Given item_code and price, revise the listing on eBay"""


    #get the ebay id given the item_code
    ebay_id = frappe.get_value('Item', item_code, 'ebay_id')
    if ebay_id and item_code and new_price:

        try:
            new_price_inc = float(new_price) * ugssettings.VAT
            api_trading = Trading(config_file=PATH_TO_YAML, warnings=True, timeout=20)

            if is_auction:
                api_trading.execute('ReviseItem', {'Item':{'ItemID':ebay_id, \
                                'StartPrice':new_price_inc}})
            else:
                # ReviseInventoryStatus enables change to price and/or quantity of an active, fixed-price listing. 
                # The fixed-price listing is identified with the ItemID of the listing or the SKUvalue of the item
                api_trading.execute('ReviseInventoryStatus', {'InventoryStatus':{'ItemID':ebay_id, \
                                    'StartPrice':new_price_inc}})

        except ConnectionError:
            return ("Connection Error - possibly ebay.yaml file not found")

        except Exception:
            return ("Price sync. There was a problem using the eBay Api")
            #raise

        else:
            return ("Price sync success - eBay listing updated!")
    else:
        return ("Price Sync Error: There was a problem getting with the item_code, price or ebayid")
Exemplo n.º 20
0
def UploadPictures(opts, image_file, image_name):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                                  certid=opts.certid, devid=opts.devid, warnings=False)
        
        try:
            with Image.open(image_file) as im:
                # scale the image to a suitable size
                # use thumbnail to scale to the bounding box
                # use resize if you want to calculate the dims 
                im.thumbnail((1600,1600))
                with io.BytesIO() as fp:
                    im.save(fp, "JPEG")
            
                    files = {'file': ('EbayImage', fp.getvalue())}
                    pictureData = {
                        "WarningLevel": "High",
                        "PictureSet":'Supersize',
                        "PictureName": image_name
                    }
                    response = api.execute('UploadSiteHostedPictures', pictureData, files=files)
                    url = response.reply.SiteHostedPictureDetails.FullURL  
                    
                    return url
            
            dump(api)
        except:
            pass
            
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 21
0
def EndItems(Items):
    api = Connection(config_file='user.yaml', domain="api.ebay.com")

    temp_data = '{"EndItemRequestContainer":['
    #request =json.loads("{}")

    #res = Items.split(",")
    i = 1

    for iid in Items:
        temp_data = temp_data + '{"MessageID":' + "\"" + str(
            i
        ) + "\"" + ',"EndingReason":"NotAvailable","ItemID": \"' + iid + '\" }'
        if (len(Items) > i):
            temp_data = temp_data + ','
        i = i + 1

    temp_data = temp_data + ']}'
    #print(temp_data)
    #request = eval(temp_data)
    request = json.loads(temp_data)
    print(request)
    response = api.execute('EndItems', request)

    print(f"{response.reply.Ack}")
Exemplo n.º 22
0
 def __init__(
     self,
     domain='api.ebay.com',
     appid='ZhouPeng-3242-4cc7-88fd-310f513fcd71',
     devid='df3f2898-65b1-4e15-afd5-172b989903aa',
     certid='a0e19cf9-9b2b-457f-b6f1-87f3f600ca63',
     # token='AgAAAA**AQAAAA**aAAAAA**cJyLVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wMkoqiC5mHoQmdj6x9nY+seQ**N+QCAA**AAMAAA**nLCwNt4AQt1TRtd2ydNIMuZ2JYnQZKVVYarn41QQfBSqccEDld22ltKr+C/HJTN8AKD4+jn/nIEqtjNMkmh9sxTIa6jVVLAH5sN/93X7gTCmTkOsE/Av612U90nRoyQJ5bX1+NO25tMDZs9U0aTJIwVVu1BAB8/nsjL0pTCWw7KZACJ+a/aQ6swXLvSvOCWIBjFyCaWibKZseT2LoJMvJQmC2QpIuDsQ8cTYozLUYZqC88uKAjo7DNWIvaPVCdwkp/Vux3arR1Asin4ewX1l+LWCamWsXeBiVyaYq/oEUXABgknieVAPEpaFAfSzlrcTNmTWLBDDRwRGI/8hJCwK6/eJWexGrLk7U7p0kRltktNseTckAKT7g1ED4C5gUeQ4/nTHsNQBejUPTzTlwBWTJpwRaBFD7dAlbagH+TKaEJK41Esf/ZpL2599LUMolsO8tBgo0BhtCF/bYtdUUfopksIKNUwPXikadUxx6TurknnTtR1WDD229uUJIIf9BCS68WB56OfDTdXcZ8rdPZ0zdHuw5+BRxrumpFUzTQb5fJeHRDLPtQbLdX5rFPrS+NPJl6Qzi7bWNxUCydNQcIzKv7xLquIPoPx8bD1PRCoQbzjTQsOqhe9PBvLtcJ0Ggve78YjQKb5nDt6YThZ6D+1EOKdcthU03VizDfBKBLJ/NPqktDTx74tsS3l4feAjblGDoQ2RZXefJ9Jk3t+Qc4khlvl4mKpjZ4sCakh4qPWr9H6t3CN80hz5MO1Y7uHPUY61',
     token='AgAAAA**AQAAAA**aAAAAA**aCRbWA**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wDmYShCJCHogmdj6x9nY+seQ**N+QCAA**AAMAAA**ktFg8zDYputToOiGDvTfZku93pjbVq3rGn7AR53h1eWAByiTLP+Gd8uKuDof0BQ0prvskMARI/nHxkjFYUp7IUsQkZ6sH/E2UmmvRRwqDHZ/XsXt0+meLqS6ZHMjw7v/CpISJqnZjGChDSYPFRe6RboawkjPi8ial5wEXojlvNWvHl02yT92ih6dTYj44g2xprmmyOSyTYC8l8oG+YLKZ+FPzOj5zxO3Qm8rhVtQwc1KGGtHnthz2ZwHwbeFDh8cVp1qaFQmCaHc27ftM8/to2U22mccon5zRk6yf59EiN88WPzag/ii0XpkwELXWRsHKBfl/9pepWUqWZvgjhQ9jcGQsrYyQfS6T54dLcaJ7a2IrCxOvpdkv4Z26T7CpTpUBbYzG4olJI42jFMZBu5quqOanio2qbHNFov5Jq85jMR9Zx51KlKezNaauIW16upj7P2gvCwDt+E7xCQMoqKDrIyx7J0g0KLHKhSavzeC0vnrF0H9NAfqxVEdYtLUgbR9A8JQagPAYp+vPuMpSEbhc5/fTLBfD6YFSoJ+izMzx0n6Gj2df5n77hS3X1850eLzqzCREtUClZfJ7tcTMR+oU8i0aB75rWDr/sFKsfgW/rAe8hcuMzYBms+rsL4i7ddt5KWfCieMksAfabdUrPF5Owfr/24en/omwHXtBrb39u/oMKTfGZOS2JKyXdbpmpV1YWsJ8eDzxNIN0hJfG6wqrjdEJAUX5dkg4j5L5UXE6deogb9MUYHJgkP3nch5yPfS',
     # timeout=3
 ):
     self.idomain = domain
     self.iappid = appid
     self.idevid = devid
     self.icertid = certid
     self.itoken = token
     # self.timeout=
     self.mycon = Connection(
         domain=self.idomain,
         appid=self.iappid,
         devid=self.idevid,
         certid=self.icertid,
         token=self.itoken,
         timeout=15,
         config_file=None,
         #proxy_host='127.0.0.1',
         #proxy_port='1080'
     )
Exemplo n.º 23
0
def revise_inventory_status(item_id, price=None, quantity=None, sku=None):
    """Revise the price or quantity or SKU of an item you own on ebay given
    its item id. A price or quantity must be provided at the very least.

    :param item_id: ebay item id
    :param price: change item price to this
    :param quantity: change item quantity to this
    :param sku: change item SKU to this
    :return: the response from ebay api call
    """
    if price is None and quantity is None:
        raise EbayScriptsException('price or quantity needs to be specified')

    api = Trading(config_file=EBAY_API)

    new_status = {'ItemID': item_id}
    if quantity is not None:
        new_status.update({'Quantity': quantity})
    if price is not None:
        new_status.update({'StartPrice': price})
    if sku is not None:
        new_status.update({'SKU': sku})

    response = api.execute('ReviseInventoryStatus',
                           {'InventoryStatus': new_status})

    pretty_reply = pformat(convert_rdo_to_dict(response.reply))
    print(pretty_reply)
    # LOGGER.info(pretty_reply)

    return response
Exemplo n.º 24
0
 def get_order(self, order_id):
     api = Trading(config_file=None, **self.credentials)
     response = api.execute('GetOrders',
                            {'OrderIDArray': [{
                                'OrderID': order_id
                            }]})
     return response.reply.OrderArray.Order[0]
Exemplo n.º 25
0
def categories(args):

    try:
        api = Trading(debug=args.debug,
                      appid=app_id,
                      token=token_id,
                      certid=cert_id,
                      devid=dev_id,
                      warnings=True,
                      timeout=20,
                      siteid=site_id,
                      config_file=None)

        callData = {
            'DetailLevel': 'ReturnAll',
            'CategorySiteID': site_id,
            'LevelLimit': 1,
        }

        api.execute('GetCategories', callData)
        dump(api, full=False)

    except ConnectionError as e:
        print(e)
        print(e.response.dict())


# Get Store Catergories
    '''
Exemplo n.º 26
0
def get_item(item_id=None, item_code=None, site_id=default_site_id):
    """Returns a single listing from the eBay TradingAPI."""

    if not (item_code or item_id):
        raise ValueError('No item_code or item_id passed to get_item!')

    api_dict = {'IncludeWatchCount': True}
    if item_code:
        api_dict['SKU'] = item_code
    if item_id:
        api_dict['ItemID'] = item_id

    try:
        # Initialize TradingAPI; default timeout is 20.

        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id, warnings=True, timeout=20)

        api.execute('GetItem', api_dict)

        listing = api.response.dict()
        test_for_message(listing)

    except ConnectionError as e:
        handle_ebay_error(e)

    if six.PY2:
        # Convert all strings to unicode
        listing = convert_to_unicode(listing)

    return listing['Item']
Exemplo n.º 27
0
def categories(opts, tree_level):

    try:
        api = Trading(domain=opts['domain'],
                      debug=opts['debug'],
                      config_file=opts['config_fpath'],
                      appid=opts['appid'],
                      certid=opts['certid'],
                      devid=opts['devid'],
                      warnings=False,
                      timeout=20,
                      siteid='101')

        q = {
            'DetailLevel': 'ReturnAll',
            'CategorySiteID': 0,
            'LevelLimit': 4,
        }

        api.execute('GetCategories', callData)
        return dump(api, full=False)

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 28
0
def get_categories_versions(site_id=default_site_id):
    """Load the version number of the current eBay categories
    and category features.
    """

    try:
        # Initialize TradingAPI; default timeout is 20.
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id,
                      warnings=True,
                      timeout=20)

        response1 = api.execute('GetCategories', {
            'LevelLimit': 1,
            'ViewAllNodes': False
        })
        test_for_message(response1.dict())

        response2 = api.execute('GetCategoryFeatures', {})
        test_for_message(response2.dict())

    except ConnectionError as e:
        handle_ebay_error(e)

    categories_version = response1.reply.CategoryVersion
    features_version = response2.reply.CategoryVersion

    return (categories_version, features_version)
Exemplo n.º 29
0
def get_item(item_id=None,
             item_code=None,
             site_id=default_site_id,
             output_selector=None):
    """Returns a single listing from the eBay TradingAPI."""

    if not (item_code or item_id):
        raise ValueError('No item_code or item_id passed to get_item!')

    api_dict = {'IncludeWatchCount': True}
    if output_selector:
        api_dict['OutputSelector'] = ['ItemID', 'Item.Site'] + output_selector
    if item_code:
        api_dict['SKU'] = item_code
    if item_id:
        api_dict['ItemID'] = item_id
    try:
        # Initialize TradingAPI; default timeout is 20.

        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id,
                      warnings=True,
                      timeout=20)

        api.execute('GetItem', api_dict)

        listing = api.response.dict()
        test_for_message(listing)

    except ConnectionError as e:
        handle_ebay_error(e)

    return listing['Item']
Exemplo n.º 30
0
def ImportEbay(FeedbackContents, INVOICE, TRACK, LOGICSTICS):
    FeedbacksCount = sum(1 for i in FeedbackContents)
    CountTrack = sum(1 for i in OrderDetails)
    for i in range(0, CountTrack):
        if OrderDetails[i]['INVOICE'].split(
                '|')[0][0:1] == 'U' or OrderDetails[i]['INVOICE'].split(
                    '|')[0][:1] == 'V':
            CONFIG = f'{INVOICE.split("|")[0]}.yaml'
            api = Trading(config_file=CONFIG, domain='api.ebay.com')
            UserID = INVOICE.split('|')[1]
            OrderLineItemID = INVOICE.split('|')[2]
            RandomFeedback = FeedbackContents[random.randint(
                0, FeedbacksCount - 1)]
            ImportTracking = {
                'FeedbackInfo': {
                    'CommentText': RandomFeedback,
                    'CommentType': 'Positive',
                    'TargetUser': UserID
                },
                'OrderLineItemID': OrderLineItemID,
                'Shipment': {
                    'ShipmentTrackingDetails': {
                        'ShipmentTrackingNumber': TRACK,
                        'ShippingCarrierUsed': LOGICSTICS
                    }
                },
                'Shipped': 1
            }
            api.execute('CompleteSale', ImportTracking)
    DigitalComplete(FeedbackContents)
Exemplo n.º 31
0
def revise_ebay_price(item_code, new_price, is_auction=False):
    """Given item_code and (inc vat) price, revise the listing on eBay"""

    # get the ebay id given the item_code
    ebay_id = frappe.get_value('Item', item_code, 'ebay_id')
    if not ebay_id and item_code and new_price:
        raise ValueError(
            'Price Sync Error: There was a problem getting with the ' +
            'item_code, price or eBay ID')

        new_price_inc = float(new_price)
        api_trading = Trading(config_file=PATH_TO_YAML,
                              warnings=True,
                              timeout=20)

        if is_auction:
            api_trading.execute(
                'ReviseItem',
                {'Item': {
                    'ItemID': ebay_id,
                    'StartPrice': new_price_inc
                }})
        else:
            # ReviseInventoryStatus enables change to price and/or quantity
            # of an active, fixed-price listing.
            # The fixed-price listing is identified with the ItemID of the
            # listing or the SKUvalue of the item
            api_trading.execute(
                'ReviseInventoryStatus', {
                    'InventoryStatus': {
                        'ItemID': ebay_id,
                        'StartPrice': new_price_inc
                    }
                })
Exemplo n.º 32
0
 def ebay_execute(self, verb, data=None, list_nodes=[], verb_attrs=None, files=None, raise_exception=False):
     self.ensure_one()
     if self.ebay_domain == 'sand':
         domain = 'api.sandbox.ebay.com'
     else:
         domain = 'api.ebay.com'
     if self.is_external_store:
         ok = self.test_proxy()
         if not ok:
             _logger.error('Store has proxy but proxy is not working!')
             return
         else:
             ebay_api = Trading(domain=domain,
                                https=True,
                                proxy_host=self.https_proxy,
                                proxy_port=self.https_port,
                                config_file=None,
                                appid=self.ebay_app_id,
                                devid=self.ebay_dev_id,
                                certid=self.ebay_cert_id,
                                token=self.ebay_token,
                                siteid=str(self.ebay_site_id))
     else:
         ebay_api = Trading(domain=domain,
                            config_file=None,
                            appid=self.ebay_app_id,
                            devid=self.ebay_dev_id,
                            certid=self.ebay_cert_id,
                            token=self.ebay_token,
                            siteid=str(self.ebay_site_id))
     try:
         return ebay_api.execute(verb, data, list_nodes, verb_attrs, files)
     except ConnectionError as e:
         errors = e.response.dict()['Errors']
         if not raise_exception:
             _logger.error(e)
             return
         if not isinstance(errors, list):
             errors = [errors]
         error_message = ''
         for error in errors:
             if error['SeverityCode'] == 'Error':
                 error_message += error['LongMessage']
         if 'Condition is required for this category.' in error_message:
             error_message += _('Or the condition is not compatible with the category.')
         if any(s in error for s in ['Internal error to the application', 'Internal application error']):
             error_message = _('eBay is unreachable. Please try again later.')
         if 'Invalid Multi-SKU item id supplied with variations' in error_message:
             error_message = _('Impossible to revise a listing into a multi-variations listing.\n Create a new listing.')
         if 'UPC is missing a value.' in error_message:
             error_message = _('The UPC value (the barcode value of your product) is not valid by using the checksum.')
         if 'must have a quantity greater than 0' in error_message:
             error_message += _(" If you want to set quantity to 0, the Out Of Stock option should be enabled"
                               " and the listing duration should set to Good 'Til Canceled")
         if 'Item Specifics entered for a Multi-SKU item should be different' in error_message:
             error_message = _(" You need to have at least 2 variations selected for a multi-variations listing.\n"
                                " Or if you try to delete a variation, you cannot do it by unselecting it."
                                " Setting the quantity to 0 is the safest method to make a variation unavailable.")
         raise UserError(_("Error Encountered.\n'%s'") % (error_message,))
Exemplo n.º 33
0
def update(config, changes):
    api = Trading(domain=config.domain, config_file=config.config_file)
    for change in changes:
        try:
            api.execute('ReviseFixedPriceItem', change)
            LOG.info('%s is successfully changed. ' % change['Item']['ItemID'])
        except ConnectionError as error:
            LOG.error(error)
Exemplo n.º 34
0
def get_orders():
    """Returns a list of recent orders from the eBay TradingAPI.

    This list is NOT filtered by a siteid as the API call does not filter
    by siteid.
    """

    num_days = frappe.db.get_value(
        'eBay Manager Settings', filters=None, fieldname='ebay_sync_days')

    try:
        if num_days < 1:
            frappe.msgprint('Invalid number of days: ' + str(num_days))
    except TypeError:
        raise ValueError('Invalid type in ebay_sync_days')

    orders = []
    page = 1

    try:
        # Initialize TradingAPI; default timeout is 20.

        # Always use the US site for GetOrders as it returns fields we need
        # (which the UK site, for example, doesn't) and it doesn't filter by
        # siteID anyway
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=0, warnings=True, timeout=20)

        while True:
            # TradingAPI results are paginated, so loop until
            # all pages have been obtained
            api.execute('GetOrders', {
                'NumberOfDays': num_days,
                'Pagination': {
                    'EntriesPerPage': 50,
                    'PageNumber': page}
                })

            orders_api = api.response.dict()
            test_for_message(orders_api)

            n_orders = int(orders_api['ReturnedOrderCountActual'])
            if n_orders == 1:
                orders.append(orders_api['OrderArray']['Order'])
            elif n_orders > 0:
                orders.extend(orders_api['OrderArray']['Order'])
            if orders_api['HasMoreOrders'] == 'false':
                break
            page += 1

    except ConnectionError as e:
        handle_ebay_error(e)

    if six.PY2:
        # Convert all strings to unicode
        orders = convert_to_unicode(orders)

    return orders, num_days
Exemplo n.º 35
0
def verifyAddItemErrorCodes(opts):
    """http://www.utilities-online.info/xmltojson/#.UXli2it4avc
    """

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=False)

        myitem = {
            "Item": {
                "Title": "Harry Potter and the Philosopher's Stone",
                "Description": "This is the first book in the Harry Potter series. In excellent condition!",
                "PrimaryCategory": {"CategoryID": "377aaaaaa"},
                "StartPrice": "1.0",
                "CategoryMappingAllowed": "true",
                "Country": "US",
                "ConditionID": "3000",
                "Currency": "USD",
                "DispatchTimeMax": "3",
                "ListingDuration": "Days_7",
                "ListingType": "Chinese",
                "PaymentMethods": "PayPal",
                "PayPalEmailAddress": "*****@*****.**",
                "PictureDetails": {"PictureURL": "http://i1.sandbox.ebayimg.com/03/i/00/30/07/20_1.JPG?set_id=8800005007"},
                "PostalCode": "95125",
                "Quantity": "1",
                "ReturnPolicy": {
                    "ReturnsAcceptedOption": "ReturnsAccepted",
                    "RefundOption": "MoneyBack",
                    "ReturnsWithinOption": "Days_30",
                    "Description": "If you are not satisfied, return the book for refund.",
                    "ShippingCostPaidByOption": "Buyer"
                },
                "ShippingDetails": {
                    "ShippingType": "Flat",
                    "ShippingServiceOptions": {
                        "ShippingServicePriority": "1",
                        "ShippingService": "USPSMedia",
                        "ShippingServiceCost": "2.50"
                    }
                },
                "Site": "US"
            }
        }

        api.execute('VerifyAddItem', myitem)

    except ConnectionError as e:
        # traverse the DOM to look for error codes
        for node in api.response.dom().findall('ErrorCode'):
            print("error code: %s" % node.text)

        # check for invalid data - error code 37
        if 37 in api.response_codes():
            print("Invalid data in request")

        print(e)
        print(e.response.dict())
Exemplo n.º 36
0
def verifyAddItemErrorCodes(opts):
    """http://www.utilities-online.info/xmltojson/#.UXli2it4avc
    """

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=False)

        myitem = {
            "Item": {
                "Title": "Harry Potter and the Philosopher's Stone",
                "Description": "This is the first book in the Harry Potter series. In excellent condition!",
                "PrimaryCategory": {"CategoryID": "377aaaaaa"},
                "StartPrice": "1.0",
                "CategoryMappingAllowed": "true",
                "Country": "US",
                "ConditionID": "3000",
                "Currency": "USD",
                "DispatchTimeMax": "3",
                "ListingDuration": "Days_7",
                "ListingType": "Chinese",
                "PaymentMethods": "PayPal",
                "PayPalEmailAddress": "*****@*****.**",
                "PictureDetails": {"PictureURL": "http://i1.sandbox.ebayimg.com/03/i/00/30/07/20_1.JPG?set_id=8800005007"},
                "PostalCode": "95125",
                "Quantity": "1",
                "ReturnPolicy": {
                    "ReturnsAcceptedOption": "ReturnsAccepted",
                    "RefundOption": "MoneyBack",
                    "ReturnsWithinOption": "Days_30",
                    "Description": "If you are not satisfied, return the book for refund.",
                    "ShippingCostPaidByOption": "Buyer"
                },
                "ShippingDetails": {
                    "ShippingType": "Flat",
                    "ShippingServiceOptions": {
                        "ShippingServicePriority": "1",
                        "ShippingService": "USPSMedia",
                        "ShippingServiceCost": "2.50"
                    }
                },
                "Site": "US"
            }
        }

        api.execute('VerifyAddItem', myitem)
    
    except ConnectionError as e:
        # traverse the DOM to look for error codes
        for node in api.response.dom().findall('ErrorCode'):
            print("error code: %s" % node.text)

        # check for invalid data - error code 37
        if 37 in api.response_codes():
            print("Invalid data in request")

        print(e)
        print(e.response.dict())
Exemplo n.º 37
0
def test_get_item(item):
	api = Connection(config_file='ebay.yaml')
	details_dict = dict()
	try: 
		response = api.execute('GetItem',{"ItemID":item,"OutputSelector":"Seller","DetailLevel":"ReturnAll"})
		details = response.reply.Item
		print details
	except Exception as e:
		print e
Exemplo n.º 38
0
def test_get_user(item):
	api = Connection(config_file='ebay.yaml')
	details_dict = dict()
	try: 
		response = api.execute('GetUser',{"UserID":item,"DetailLevel":"ReturnAll"})
		details = response.reply
		print details
	except Exception as e:
		print e
Exemplo n.º 39
0
def AddItem(opts):
    """http://www.utilities-online.info/xmltojson/#.UXli2it4avc
    """

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=False)

        myitem = {
            "Item": {
                "Title": "Harry Potter and the Philosopher's Stone",
                "Description": "<![CDATA[HTML go here]]>",
                "PrimaryCategory": {"CategoryID": "377"},
                "StartPrice": "1.0",
                "CategoryMappingAllowed": "true",
                "Country": "US",
                "ConditionID": "3000",
                "Currency": "USD",
                "DispatchTimeMax": "3",
                "ListingDuration": "Days_7",
                "ListingType": "Chinese",
                "PaymentMethods": "PayPal",
                "PayPalEmailAddress": "*****@*****.**",
                "PictureDetails": {
                    "PictureURL": "http://i.ebayimg.com/00/s/NzY4WDEwMjQ=/z/6S4AAOSw2x1XMFYY/$_12.JPG?set_id=880000500F"
                    },
                "PostalCode": "95125",
                "Quantity": "1",
                "ReturnPolicy": {
                    "ReturnsAcceptedOption": "ReturnsAccepted",
                    "RefundOption": "MoneyBack",
                    "ReturnsWithinOption": "Days_30",
                    "Description": "If you are not satisfied, return the book for refund.",
                    "ShippingCostPaidByOption": "Buyer"
                },
                "ShippingDetails": {
                    "ShippingType": "Flat",
                    "ShippingServiceOptions": {
                        "ShippingServicePriority": "1",
                        "ShippingService": "USPSMedia",
                        "ShippingServiceCost": "2.50"
                    }
                },
                "Site": "US"
            }
        }

        response = api.execute('AddItem', myitem)
        dump(api)
        
        return response.dict()

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
        
        return e.response.dict()
Exemplo n.º 40
0
def get_categories(site_id=default_site_id):
    """Load the eBay categories for the categories cache."""

    try:
        # Initialize TradingAPI; default timeout is 20.
        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id, warnings=True, timeout=60)

        response = api.execute('GetCategories', {'DetailLevel': 'ReturnAll',
                                                 'ViewAllNodes': 'true'})

    except ConnectionError as e:
        handle_ebay_error(e)

    categories_data = response.dict()

    if six.PY2:
        # Convert all strings to unicode
        categories_data = convert_to_unicode(categories_data)

    # Process the remaining categories data
    cl = categories_data['CategoryArray']['Category']
    # Use one dictionary element per level, to store each Category against its
    # CategoryID. For simplicity don't use the first [0] level as CategoryLevel
    # is one-indexed.
    levels = []
    for cat in cl:
        cat['Children'] = []
        cat_level = int(cat['CategoryLevel'])
        while cat_level > len(levels)-1:
            levels.append({})
        # Add the category to the relevant level dictionary
        levels[cat_level][cat['CategoryID']] = cat

    max_level = len(levels) - 1

    # Loop over all deeper levels; connect categories to their parents
    for parent_level, level_dict in enumerate(levels[2:], start=1):
        for cat in level_dict.values():
            parent = levels[parent_level][cat['CategoryParentID']]
            parent['Children'].append(cat)

    # Sort the Children list of each category according to its CategoryName
    for cat in cl:
        cat['Children'].sort(key=operator.itemgetter('CategoryName'))

    # Sort the top level list according to the CategoryName of the categories
    top_level = levels[1].values()
    top_level.sort(key=operator.itemgetter('CategoryName'))

    categories_data['TopLevel'] = top_level

    del categories_data['CategoryArray']

    # Return the new categories
    return categories_data, max_level
Exemplo n.º 41
0
def getUser(opts):
    try:

        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True, timeout=20, siteid=101)

        api.execute('GetUser', {'UserID': 'biddergoat'})
        dump(api, full=False)
    
    except ConnectionError as e:
        print e
Exemplo n.º 42
0
def getOrders(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True, timeout=20)

        api.execute('GetOrders', {'NumberOfDays': 30})
        dump(api, full=False)

    except ConnectionError as e:
        print e
Exemplo n.º 43
0
def getTokenStatus(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=False)

        api.execute('GetTokenStatus')
        dump(api)

    except ConnectionError as e:
        print e
Exemplo n.º 44
0
def getxml(myset):
    mycon = Connection(domain='api.ebay.com',
                appid='ZhouPeng-3242-4cc7-88fd-310f513fcd71',
                devid='df3f2898-65b1-4e15-afd5-172b989903aa',
                certid='a0e19cf9-9b2b-457f-b6f1-87f3f600ca63',
                token='AgAAAA**AQAAAA**aAAAAA**cJyLVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wMkoqiC5mHoQmdj6x9nY+seQ**N+QCAA**AAMAAA**nLCwNt4AQt1TRtd2ydNIMuZ2JYnQZKVVYarn41QQfBSqccEDld22ltKr+C/HJTN8AKD4+jn/nIEqtjNMkmh9sxTIa6jVVLAH5sN/93X7gTCmTkOsE/Av612U90nRoyQJ5bX1+NO25tMDZs9U0aTJIwVVu1BAB8/nsjL0pTCWw7KZACJ+a/aQ6swXLvSvOCWIBjFyCaWibKZseT2LoJMvJQmC2QpIuDsQ8cTYozLUYZqC88uKAjo7DNWIvaPVCdwkp/Vux3arR1Asin4ewX1l+LWCamWsXeBiVyaYq/oEUXABgknieVAPEpaFAfSzlrcTNmTWLBDDRwRGI/8hJCwK6/eJWexGrLk7U7p0kRltktNseTckAKT7g1ED4C5gUeQ4/nTHsNQBejUPTzTlwBWTJpwRaBFD7dAlbagH+TKaEJK41Esf/ZpL2599LUMolsO8tBgo0BhtCF/bYtdUUfopksIKNUwPXikadUxx6TurknnTtR1WDD229uUJIIf9BCS68WB56OfDTdXcZ8rdPZ0zdHuw5+BRxrumpFUzTQb5fJeHRDLPtQbLdX5rFPrS+NPJl6Qzi7bWNxUCydNQcIzKv7xLquIPoPx8bD1PRCoQbzjTQsOqhe9PBvLtcJ0Ggve78YjQKb5nDt6YThZ6D+1EOKdcthU03VizDfBKBLJ/NPqktDTx74tsS3l4feAjblGDoQ2RZXefJ9Jk3t+Qc4khlvl4mKpjZ4sCakh4qPWr9H6t3CN80hz5MO1Y7uHPUY61',

                )
    for ele in myset:
        myrequest={'ItemID':ele,'IncludeWatchCount':True}
        myresponse=mycon.execute('GetItem',myrequest)
        yield myresponse.text
Exemplo n.º 45
0
def getUser(opts):
    try:

        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True, timeout=20, siteid='101')

        api.execute('GetUser', {'UserID': 'sallyma789'})
        dump(api, full=False)

    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 46
0
def check_ebay_item_exists(itemID):
    ''' 
    True if Item exists   
    '''
    try:
        api = Trading(debug=False, config_file=config_file, appid=appid,
                      certid=certid, devid=devid,warnings=False)
        api.execute('GetItem', {'ItemID': itemID})
        return True
       
    except ConnectionError as e:
        return False
Exemplo n.º 47
0
def run(api_request, params):
    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid, certid=opts.certid, devid=opts.devid)

        response = api.execute(api_request, params)

        dump(api)
        # print(api.response.reply.Charity.Name)
        return response.dict()
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 48
0
def run(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid)

        api.execute('GetCharities', {'CharityID': 3897})
        dump(api)
        print(api.response_dict().Charity.Name)

    except ConnectionError as e:
        print e
Exemplo n.º 49
0
def GetOrders(
        CreateTimeFrom=None,
        CreateTimeTo=None,
        IncludeFinalValueFee=False,
        ModTimeFrom=None,
        ModTimeTo=None,
        NumberOfDays=None,
        OrderID=None,
        DetailLevel=None
    ):

    options = {}
    
    if CreateTimeFrom:
        options['CreateTimeFrom'] = CreateTimeFrom
    if CreateTimeTo:
        options['CreateTimeTo'] = CreateTimeTo

    if IncludeFinalValueFee:
        options['IncludeFinalValueFee'] = str(IncludeFinalValueFee).lower()
    
    if ModTimeFrom:
        options['ModTimeFrom'] = ModTimeFrom
    if ModTimeTo:
        options['ModTimeTo'] = ModTimeTo
    
    if NumberOfDays:
        options['NumberOfDays'] = int(NumberOfDays)
    
    if OrderID:
        options['OrderIDArray'] = { 'OrderID': OrderID }
    
    if DetailLevel:
        options['DetailLevel'] = DetailLevel
    
    trading = Trading()
    options['Pagination'] = { 'EntriesPerPage': '1000', 'PageNumber': 0 }
    has_more = True

    while has_more:
        options['Pagination']['PageNumber'] += 1
        
        try:
            response = trading.execute('GetOrders', options)
        except ConnectionError as e:
            raise Exception('ConnectionError:\n%s' % json.dumps(e.response.dict(), sort_keys=True, indent=5))
        else:
            yield response
        
        has_more = response.dict().get('HasMoreEntries') == "true"
Exemplo n.º 50
0
def get_ebay_item_price(itemID):
    ''' 
    searches for itemID and returns the start price.    
    '''
    try:
        api = Trading(debug=False, config_file=config_file, appid=appid,
                      certid=certid, devid=devid,warnings=False)
    
        api.execute('GetItem', {'ItemID': itemID})
        return float(api.response.reply.Item.StartPrice.value)
       
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
        return False
Exemplo n.º 51
0
def feedback(opts):
    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=False)

        api.execute('GetFeedback', {'UserID': 'tim0th3us'})
        dump(api)

        if int(api.response_dict().FeedbackScore) > 50:
            print("Doing good!")
        else:
            print("Sell more, buy more..")
    
    except ConnectionError as e:
        print e
Exemplo n.º 52
0
def get_seller_list(item_codes=None, site_id=default_site_id):
    """Runs GetSellerList to obtain a list of items."""

    # Create eBay acceptable datetime stamps for EndTimeTo and EndTimeFrom
    end_from = datetime.utcnow().isoformat()[:-3] + 'Z'
    end_to = (datetime.utcnow() + timedelta(days=119)).isoformat()[:-3] + 'Z'

    listings = []

    try:
        # Initialize TradingAPI; default timeout is 20.

        api = Trading(config_file=PATH_TO_YAML,
                      siteid=site_id, warnings=True, timeout=20)

        page = 1
        while True:
            # TradingAPI results are paginated, so loop until
            # all pages have been obtained
            api.execute('GetSellerList', {
                'SKUArray': {'SKU': item_codes},
                'EndTimeTo': end_to,
                'EndTimeFrom': end_from,
                'Pagination': {
                    'EntriesPerPage': 50,
                    'PageNumber': page}
                })

            listings_api = api.response.dict()
            test_for_message(listings_api)

            n_listings = int(listings_api['ReturnedItemCountActual'])
            if n_listings == 1:
                listings.append(listings_api['ItemArray']['Item'])
            elif int(listings_api['ReturnedItemCountActual']) > 0:
                listings.extend(listings_api['ItemArray']['Item'])
            if listings_api['HasMoreItems'] == 'false':
                break
            page += 1

    except ConnectionError as e:
        handle_ebay_error(e)

    if six.PY2:
        # Convert all strings to unicode
        listings = convert_to_unicode(listings)

    return listings
Exemplo n.º 53
0
def test_AddFixedPriceItem():  
    try:
        api = Trading(config_file=config_file, appid=appid,
                      certid=certid, devid=devid, warnings=False)

        myitem = {
            "Item": {
                "Title": "Harry Potter and the Philosopher's Stone",
                "Description": "This is the first book in the Harry Potter series. In excellent condition!",
                "PrimaryCategory": {"CategoryID": "377"},
                "StartPrice": "100",
                "CategoryMappingAllowed": "true",
                "Country": "US",
                "ConditionID": "3000",
                "Currency": "USD",
                "DispatchTimeMax": "3",
                "ListingDuration": "Days_7",
                "ListingType": "FixedPriceItem",
                "PaymentMethods": "PayPal",
                "PayPalEmailAddress": "*****@*****.**",
                "PictureDetails": {"PictureURL": "https://upload.wikimedia.org/wikipedia/en/b/bf/Harry_Potter_and_the_Sorcerer's_Stone.jpg"},
                "PostalCode": "95125",
                "Quantity": "1",
                "ReturnPolicy": {
                    "ReturnsAcceptedOption": "ReturnsAccepted",
                    "RefundOption": "MoneyBack",
                    "ReturnsWithinOption": "Days_30",
                    "Description": "If you are not satisfied, return the book for refund.",
                    "ShippingCostPaidByOption": "Buyer"
                },
                "ShippingDetails": {
                    "ShippingType": "Flat",
                    "ShippingServiceOptions": {
                        "ShippingServicePriority": "1",
                        "ShippingService": "UPS3rdDay",
                        "ShippingServiceCost": "2.50"
                    }
                },
                "Site": "US"
            }
        }

        return(api.execute('VerifyAddFixedPriceItem', myitem))
        
    except ConnectionError as e:
        print(e)
        print(e.response.dict())
Exemplo n.º 54
0
def get_item_details(itemid):
	api = Connection(config_file="ebay.yaml")
	request = {
		"ItemID":itemid,
		"OutputSelector":"Item",
	}
	item_details = dict()
	try:
		response = api.execute("GetItem",request)
		item_details_tree = response.reply.Item
		item_details["itemid"]=itemid
		item_details["quantitysold"] = item_details_tree.SellingStatus.QuantitySold
		item_details["hitcount"] = item_details_tree.HitCount
		# print item_details
	except Exception as e:
		print e
	return item_details
Exemplo n.º 55
0
def categories(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True, timeout=20, siteid=101)

        callData = {
            'DetailLevel': 'ReturnAll',
            'CategorySiteID': 101,
            'LevelLimit': 4,
        }

        api.execute('GetCategories', callData)
        dump(api, full=False)

    except ConnectionError as e:
        print e
Exemplo n.º 56
0
def uploadPicture(opts):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True)

        pictureData = {
            "WarningLevel": "High",
            "ExternalPictureURL": "http://developer.ebay.com/DevZone/XML/docs/images/hp_book_image.jpg",
            "PictureName": "WorldLeaders"
        }

        api.execute('UploadSiteHostedPictures', pictureData)
        dump(api)

    except ConnectionError as e:
        print e
Exemplo n.º 57
0
def getAllListings():
	
	dn = os.path.dirname(os.path.realpath(__file__))
	api = Connection(domain=getConfig("default","Domain"),config_file=os.path.join(dn,"ebay.yaml"))
	timeFilters = getTimeFilter()
	query = [api.execute('GetSellerList',f).dict() for f in timeFilters]
	f = False
	f2 = False
	ret = []
	for listing in query:

		try:
			for item in listing["ItemArray"]["Item"]:
				if type(item) is not str:
					ret.append([item["Title"],item["ListingDetails"]["ViewItemURL"],item["ItemID"]])
		except AttributeError as e:
			pass

	return ret
Exemplo n.º 58
0
class ItemRequest:
    def __init__(self, credentials):
        self.trading = Trading(config_file=None, **credentials)

    def get_items(self, fields):
        for page_num in itertools.count(1):
            response = self._get_page(page_num, fields)
            activelist = response.reply.ActiveList
            page_count = int(activelist.PaginationResult.TotalNumberOfPages)
            print('Page {} of {}'.format(page_num, page_count))

            for item in response.dict()['ActiveList']['ItemArray']['Item']:
                yield item

            if page_count == page_num:
                break

    def get_item_ids(self):
        for item in self.get_items(fields=[]):
            yield item['ItemID']

    def get_item(self, item_id, params):
        params.update({'ItemID': item_id})
        response = self.trading.execute('GetItem', params)
        return response.dict()['Item']

    def _get_page(self, page_num, fields=[]):
        fields = fields + [
            'ActiveList.PaginationResult',
            'ActiveList.ItemArray.Item.ItemID',
        ]

        return self.trading.execute('GetMyeBaySelling', {
            'ActiveList': {
                'Include': True,
                'Pagination': {
                    'PageNumber': page_num
                }
            },
            'OutputSelector': fields,
        })
Exemplo n.º 59
0
def dev_ReviseFixedPriceItem(ItemID,newPrice):
    ''' change ebay listing if price changed '''    
       
    try:
        api = Trading(config_file=config_file, appid=appid,
                      certid=certid, devid=devid, warnings=False,)

        myitem = {
            "Item": {
                "ItemID": str(ItemID),
                "StartPrice": str(newPrice)                
            }
        }

        return(api.execute('ReviseFixedPriceItem', myitem))
        
    except ConnectionError as e:
        print(e)
        print(e.response.dict())

    return True
Exemplo n.º 60
0
def uploadPictureFromFilesystem(opts, filepath):

    try:
        api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid,
                      certid=opts.certid, devid=opts.devid, warnings=True)

        # pass in an open file
        # the Requests module will close the file
        files = {'file': ('EbayImage', open(filepath, 'rb'))}

        pictureData = {
            "WarningLevel": "High",
            "PictureName": "WorldLeaders"
        }

        api.execute('UploadSiteHostedPictures', pictureData, files=files)
        dump(api)

    except ConnectionError as e:
        print(e)
        print(e.response.dict())