Giter Club home page Giter Club logo

mws-api's Introduction

mws-api

Amazon MWS Node.js modules are a mess. This project is based on multiple projects from this.

Promise based. Only compatible with Node ^4.0.0. (unless someone adds a babel precompilation step)

Supports throttling and pagification. (NextToken stuff)

Examples

Installation:

npm i mws-api -S

Initialization:

const MWSClient = require('mws-api');
const mws = new MWSClient({
  accessKeyId: 'lol',
  secretAccessKey: 'kek',
  merchantId: 'hue',
  meta: {
    retry: true, // retry requests when throttled
    next: true, // auto-paginate
    limit: Infinity // only get this number of items (NOT the same as MaxRequestsPerPage)
  }
});

For other countries, also set the host parameter, according to the MarketPlaceId you are using, otherwise it leads to AccessDenied error. For example:

...
const mws = new MWSClient({
  host: 'mws.amazonservices.co.uk', // .de, .es, .fr, .it, etc
  ...
}

Usage:

mws.Orders.ListOrders({
  MarketplaceId: 'lel',
  MaxResultsPerPage: 10,
  CreatedAfter: new Date(1,1,2015),
  CreatedBefore: new Date(1,2,2015)
})
.then(({ result, metadata }) => {
  // result
});

Flat files:

When working with a flat-file response from Amazon, a parseCSVResult function is provided as an option to conviniently post-process the result. Returning a Promise will result in the Promise being resolved.

// An example to change the encoding of the raw response
const iconv = require('iconv-lite');
const MWSClient = require('mws-api');
const mws = new MWSClient({
  accessKeyId: 'lol',
  secretAccessKey: 'kek',
  merchantId: 'hue',
  meta: {
    parseCSVResult: (data) => iconv.encode(data, 'utf-8').toString()
  }
});

mws-api's People

Contributors

barrycarlyon avatar dakk avatar dciccale avatar greenkeeperio-bot avatar tyscorp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mws-api's Issues

MWSClient is not a function

Hey guys,
sorry for molesting but I've got a problem using your libary. I'am trying to execute this function on AWS Lambda, but I've getting this error all the time...

260870fe-c7c9-11e6-98c9-818bc8b674a1 TypeError: MWSClient is not a function
at exports.handler (/var/task/index.js:10:17)

my code is:

const MWSClient = require('mws-api');

exports.handler = (event, context, callback) => {

//Check if required variables are given, if not exit
  if (event.accessKeyId && event.secretAccessKey && event.merchantId && event.ReportType) {

    // mws authentication
    const mws = new MWSClient(JSON.parse(JSON.stringify({
      accessKeyId: event.accessKeyId,
      secretAccessKey: event.secretAccessKey,
      merchantId: event.merchantId,
      host: event.MarketplaceURL,
      meta: {
        retry: event.Retry,
        next: event.Next,
        limit: event.Limit
      }
    })));

  mws.Reports.RequestReport(JSON.parse(JSON.stringify({
      ReportType: event.ReportType,
      StartDate: new Date(event.StartDate),
      EndDate: new Date(event.EndDate),
      ReportOptions: event.ReportOptions,
      MarketplaceIdList: event.MarketplaceIdList
    })))
    .then(function(result, metadata) {
      // result
      console.log(JSON.stringify(result));
      console.log(JSON.stringify(metadata));
      context.done(null, result);
    });


  } else {
    callback("ERROR: accessKeyId, secretAccessKey, merchantId missing");
    console.log("ERROR:accessKeyId, secretAccessKey, merchantId missing");
    process.exit(1);
  }

}

I would be so thankful if someone can help me :)

special characters like Ä, ö, ü

Thank you for this library. Special characters like ä, ö, ü, etc. are not handled properly… instead ö for example is returned as ö

Any hint how to encode responses right?

Orders GetServiceStatus

When calling GetServiceStatus for the Orders API I get "Cannot read property 'list' of undefined" errors.
Looking through the code it would appear that /lib/request.js is checking for param.list when there isn't a param object.

I implemented a quick fix to check if param exists before trying to check if it has properties and executing this block of code. "if (param){" . This fixes the immediate error but I haven't had time to check if this is quite the right place to do this. Maybe the /lib/sections should define an empty params on GetServiceStatus ?

Here is the complete change, line 152 in /lib/request.js

            // Lists need to be sequentially numbered and we take care of that here
            if (param) {
                if (param.list) {
                    const values = _.map(toCollection(value), getValue);

                    _.forEach(values, (value, i) => {
                        this.values[`${param.name}.${i + 1}`] = value;
                    });
                } else {
                    this.values[param.name] = getValue(value);
                }
            }

Quite happy to do a pull request if this is ok

List fields request exception

When I try to use an API where the argument is a list, I got an exception:

mws.Products.GetMatchingProduct({ MarketplaceId: market, ASINList: [asin] }).then(function ({ result, metadata }) {
});
/home/dakk/Repositories/MyRepos/ProductsBroker/node_modules/mws-api/lib/request.js:158
            if (param.list) {
                     ^

TypeError: Cannot read property 'list' of undefined
    at AmazonMwsRequest.set (/home/dakk/Repositories/MyRepos/ProductsBroker/node_modules/mws-api/lib/request.js:158:22)

Multiple orders/fulfils. No MerchantID

As per notes in pr #75 and some in #82

The tests are wrong, the tests omit the required MerchantIdentifier and Amazon rejects feeds that don't contain this header key.

XSD is here: https://images-na.ssl-images-amazon.com/images/G/01/rainier/help/xsd/release_1_9/amzn-header.xsd

Currently my test fix is:

Using the merchantID from the first entry in the data. Which then means setting the merchantID on (first/each) passed in message.

Does it make more sense to set the merchantID when constructing the AmazonMwsClient

const _POST_ORDER_FULFILLMENT_DATA_ = createEnvelope(function (data) {
    const messages = Array.isArray(data) ? data : [data];

    return {
        MerchantIdentifier: messages[0].MerchantIdentifier,
        MessageType: 'OrderFulfillment',
        PurgeAndReplace: messages[0].PurgeAndReplace,
        Message: messages.map((m) => ({
            MessageID: m.MessageID,
            OrderFulfillment: {
                AmazonOrderID: m.AmazonOrderID,
                MerchantOrderID: m.MerchantOrderID,
                MerchantFulfillmentID: m.MerchantFulfillmentID,
                FulfillmentDate: m.FulfillmentDate,
                FulfillmentData: {
                    CarrierCode: m.CarrierCode,
                    CarrierName: m.CarrierName,
                    ShippingMethod: m.ShippingMethod,
                    ShipperTrackingNumber: m.ShipperTrackingNumber
                },
                Item: {
                    MerchantFulfillmentItemID: m.MerchantFulfillmentItemID,
                    Quantity: m.Quantity
                }
            }
        }))
    };
});

Unexpected complex element termination

I'm trying to create Fulfillment Outbound Shipment and that's what I get :
<Error> <Type>Sender</Type> <Code>MalformedInput</Code> <Message>Unexpected complex element termination</Message> </Error> <RequestId>8a03fed0-6631-4638-95a0-d99d05ecbb55</RequestId> </ErrorResponse> { ErrorResponse: { '$': { xmlns: 'http://mws.amazonaws.com/FulfillmentOutboundShipment/2010-10-01/' }, Error: [ [Object] ], RequestId: [ '8a03fed0-6631-4638-95a0-d99d05ecbb55' ] } }

Encoding issue

Hi, when getting a response as tab-delimited flat file, the body of the response is going through this bit of code in client.js:137

if (body.slice(0, 5) !== '<?xml') {
    const result = iconv.decode(new Buffer(body), 'iso-8859-1');
    const metadata = null;

    return { result, metadata };
}

The response has German words in it like "Staubbehältervolumen" which after doing the encoding conversion is turned into "Staubbehältervolumen" which is messed up.

Is that decoding necessary for some reason or we could just remove it? I think the default encoding from mws api is already iso-8859-1 but not entirely sure.

UPDATE

Checking the raw response headers, I see is already coming as ISO-8859-1

headers:
  { server: 'Server',
       date: 'Sun, 11 Dec 2016 19:31:58 GMT',
       'content-type': 'text/plain;charset=ISO-8859-1',
       'content-length': '750',
...

so it should be safe to remove that decoding. and leave it as

if (body.slice(0, 5) !== '<?xml') {
    return { result: body, metadata: null };
}

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Request signature not matching

I am getting the following error:

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

My code:

const mws = new MWSClient({
  accessKeyId: 'myAccessKey',
  secretAccessKey: 'mySecretAccessKey',
  merchantId: 'myMerchantId',
  meta: {
    retry: true,
    next: true,
    limit: Infinity,
  }
})   

mws.Products.GetMatchingProductForId({
    MarketplaceId: 'myMarketPlaceId',
    IdType: 'ISBN',
    IdList: {
      Id: ['9780439708180']
    }
  })

Any help would be greatly appreciated.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Creating fulfillment with multiple <Message>'s

normally, this should be allowed and is encouraged by amazon api docs, sending less requests and somewhat bigger files with multiple fulfillments. (up to around 10mb). Under multiple <Message> tags by increasing the <MessageID>

<?xml version="1.0" encoding="UTF-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
  <Header>
    <DocumentVersion>1.01</DocumentVersion>
    <MerchantIdentifier>test</MerchantIdentifier>
  </Header>
  <MessageType>OrderFulfillment</MessageType>
  <Message>
    <MessageID>1</MessageID>
    <OrderFulfillment>
      <AmazonOrderID>102-9395366-2079430</AmazonOrderID> // order id
      <MerchantFulfillmentID>1</MerchantFulfillmentID> // May not be needed
      <FulfillmentDate>2013-07-18T21:58:28.000-04:00</FulfillmentDate>
      <FulfillmentData>
        <CarrierCode>UPS</CarrierCode>
        <ShippingMethod>UPS Ground</ShippingMethod>
        <ShipperTrackingNumber>1Z86A94T0398667660</ShipperTrackingNumber>
      </FulfillmentData>
    </OrderFulfillment>
  </Message>
  <Message>
    <MessageID>2</MessageID>
    <OrderFulfillment>
      <AmazonOrderID>102-9395366-2079430</AmazonOrderID> // order id
      <MerchantFulfillmentID>1</MerchantFulfillmentID>
      <FulfillmentDate>2013-07-18T21:58:28.000-04:00</FulfillmentDate>
      <FulfillmentData>
        <CarrierCode>UPS</CarrierCode>
        <ShippingMethod>UPS Ground</ShippingMethod>
        <ShipperTrackingNumber>1Z86A94T0398667660</ShipperTrackingNumber>
      </FulfillmentData>
    </OrderFulfillment>
  </Message>
</AmazonEnvelope>

However with mws-api I can only create one at a time:

const Feeds = require('mws-api/feeds');
mws.Feeds.SubmitFeed({
    FeedContent: Feeds._POST_ORDER_FULFILLMENT_DATA_({
      MessageID: 1,
      MerchantOrderID: 1234567,
      MerchantFulfillmentID: 1234567,
      FulfillmentDate: '2002-05-01T15:36:33-08:00',
      CarrierCode: 'DHL Paket',
      ShippingMethod: 'DHL Paket',
      ShipperTrackingNumber: '1234567890'
    }),
    FeedType: '_POST_ORDER_FULFILLMENT_DATA_'
  })
  .then((res) => {
    console.log(res)
  })
  .catch((e) => {
    console.log('error', e);
  })

Is there a way to do this which I am not aware of?

I have been looking at the code in libs/feeds/orders.js which uses createEnvelope function, however this is used like everywhere and I don't feel confortable change it.

I could propose a PR after some feedback on this.

outbound shipping (FBA) example

any chance to get an example hwo to send a outbound shipping (fba) feed with items? I really struggle with the code so far and can't find a full example.

EDITED for clarity

InputDataError calling RequestReport

I'm getting InputDataError when running GetReport after successfully running RequestReport. Code:
mws.Reports.RequestReport({ ReportType: '_GET_V1_SELLER_PERFORMANCE_REPORT_', MarketplaceIdList: 'ATVPDKIKX0DER', StartDate: '2018-10-01', EndDate: '2018-10-31', }) .then(({ result, metadata }) => { console.log(result, "metadata: ", metadata) console.log("reportID: ",result.ReportRequestInfo.ReportRequestId) mws.Reports.GetReport({ ReportId: result.ReportRequestInfo.ReportRequestId }) .then(({ result, metadata })=> { console.log("result: ",result, "metadata: ", metadata) }) .catch((error)=> { console.log(error) }) }) .catch((error)=> { console.log(error) })

"Uncaught TypeError: exists is not a function" in Meteor app

I get the following error upon initializing the mws-api in my Meteor app. Any idea how to get around this issue? Running my code on Node directly from the console works fine so seems to be a Meteor issue?

modules.js?hash=c0646c9…:103512 Uncaught TypeError: exists is not a function at Function.getRoot (modules.js?hash=c0646c9…:103512) at bindings (modules.js?hash=c0646c9…:103414) at meteorInstall.node_modules.node-expat.lib.node-expat.js (modules.js?hash=c0646c9…:103224) at fileEvaluate (modules-runtime.js?hash=2b888cb…:207) at require (modules-runtime.js?hash=2b888cb…:130) at meteorInstall.node_modules.xml2json.lib.xml2json.js (modules.js?hash=c0646c9…:101709) at fileEvaluate (modules-runtime.js?hash=2b888cb…:207) at require (modules-runtime.js?hash=2b888cb…:130) at meteorInstall.node_modules.xml2json.lib.index.js (modules.js?hash=c0646c9…:101696) at fileEvaluate (modules-runtime.js?hash=2b888cb…:207) at require (modules-runtime.js?hash=2b888cb…:130) at meteorInstall.node_modules.xml2json.index.js (modules.js?hash=c0646c9…:101682) at fileEvaluate (modules-runtime.js?hash=2b888cb…:207) at require (modules-runtime.js?hash=2b888cb…:130) at meteorInstall.node_modules.mws-api.lib.client.js (modules.js?hash=c0646c9…:759) at fileEvaluate (modules-runtime.js?hash=2b888cb…:207)

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Product Feed

Hi,

any news on the support of product feed?

I'm mainly interested in POST_PRODUCT_PRICING_DATA and POST_INVENTORY_AVAILABILITY_DATA.

Regards,

Do not enable longStackTraces, consider using Promise.getNewLibraryCopy

Should not globally set longStackTraces option from bluebird (https://github.com/beardon/mws-api/blob/master/lib/client.js#L15) because it will be set in bluebird singleton instance itself, forcing my or any project to have this enabled even in the production environment. Which apparently it can have a 2x-3x performance impact http://bluebirdjs.com/docs/api/promise.config.html#comment-3322469547

Consider using Promise.getNewLibraryCopy http://bluebirdjs.com/docs/api/promise.getnewlibrarycopy.html to create a custom instance and enable longStackTraces to that instance.

const Promise = require('bluebird');
console.log(Promise.hasLongStackTraces()); // false (bluebird's default)
const mws = require('mws-api');
console.log(Promise.hasLongStackTraces()); // true (after importing mws-api)

Missing required MWSAuthToken for Seller

i got an error:
Missing required MWSAuthToken for Seller

code:
const mws = new MWSClient({
MWSAuthToken: 'mwstokenfrommyaccount',
accessKeyId: 'myaccesskey',
secretAccessKey: 'mysecretkey',
merchantId: 'merchantIdsample',
meta: {
retry: true, // retry requests when throttled
next: true, // auto-paginate
limit: Infinity, // only get this number of items (NOT the same as MaxRequestsPerPage)
},
});

Issues with CreateInboundShipmentPlan

Hi there,

I'm seeming to have some bugs with CreateInboundShipmentPlan. I believe it's an API-related bug so I'd be happy to collaborate a bit and get a fix for this one.

My request looks like:

mws.FulfillmentInboundShipment.CreateInboundShipmentPlan({
            InboundShipmentPlanRequestItems: items,
            LabelPrepPreference: "SELLER_LABEL",
            ShipFromAddressLine1: address.AddressLine1,
            ShipFromCity: address.City,
            ShipFromCountryCode: address.CountryCode,
            ShipFromName: address.Name,
            ShipFromPostalCode: address.PostalCode,
            ShipFromStateOrProvince: address.StateOrProvinceCode,
            ShipToCountryCode: "US"
        }).then(({
            result,
            metadata
        }) => {
           // ... etc

None of the address items are null; I've triple checked on that end.

Items is formatted like the following, which should be correct according to the API:

[{"SellerSKU":"(whatever SKU)","Quantity":"15","Condition":"NewItem","ASIN":"(whatever ASIN)"}]

On the module, the code looks like the following. I did modify this method a bit; "params" was "parms" prior, which I believe was a typo. Also, a few variables were left out, so I decided to add those in. Unfortunately though, I'm still getting a invalid request error from MWS and I'm not exactly sure where it is.

Thanks so much for any help you can provide! I'd be happy to send a donation for your time. Additionally, I have fixes for a couple of methods in the API - I'd be happy to provide them in this comment if needed!

CreateInboundShipmentPlan: {

        params: {
            LabelPrepPreference: {
                required
            },
            ShipFromName: {
                name: 'ShipFromAddress.Name',
                required
            },
            ShipFromAddressLine1: {
                name: 'ShipFromAddress.AddressLine1',
                required
            },
            ShipFromCity: {
                name: 'ShipFromAddress.City',
                required
            },
            ShipFromStateOrProvince: {
                name: 'ShipFromAddress.StateOrProvinceCode',
                required
            },
            ShipFromPostalCode: {
                name: 'ShipFromAddress.PostalCode',
                required
            },
            ShipFromCountryCode: {
                name: 'ShipFromAddress.CountryCode',
                required
            },
            ShipFromAddressLine2: {
                name: 'ShipFromAddress.AddressLine2'
            },
            ShipFromDistrictOrCounty: {
                name: 'ShipFromAddress.DistrictOrCounty'
            },
            ShipToCountryCode: {
                required
            },
            InboundShipmentPlanRequestItems: {
                type: Type.COMPLEX,
                required,
                construct: complex.InboundShipmentPlanRequestItems
            }
        }
    },

Signature error calling GetReportList

I get the following error when calling GetReportList.

"Error: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."
From previous event:
at AmazonMwsClient.call (/.../node_modules/mws-api/lib/client.js:130:43)
at req.query.then (/.../node_modules/mws-api/lib/client.js:254:45)

All the other calls I've tried to the Reports section work fine without error. Suggestions?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Enums aren't used

A number of enums are defined – for example, in sections/fulfillment.js, we have:

const enums = {
    ResponseGroups() {
        return new Enum(['Basic', 'Detailed']);
    },
    ShippingSpeedCategories() {
        return new Enum(['Standard', 'Expedited', 'Priority']);
    },
    FulfillmentPolicies() {
        return new Enum(['FillOrKill', 'FillAll', 'FillAllAvailable']);
    }
};

– but none are used. Would require grabbing the section's enums in api.js, passing into AmazonMwsRequest, and handling enum types in getValueForParam in request.js

Missing required MWSAuthToken for Seller.

import mws, os
access_key = '' #replace with your access key
secret_key = '' #replace with your secret key
seller_id = '' #replace with your seller id
auth_token=""
marketplaceids=''
created_after='2018-12-31'
orders_api = mws.Orders(access_key, secret_key, seller_id, region='US')
orders = orders_api.list_orders(marketplaceids='ATVPDKIKX0DER', created_after='2019-01-01')


MWSError Traceback (most recent call last)
in ()
7 created_after='2018-12-31'
8 orders_api = mws.Orders(access_key, secret_key, seller_id, region='US')
----> 9 orders = orders_api.list_orders(marketplaceids='ATVPDKIKX0DER', created_after='2019-01-01')
10

/usr/local/lib/python2.7/dist-packages/mws/utils.pyc in _wrapped_func(self, *args, **kwargs)
248 # Token captured: run the "next" action.
249 return self.action_by_next_token(action_name, next_token)
--> 250 return request_func(self, *args, **kwargs)
251 return _wrapped_func
252 return _decorator

/usr/local/lib/python2.7/dist-packages/mws/mws.pyc in list_orders(self, marketplaceids, created_after, created_before, lastupdatedafter, lastupdatedbefore, orderstatus, fulfillment_channels, payment_methods, buyer_email, seller_orderid, max_results, next_token)
541 data.update(utils.enumerate_param('FulfillmentChannel.Channel.', fulfillment_channels))
542 data.update(utils.enumerate_param('PaymentMethod.Method.', payment_methods))
--> 543 return self.make_request(data)
544
545 def list_orders_by_next_token(self, token):

/usr/local/lib/python2.7/dist-packages/mws/mws.pyc in make_request(self, extra_data, method, **kwargs)
259 error = MWSError(str(e.response.text))
260 error.response = e.response
--> 261 raise error
262
263 # Store the response object in the parsed_response for quick access

MWSError:


Sender
AccessDenied
Missing required MWSAuthToken for Seller.

93eb14c8-7f06-4967-981f-9b0e806ffcf8

Bug: XML/CSV detection heuristic is inaccurate

if (body.slice(0, 5) !== '<?xml') {

FulfillmentInventory.ListInventorySupply call does not return a valid XML prolog, thereby <?xml test fails and the CSV is assumed.

First line of the response is:

<ListInventorySupplyResponse xmlns="http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/">

Throttled requests in ListOrders operation

When amount of orders is more then 600 there is now way to get all orders at once because the request is throttled. maxResultsPerPage value must be less than 100 so in order to get 600 orders it has to be 6 requests to amazon when maximum request quota is 6: Amazon doc
How to solve this problem??

Error: Request is throttled

It doesn't happen all the time, however since I have imports of orders on cron job (every 3 minutes) I sometimes find my server crashed with this error:

{ Error: Request is throttled
    at Promise.try (/home/api/e-shop-sync/node_modules/mws-api/lib/client.js:144:33)
    at tryCatcher (/home/api/e-shop-sync/node_modules/bluebird/js/release/util.js:16:23)
    at Function.Promise.attempt.Promise.try (/home/api/e-shop-sync/node_modules/bluebird/js/release/method.js:39:29)
    at request.then (/home/api/e-shop-sync/node_modules/mws-api/lib/client.js:140:31)
    at tryCatcher (/home/api/e-shop-sync/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/api/e-shop-sync/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/api/e-shop-sync/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/home/api/e-shop-sync/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/home/api/e-shop-sync/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/home/api/e-shop-sync/node_modules/bluebird/js/release/promise.js:638:18)
    at Request._callback (/home/api/e-shop-sync/node_modules/bluebird/js/release/nodeback.js:42:21)
    at Request.self.callback (/home/api/e-shop-sync/node_modules/request/request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:194:7)
    at Request.<anonymous> (/home/api/e-shop-sync/node_modules/request/request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:191:7)
    at IncomingMessage.<anonymous> (/home/api/e-shop-sync/node_modules/request/request.js:1091:12)
    at Object.onceWrapper (events.js:293:19)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:188:7)
    at endReadableNT (_stream_readable.js:975:12) code: 'RequestThrottled', type: {}
}

Here is my setup:

    if (!marketplaceCredentials.other.meta) {

        marketplaceCredentials.other.meta = {
            retry: true, // retry requests when throttled
            next: true, // auto-paginate
            limit: Infinity // only get this number of items (NOT the same as MaxRequestsPerPage)
        }

    }

    this.mws = new MWSClient(marketplaceCredentials.other);

And here is where I am getting orders:

    if (!query) {
        return Promise.reject("Query not provided");
    }

    if (!query.fromDate) {
        return Promise.reject("From date not provided");
    }

    return new Promise((resolve, reject) => {

        this.mws.Orders.ListOrders({
            MarketplaceId: this.credentials.other.marketplaceId,
            LastUpdatedAfter: new Date(query.fromDate),
        }).then(({result, metadata}) => {

            let that = this;

            console.log("getOrders => orders.length", result.length);

            return Promise.map(result, function (orderItem, index) {

                return that.mws.Orders.ListOrderItems({AmazonOrderId: orderItem.AmazonOrderId}).then(res => {
                    console.log("orderItem.AmazonOrderId", orderItem.AmazonOrderId);
                    orderItem.listOrderItems = res.result;
                    return Promise.resolve(orderItem);
                });

            }, {concurrency: 5});

        }).then(function (result) {

            resolve(result);

        }).catch(error => {
            console.log(error);
            reject(error);
        });

    });

ListOrders with pagination turned on throws an error.

Hey @tyscorp. Thanks a lot for putting this together. Really appreciate it. Not sure if I'm not making the call properly, but I have a setup (to fetch orders) that looks something like so:

  var mws = new MWSClient({
    accessKeyId: ACCESS_KEY_ID,
    secretAccessKey: SECRET_KEY,
    merchantId: this._sellerId,
    authToken: this._authToken,
    host: 'mws-eu.amazonservices.com',
    meta: {
      retry: true, // retry requests when throttled
      next: true, // auto-paginate
      limit: Infinity // only get this number of items (NOT the same as MaxRequestsPerPage)
    }
  })

    mws.Orders.ListOrders({
      MarketplaceId: marketplaceId,
      MaxResultsPerPage: 5,
      CreatedAfter: createdAfter,
      OrderStatus: ['Unshipped', 'PartiallyShipped']
    })
    .then(function (result, meta) {
      //...
    })
    .catch(function (err) {
      //...
    });

When I run this an exception gets thrown at line 168 of lib/client.js with message: _.get(...) is not a function. After digging around a bit, I found that the code in question looks like so:

return _.get(this, req.options.next)({ NextToken: nextToken }, nextMeta)
.then(function (nextData) {
    return {
         result: _.concat(result, nextData.result),
         metadata: _.concat(metadata, nextData.metadata)
    };
});

I found that the this object doesn't have a property matching the value of req.options.next (which evaluates to be ListOrdersByNextToken), hence the error. ListOrdersByNextToken exists on this.Orders instead.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.