该软件包的最新版本(v1.1.4)没有可用的许可证信息。

Amazon Selling Partner API 客户端

v1.1.4 2022-07-22 10:21 UTC

README

spapi-php 是 Amazon Selling Partner API 的 http 客户端

作者:Lyubomir Slavilov

开始之前

Spapi 以 Composer 包的形式发布为 double-break/spapi-php,无任何保证或承诺。

有几个类(如 SignerCredentials)对于 API 调用至关重要。大部分问题都会在这里出现。

所有实际的 API 客户端都是自动生成的,并且根据上述免责声明,未经过充分测试。

要求

  • php 7.3(从未在更低版本上进行过测试)
  • composer
  • 花大量时间阅读 Amazon SP API 文档

安装和更新

现在你已准备好进行

composer require double-break/spapi-php

软件包更新

成功安装软件包后,更新就像正常的 Composer 软件包更新一样简单。只需执行

composer update double-break/spapi-php

配置

示例

简单使用

<?php
  include __DIR__ . '/vendor/autoload.php';


  /** The Setup **/

  $config = [
    //Guzzle configuration
    'http' => [
      'verify' => false,    //<--- NOT SAFE FOR PRODUCTION
      'debug' => true       //<--- NOT SAFE FOR PRODUCTION
    ],

    //LWA: Keys needed to obtain access token from Login With Amazon Service
    'refresh_token' => '<YOUR-REFRESH-TOKEN>',
    'client_id' => '<CLINET-ID-IN-SELLER-CONSOLE>',
    'client_secret' => '<CLIENT_SECRET>',

    //STS: Keys of the IAM role which are needed to generate Secure Session
    // (a.k.a Secure token) for accessing and assuming the IAM role
    'access_key' => '<STS-ACCESS_KEY>',
    'secret_key' => '<STS-SECRET-KEY>',
    'role_arn' => '<ROLE-ARN>' ,

    //API: Actual configuration related to the SP API :)
    'region' => 'eu-west-1',
    'host' => 'sellingpartnerapi-eu.amazon.com'
  ];

  //Create token storage which will store the temporary tokens
  $tokenStorage = new DoubleBreak\Spapi\SimpleTokenStorage('./aws-tokens');

  //Create the request signer which will be automatically used to sign all of the
  //requests to the API
  $signer = new DoubleBreak\Spapi\Signer();

  //Create Credentials service and call getCredentials() to obtain
  //all the tokens needed under the hood

  $credentials = new DoubleBreak\Spapi\Credentials($tokenStorage, $signer, $config);
  $cred = $credentials->getCredentials();



  /** The application logic implementation **/


  //Create SP API Catalog client and execute one ot its REST methods.
  $catalogClient = new DoubleBreak\Spapi\Api\CatalogItems($cred, $config);

  //Check the catalog info for B074Z9QH5F ASIN
  $result = $catalogClient->getCatalogItem('B074Z9QH5F', [
      'marketplaceIds' => 'A1PA6795UKMFR9',
  ]);


  print_r($result);

Feed API 使用

对于 Feed API,用户可以参考Feeds API 使用案例指南

在此指南的第2步“加密和上传数据”:用户可以使用以下示例

<?php

// content type of the feed data to be uploaded.
$contentType = 'text/xml; charset=UTF-8';

// create feed document
$feedClient = new \DoubleBreak\Spapi\Api\Feeds($cred, $config);
$response = $feedClient->createFeedDocument(["contentType" => $contentType]);
$payload = $response['payload'];

$feedContentFilePath = './testFeedDoc.xml';

$result = (new \DoubleBreak\Spapi\Helper\Feeder())->uploadFeedDocument($payload,$contentType,$feedContentFilePath);
print_r($result);

在此指南的第6步“下载和解密数据处理报告”:用户可以使用以下示例

<?php
$feedClient = new \DoubleBreak\Spapi\Api\Feeds($cred, $config);

// $resultFeedDocumentId: from response of getFeed() function.
$resultFeedDocumentId = 'amzn1.tortuga.3.ed4cd0d8-447b-4c22-96b5-52da8ace1207.T3YUVYPGKE9BMY';
$response = $feedClient->getFeedDocument($resultFeedDocumentId);
$payload = $response['payload'];

$result = (new \DoubleBreak\Spapi\Helper\Feeder())->downloadFeedProcessingReport($payload);
print_r($result);

调试响应

<?php
  //configuration and initialization here

  $catalogClinet = new DoubleBreak\Spapi\Api\Catalog($cred, $config);
  try {
    $result = $catalogClinet->getCatalogItem('B074Z9QH5F', [
      'MarketplaceId' => 'A1PA6795UKMFR9',
    ])['payload'];
    //do your business here
  } catch (\GuzzleHttp\Exception\ClientException $e) {
    $httpCode = $e->getResponse()->getStatusCode();
    $errorBody =  $e->getResponse()->getBody();

    echo "Amazon SP API responded with HTTP {$httpCode}\n {$errorBody}";

  } catch(\Exception $e) {
    echo "Unexpected exception: " . $e->getMessage();
  }

访问响应头

📝从 v1.0.5 版本开始,通过客户端的 getLastHttpResponse() 访问头信息是可用的

<?php
  //configuration and initialization here

  //Create SP API Catalog client and execute one ot its REST methds.
  $catalogClinet = new DoubleBreak\Spapi\Api\Catalog($cred, $config);

  //Check the catalog info for B074Z9QH5F ASIN
  $result = $catalogClinet->getCatalogItem('B074Z9QH5F', [
    'MarketplaceId' => 'A1PA6795UKMFR9',
  ])['payload'];

  $headers = $catalogClinet->getLastHttpResponse()->getHeaders();
  foreach ($headers as $headerName => $values) {
    echo "{$headerName}: " . implode(','. $values);
  }

调试 4xx 和 5xx 响应头

📝从 v1.0.5 版本开始,通过客户端的 getLastHttpResponse() 访问头信息是可用的

<?php
  //configuration and initialization here

  $catalogClinet = new DoubleBreak\Spapi\Api\Catalog($cred, $config);
  try {
    $result = $catalogClinet->getCatalogItem('B074Z9QH5F', [
      'MarketplaceId' => 'A1PA6795UKMFR9',
    ])['payload'];
    //do your business here
  } catch (\GuzzleHttp\Exception\ClientException $e) {
    $headers = $e->getResponse()->getHeaders();
    print_r($headers);
  }

  // OR

  try {
    $result = $catalogClinet->getCatalogItem('B074Z9QH5F', [
      'MarketplaceId' => 'A1PA6795UKMFR9',
    ])['payload'];
    //do your business here

  } catch (\GuzzleHttp\Exception\ClientException $e) {
    $headers = $catalogClinet->getLastHttpResponse()->getHeaders();
    print_r($headers);
  }

从 Amazon Marketplace Web 服务迁移授权到 Selling Partner API

请参阅 Selling Partner API 文档中的更多详细信息

<?php
include __DIR__ . '/vendor/autoload.php';

  /** The Setup **/

$config = [
    //Guzzle configuration
    'http' => [
        'verify' => false,
        'debug' => true
    ],

    //LWA: Keys needed to obtain access token from Login With Amazon Service
    'refresh_token' => '<YOUR-REFRESH-TOKEN>',
    'client_id' => '<CLINET-ID-IN-SELLER-CONSOLE>',
    'client_secret' => '<CLIENT_SECRET>',

    //STS: Keys of the IAM role which are needed to generate Secure Session
    // (a.k.a Secure token) for accessing and assuming the IAM role
    'access_key' => '<STS-ACCESS_KEY>',
    'secret_key' => '<STS-SECRET-KEY>',
    'role_arn' => '<ROLE-ARN>' ,

    //API: Actual configuration related to the SP API :)
    'region' => 'eu-west-1',
    'host' => 'sellingpartnerapi-eu.amazon.com'
];

//Create token storage which will store the temporary tokens
$tokenStorage = new DoubleBreak\Spapi\SimpleTokenStorage('./aws-tokens');

//Create the request signer which will be automatically used to sign all of the
//requests to the API
$signer = new DoubleBreak\Spapi\Signer();

//Create Credentials service and call getCredentials() to obtain
//all the tokens needed under the hood
$credentials = new DoubleBreak\Spapi\Credentials($tokenStorage, $signer, $config);
//get credentials with migration token, it's needed for /authorization/v1/authorizationCode request
$cred = $credentials->getCredentials(true);

/** The application logic implementation **/

//Create SP API Catalog client and execute one ot its REST methods.
$authorizationClient = new DoubleBreak\Spapi\Api\Authorization($cred, $config);

//Get Authorization code
$result = $authorizationClient->getAuthorizationCode([
    'developerId' => '<DEVELOPER-ID-AUTHORIZED-BY-SELLING-PARTNER>',
    'mwsAuthToken' => '<MWS-AUTH-TOKEN>',
    'sellingPartnerId' => '<SELLING-PARTNER-ID>'
])['payload'];

//Authorization code should be changed to Access and Refresh token
print_r($credentials->exchangesAuthorizationCodeForRefreshToken($result['authorizationCode']));

Selling Partner API 中无授权操作的授权

请参阅 Selling Partner API 文档中的更多详细信息

<?php
include __DIR__ . '/vendor/autoload.php';

  /** The Setup **/

$config = [
    //Guzzle configuration
    'http' => [
        'verify' => false,
        'debug' => true
    ],

    //LWA: Keys needed to obtain access token from Login With Amazon Service
    'refresh_token' => '<YOUR-REFRESH-TOKEN>',
    'client_id' => '<CLINET-ID-IN-SELLER-CONSOLE>',
    'client_secret' => '<CLIENT_SECRET>',

    //STS: Keys of the IAM role which are needed to generate Secure Session
    // (a.k.a Secure token) for accessing and assuming the IAM role
    'access_key' => '<STS-ACCESS_KEY>',
    'secret_key' => '<STS-SECRET-KEY>',
    'role_arn' => '<ROLE-ARN>' ,

    //API: Actual configuration related to the SP API :)
    'region' => 'eu-west-1',
    'host' => 'sellingpartnerapi-eu.amazon.com'
];

//Create token storage which will store the temporary tokens
$tokenStorage = new DoubleBreak\Spapi\SimpleTokenStorage('./aws-tokens');

//Create the request signer which will be automatically used to sign all of the
//requests to the API
$signer = new DoubleBreak\Spapi\Signer();

//Create Credentials service and call getCredentials() to obtain
//all the tokens needed under the hood
$credentials = new DoubleBreak\Spapi\Credentials($tokenStorage, $signer, $config);
//get credentials with Grantless auth token, it's needed for grantless operations request
$cred = $credentials->getCredentials('grantless');

/** The application logic implementation **/

//Create SP API Notification client and execute one ot its REST methods.
$notificationClient = new DoubleBreak\Spapi\Api\Notifications($cred, $config);

//Get notification destinations
$result = $notificationClient->getDestinations();
print_r($result['payload']);

处理受限制的数据 API

<?php
  include __DIR__ . '/vendor/autoload.php';


  /** The Setup **/

  $config = [
    // same as examples above...
  ];

  //Create token storage which will store the temporary tokens
  $tokenStorage = new DoubleBreak\Spapi\SimpleTokenStorage('./aws-tokens');

  //Create the request signer which will be automatically used to sign all of the
  //requests to the API
  $signer = new DoubleBreak\Spapi\Signer();

  //Create Credentials service and call getCredentials() to obtain
  //all the tokens needed under the hood

  $credentials = new DoubleBreak\Spapi\Credentials($tokenStorage, $signer, $config);
  $cred = $credentials->getRdtCredentials([
    'restrictedResources' => [
      [
        'method' => 'GET',
        'path' => '/orders/v0/orders/{orderId}/buyerInfo'
      ],
      [
        'method' => 'GET',
        'path' => '/mfn/v0/shipments/{shipmentId}'
      ]
    ]
  ]);



  /** The application logic implementation **/


  //Create SP API Orders client and execute one ot its REST methods.
  $orderClient = new DoubleBreak\Spapi\Api\Orders($cred, $config);

  //Get order's buyer info
  $result = $catalogClient->getOrderBuyerInfo('902-3159896-1390916')['payload'];
  print_r($result);

  //...

有关此主题的更多信息,请参阅 Amazon 关于此主题的使用案例文档:https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/tokens-api-use-case-guide/tokens-API-use-case-guide-2021-03-01.md