带固定功能的Amazon Selling Partner API客户端

v1.0.5 2021-03-19 09:10 UTC

This package is auto-updated.

Last update: 2024-09-19 16:42:06 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', [
    'MarketplaceId' => 'A1PA6795UKMFR9',
  ])['payload'];


  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 \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步中下载和解密feed处理报告:用户可以使用以下示例

<?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']);