Amazon SP API 提供的“marketplaceIds”无效

问题描述 投票:0回答:1

我正在使用 Electron 并尝试使用 Amazon SP SPI。不知何故,尽管我的

marketplaceIds
是正确的,但我总是收到以下错误。

// apiCall.js
const SellingPartner = require("amazon-sp-api");
require('dotenv').config({ path: './api.env' });

function apiCall(eanNumbers) {
    (async () => {
        try {
            const spClient = new SellingPartner({
                region: "eu",
                refresh_token: process.env.REFRESH_TOKEN,
                credentials: {
                    SELLING_PARTNER_APP_CLIENT_ID: process.env.CLIENT_ID,
                    SELLING_PARTNER_APP_CLIENT_SECRET: process.env.SECRET_KEY,
                },
            });
            let res = await spClient.callAPI({
                operation: "searchCatalogItems",
                endpoint: "catalogItems",
                marketplaceIds: ["A1PA6795UKMFR9"],
                identifiers: eanNumbers,
                identifiersType: "EAN",
            });
            console.log(res);
        } catch (e) {
            console.log(e);
        }
    })();
}

module.exports = apiCall;

我在

marketplaceIds
字段中尝试了不同的数字(所有这些都在亚马逊文档中)和其他格式,例如 JSON 数组、字符串和带有字符串的 JavaScript 数组。

javascript node.js electron amazon-selling-partner-api
1个回答
0
投票

确保您使用正确的市场 ID,这是我正确的工作代码

require("dotenv").config();
const SellingPartnerAPI = require("amazon-sp-api");
const fs = require("fs");
const path = require("path");
var bunyan = require("bunyan");
var log = bunyan.createLogger({ name: "node" });

/*
 * Configure logging error or bunyan logger
 */
const logFilePath = path.join(__dirname, "error.log");
const logger = new console.Console({
  stdout: fs.createWriteStream(logFilePath, { flags: "a" }),
  stderr: fs.createWriteStream(logFilePath, { flags: "a" }),
});

/*
 * AmazonOrders Class which used for fetching filtering order data
 */
class AmazonOrders {
  /*
   * Created constructor for credentials and condition for verifying
   */
  constructor() {
    this.credentials = {
      clientId: process.env.LWA_APP_ID,
      clientSecret: process.env.CLIENT_SECRET,
      refreshToken: process.env.REFRESH_TOKEN,
      aws_access_key_id: process.env.AWS_ACCESS_KEY,
      aws_secret_access_key: process.env.AWS_SECRET_KEY,
      role: process.env.ROLE_ARN,
    };
    this.verifyCredentials();
    this.sellingPartner = new SellingPartnerAPI({
      region: "eu",
      refresh_token: this.credentials.refreshToken,
      credentials: {
        SELLING_PARTNER_APP_CLIENT_ID: this.credentials.clientId,
        SELLING_PARTNER_APP_CLIENT_SECRET: this.credentials.clientSecret,
        AWS_ACCESS_KEY_ID: this.credentials.aws_access_key_id,
        AWS_SECRET_ACCESS_KEY: this.credentials.aws_secret_access_key,
        AWS_SELLING_PARTNER_ROLE: this.credentials.role,
      },
    });
  }

  verifyCredentials() {
    const missingCredentials = Object.keys(this.credentials).filter(
      (key) => !this.credentials[key]
    );
    if (missingCredentials.length) {
      logger.error(`Missing credentials: ${missingCredentials.join(", ")}`);
      throw new Error(`Missing credentials: ${missingCredentials.join(", ")}`);
    }
  }

  /*
   * getOrder method used sp api functions for getting orders details
   */
  async getOrder(
    marketplaceIds,
    lastUpdatedAfter,
    orderStatuses = ["PartiallyShipped", "Unshipped"],
    maxResultsPerPage = 100
  ) {
    try {
      logger.log(
        `Fetching orders from Amazon API for marketplace: ${marketplaceIds}...`
      );
      let params = {
        MarketplaceIds: marketplaceIds,
        LastUpdatedAfter: lastUpdatedAfter,
        // OrderStatuses: orderStatuses,
        MaxResultsPerPage: maxResultsPerPage,
      };

      let allOrders = [];
      let nextToken = null;

      do {
        /*
         * Used nextToken for pagination
         */
        if (nextToken) {
          params.NextToken = nextToken;
        }
        /*
         * Use node js npm sp api methods
         */
        const response = await this.sellingPartner.callAPI({
          operation: "getOrders",
          endpoint: "orders",
          query: params,
        });

        const orders = response.Orders;

        // console.log(response);

        allOrders = allOrders.concat(orders);
        nextToken = response.NextToken;
        /*
         * Printing out orders data into pretty format with stringify
         */
        const ordersJson = JSON.stringify(allOrders, null, 4);
        console.log(`Order Data : ${ordersJson}`);
        logger.log(`Order Data : ${ordersJson}`);

        /*
         * If condition true ordersImport method will start
         */

        // console.log(`Count of orders: ${orders.length}`);
        if (orders.length > 0) {
          await this.ordersImport(orders);
        }
      } while (nextToken);
    } catch (error) {
      logger.error(
        `Exception occurred for marketplace ${marketplaceIds}: ${error.message}`
      );
    }
  }

(async () => {
  /*
   * Creating instance of class AmazonOrders()->fetcher
   */
  const fetcher = new AmazonOrders();
  /*
   * Adding Germany and France marketplaces for fetching orders
   */
  const marketplaceIds = ["A1F83G8C2ARO7P", "A1PA6795UKMFR9"];
  /*
   * Logic for fetching data from now to 3 days
   */
  const lastUpdatedAfter = new Date(
    new Date().setDate(new Date().getDate() - 3)
  ).toISOString();

  /*
   * Calling instances of amazonorder class method getOrder and adding two parameters
   */
  await fetcher.getOrder(marketplaceIds, lastUpdatedAfter);
  /*
   * Commented code for multiple function to run which is independent
   */
  // await Promise.all([fetcher.getOrder(marketplaceIds, lastUpdatedAfter)]);
})();
© www.soinside.com 2019 - 2024. All rights reserved.