webaune/spapi-php

此包的最新版本(V1.0)没有提供许可证信息。

Amazon Selling Partner API 客户端

V1.0 2024-03-05 05:10 UTC

This package is auto-updated.

Last update: 2024-09-05 06:12:23 UTC


README

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

作者:Razeek Subair | 从 double-break/spapi-php 分支而来

开始之前

Spapi 以 Composer 包 webaune/spapi-php 的形式发布,不提供任何保证或承诺

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

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

要求

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

安装和更新

现在你已经准备好进行

composer require webaune/spapi-php

包更新

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

composer update webaune/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 Webaune\Spapi\SimpleTokenStorage('./aws-tokens');

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

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

  $credentials = new Webaune\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 Webaune\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 步中,加密并上传数据 feed:用户可以使用以下示例

<?php

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

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

$feedContentFilePath = './testFeedDoc.xml';

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

在此指南的第 6 步中,下载并解密数据 feed 处理报告:用户可以使用以下示例

<?php
$feedClient = new \Webaune\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 \Webaune\Spapi\Helper\Feeder())->downloadFeedProcessingReport($payload);
print_r($result);

调试响应

<?php
  //configuration and initialization here

  $catalogClinet = new Webaune\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 Webaune\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 Webaune\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 Webaune\Spapi\SimpleTokenStorage('./aws-tokens');

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

//Create Credentials service and call getCredentials() to obtain
//all the tokens needed under the hood
$credentials = new Webaune\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 Webaune\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 Webaune\Spapi\SimpleTokenStorage('./aws-tokens');

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

//Create Credentials service and call getCredentials() to obtain
//all the tokens needed under the hood
$credentials = new Webaune\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 Webaune\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 Webaune\Spapi\SimpleTokenStorage('./aws-tokens');

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

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

  $credentials = new Webaune\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 Webaune\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