Пример #1
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,))
Пример #2
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
Пример #3
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]
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
Пример #5
0
    def ebay_sdk(self):
        try:
            api = Trading(
                config_file=False,
                appid='ReviveOn-ZestERP-PRD-05d7504c4-7e62e952',
                token=
                'AgAAAA**AQAAAA**aAAAAA**514uWg**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AFloCgAJaEogidj6x9nY+seQ**4M8DAA**AAMAAA**pJTxWPk5v7uA4HdkanTFWcUAzgQdjHsD7hreui/eFJdqrxw3PsgdsK+WGP5fY8urMJ9rmIozaeVq5Wh7rU9FchyAwcTYu42LFXXM+7Q/TGo+KhsDuWL2WGz4t4JtuFw4iVJpWWLnkdGNkMed6S+xYjvfSU0XOYKIRnSIcs4JfzK1uwgCuSaUS1ajmH5ZCpVciLjtm9pQvguT4j3odY5CoGh5wsRYMJnjvYvQqCI114Nx65XBmShPKRLVZOfvO6OWYL6bkBhd8grmR3JFYMGj5LZz3Z3lF/Xy7Qdfz9Lpjt49k7TThwXzZw0jjsKCUUJBdfEvFBg/qZcVPreCDgm3h8X3p55e78mBnqV+OQFmIh38Kk1ZKAaYiicOHxRvVxTcZib+6bBB/5Jb1gBYTLDdqYZ6BC0B6TYc49BsOE8yMAe3/VTm0V5SZw0R3WAiyy3Csj7pFy8KN6oxXwLJsC8v2RqqnueejMPp08Vn6kRohh5uoLFSiTdxMoam5Bim/3KLXH7qNeM4y720Rw/FIantaeezF5kVug9Ic/9gq84nXj1rqRfeZfRrr2BofIBF9rjiLmZ5YHHhNKXCMsLctNgCyOosPeMc08jhZIS53ELYqZ/RB8fVCIHXAZyXFy5Vg5D/2YP9T+4NELQjJgYIx2EYh079iNJMxE9jBYOsKQP5qshRuJqOCZvubTFCiJN9e0MPLaaUz5569T2Xxi9QTlSBLuaMNmEGHeFCwGKt31cWgx9oEQroxRKBE7unHGNUY9Ws',
                certid='PRD-5d7504c480f9-39be-4693-bc3c-5485',
                devid='12b0abb8-96e5-4f07-b012-97081166a3a8',
                warnings=True)

            # pass in an open file
            # the Requests module will close the file
            files = {
                'file':
                ('EbayImage', open('/home/girish/Pictures/t-shirt.png', 'rb'))
            }

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

            response = api.execute('UploadSiteHostedPictures',
                                   pictureData,
                                   files=files)
            print(response.dict())
            json.dumps(api)
        except ConnectionError as e:
            print(e)
            print(e.response.dict())
Пример #6
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())
Пример #7
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())
Пример #8
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)
Пример #9
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
Пример #10
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))
Пример #11
0
    def get_ebay_api(self, domain):
        params = self.env['ir.config_parameter'].sudo()
        dev_id = params.get_param('ebay_dev_id')
        site_id = params.get_param('ebay_site')
        site = self.env['ebay.site'].browse(int(site_id))
        if domain == 'sand':
            app_id = params.get_param('ebay_sandbox_app_id')
            cert_id = params.get_param('ebay_sandbox_cert_id')
            token = params.get_param('ebay_sandbox_token')
            domain = 'api.sandbox.ebay.com'
        else:
            app_id = params.get_param('ebay_prod_app_id')
            cert_id = params.get_param('ebay_prod_cert_id')
            token = params.get_param('ebay_prod_token')
            domain = 'api.ebay.com'

        if not app_id or not cert_id or not token:
            action = self.env.ref('sales_team.action_sale_config')
            raise RedirectWarning(_('One parameter is missing.'), action.id,
                                  _('Configure The eBay Integrator Now'))

        return Trading(domain=domain,
                       config_file=None,
                       appid=app_id,
                       devid=dev_id,
                       certid=cert_id,
                       token=token,
                       siteid=site.ebay_id)
Пример #12
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
Пример #13
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
                    }
                })
Пример #14
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)
Пример #15
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^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',
        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())
Пример #16
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']
Пример #17
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)
Пример #18
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())
Пример #19
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
    '''
Пример #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())
Пример #21
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())
Пример #22
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
    
Пример #23
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")
Пример #24
0
def dump(config):
    api = Trading(domain=config.domain, config_file=config.config_file)
    result = []

    def get_page(page_num):
        return api.execute(
            'GetMyeBaySelling', {
                'ActiveList': {
                    'Include': True,
                    'Pagination': {
                        'PageNumber': page_num
                    }
                },
                'OutputSelector': [
                    'ActiveList.PaginationResult',
                    'ActiveList.ItemArray.Item.Title',
                    'ActiveList.ItemArray.Item.ItemID',
                    'ActiveList.ItemArray.Item.BuyItNowPrice',
                    'ActiveList.ItemArray.Item.ListingDetails.ViewItemURL',
                    'ActiveList.ItemArray.Item.QuantityAvailable'
                ]
            })

    LOG.debug('dumping a list of selling items ...')
    for page_num in itertools.count(1):
        LOG.debug('items page: %d ' % page_num)
        response = get_page(page_num)
        active = response.reply.ActiveList
        page_count = int(active.PaginationResult.TotalNumberOfPages)
        result.extend(active.ItemArray.Item)
        if page_count == page_num:
            return result
Пример #25
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())
Пример #26
0
    def trading(self, cr, uid, user, call_name, parallel=None, context=None):
        api = Trading(domain=self.pool.get('ebay.ebay').get_ebay_api_domain(
            cr, uid, user.sale_site, user.sandbox),
                      parallel=parallel)

        if user.ownership:
            api.config.set('appid', user.app_id, force=True)
            api.config.set('devid', user.dev_id, force=True)
            api.config.set('certid', user.cert, force=True)

        if parallel:
            api.config.set('errors', False, force=True)

        if call_name not in ('GetSessionID', 'FetchToken'):
            token = ''
            if user.ownership and user.ebay_auth_token:
                api.config.set('token', user.ebay_auth_token, force=True)
            else:
                auth_user = self.get_arbitrary_auth_user(
                    cr, uid, user.sandbox, context)
                api.config.set('appid', auth_user.app_id, force=True)
                api.config.set('devid', auth_user.dev_id, force=True)
                api.config.set('certid', auth_user.cert, force=True)
                api.config.set('token', auth_user.ebay_auth_token, force=True)

        return api
Пример #27
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)
Пример #28
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
Пример #29
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)
Пример #30
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())