bindcommerce/sp-api-sdk-bindcommerce

Amazon Selling Partner API - PHP SDK

v5.0.21 2024-05-29 17:23 UTC

This package is not auto-updated.

Last update: 2024-09-23 11:58:48 UTC


README

2024年5月29日 RINOMINATO 分支升级到 master 5.0

Amazon Selling Partner API - PHP SDK

此存储库不是亚马逊官方PHP库,用于其SP API。

social-preview

为什么选择这个库?

此SDK的主要目标是提供Amazon SP API的SDK,以便应用可以通过亚马逊审计。

亚马逊审计可能会发生在必须使用PII访问API端点的情况下。

已经有几个PHP SP API SDK可用,但是大多数都存在许多自动生成代码的问题。

  • 硬编码的依赖,如guzzlehttp/guzzleaws/aws-sdk-php
  • 遗留代码库(7.2)
  • 没有记录器
  • SDK围绕单个卖家设计,不适合大型系统
  • 缺少或缺乏对client_credentials授权类型的支持
  • 未涵盖所有API
  • 没有扩展

此库的目标是解决上述所有问题。

安装

composer require amazon-php/sp-api-sdk

此库尚未处于稳定状态,请谨慎使用。

版本

由于尝试使用“标签”来更清楚地了解亚马逊在其Open API规范中做了什么,该版本已弃用。此尝试失败,为了保持向后兼容性的承诺,必须在2.x中引入类名的更改。1.0版本将不再更新,请迁移到2.0版本,该版本将与Amazon Models3.x分支保持一致。分支3.x引入了亚马逊在目录项目模型中引入的BC中断。直到旧模型不会消失,2.x和3.x分支应并行维护。

4.x在以下亚马逊API模型中引入了BC中断

  • 列表
  • 报告
  • 供应商
    • 直接配送运输
    • 直接配送订单
    • 直接配送交易

5.x迁移到2022-04-01版本的目录项目API,该版本将替换2020-12-01版本。此外,用于生成关联标识符的uuid被替换为IdGenerator接口,该接口默认使用php内部uniqid()。此更改使我们能够删除一个额外的依赖项。在models/api的模板文件中进行了少量调整。

可用的SDK

SellingPartnerSDK - 所有SDK的外观

授权

要开始使用SP API,您首先需要注册为开发者并创建应用程序。整个过程在亚马逊官方指南中有详细描述。

亚马逊建议在创建应用程序时使用角色IAM,但这需要额外的API请求来获取访问令牌。使用用户IAM更容易,只需确保用户具有以下内联策略即可

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:*:*:*"
        }
    ]
}

IAM用户

将刷新令牌更改为访问令牌的示例。

<?php

use AmazonPHP\SellingPartner\OAuth;
use AmazonPHP\SellingPartner\Configuration;
use AmazonPHP\SellingPartner\HttpFactory;
use Buzz\Client\Curl;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Log\NullLogger;

$factory = new Psr17Factory();
$client = new Curl($factory);

$oauth = new OAuth(
    $client,
    $httpFactory = new HttpFactory($factory, $factory),
    $config = Configuration::forIAMUser(
        'lwaClientId',
        'lwaClientIdSecret',
        'awsAccessKey',
        'awsSecretKey'
    ),
    new NullLogger()
);

$accessToken = $oauth->exchangeRefreshToken('seller_oauth_refresh_token');

IAM角色

<?php

use AmazonPHP\SellingPartner\OAuth;
use AmazonPHP\SellingPartner\Configuration;
use AmazonPHP\SellingPartner\HttpFactory;
use AmazonPHP\SellingPartner\STSClient;
use Buzz\Client\Curl;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Log\NullLogger;

$factory = new Psr17Factory();
$client = new Curl($factory);

$sts = new STSClient(
    $client,
    $requestFactory = $factory,
    $streamFactory = $factory
);

$oauth = new OAuth(
    $client,
    $httpFactory = new HttpFactory($requestFactory, $streamFactory),
    $config = Configuration::forIAMRole(
        'lwaClientID',
        'lwaClientIdSecret',
        $sts->assumeRole(
            'awsAccessKey',
            'awsSecretKey',
            'arn:aws:iam::.........'
        )
    ),
    new NullLogger()
);

$accessToken = $oauth->exchangeRefreshToken('seller_oauth_refresh_token');

开发

此库中的99%的代码都是使用亚马逊卖家API模型OpenAPI Generator工具自动生成的。输出随后通过RectorPHP自动升级到PHP 7.4版本,最后通过PHP CS Fixer自动统一编码标准。

要求

为了重新生成代码(例如,当API定义更改时),执行以下代码

composer generate

示例

<?php

use AmazonPHP\SellingPartner\Marketplace;
use AmazonPHP\SellingPartner\Regions;
use AmazonPHP\SellingPartner\SellingPartnerSDK;
use Buzz\Client\Curl;
use AmazonPHP\SellingPartner\Exception\ApiException;
use AmazonPHP\SellingPartner\Configuration;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Nyholm\Psr7\Factory\Psr17Factory;

require_once __DIR__ . '/vendor/autoload.php';

$factory = new Psr17Factory();
$client = new Curl($factory);

$configuration = Configuration::forIAMUser(
    'lwaClientId',
    'lwaClientIdSecret',
    'awsAccessKey',
    'awsSecretKey'
);

$logger = new Logger('name');
$logger->pushHandler(new StreamHandler(__DIR__ . '/sp-api-php.log', Logger::DEBUG));

$sdk = SellingPartnerSDK::create($client, $factory, $factory, $configuration, $logger);

$accessToken = $sdk->oAuth()->exchangeRefreshToken('seller_oauth_refresh_token');

try {
    $item = $sdk->catalogItem()->getCatalogItem(
        $accessToken,
        Regions::NORTH_AMERICA,
        $asin = 'B07W13KJZC',
        $marketplaceId = [Marketplace::US()->id()]
    );
    dump($item);
} catch (ApiException $exception) {
    dump($exception->getMessage());
}

日志记录

默认日志级别设置为DEBUG,但可以在配置中将其更改为任何其他级别,以用于所有API的所有操作,或者仅用于给定API的给定操作。

$configuration->setDefaultLogLevel(\Psr\Log\LogLevel::INFO);

也可以排除特定的API或特定操作进行日志记录(例如,包含PII或敏感数据的API)。

$configuration->setLogLevel(CatalogItemSDK::API_NAME, CatalogItemSDK::OPERATION_GETCATALOGITEM, LogLevel::INFO);
$configuration->setSkipLogging(TokensSDK::API_NAME);
$configuration->setSkipLogging(AuthorizationSDK::API_NAME, AuthorizationSDK::OPERATION_GETAUTHORIZATIONCODE);

最后,您还可以在记录http请求/响应时忽略特定的头信息。默认情况下,配置设置为忽略以下敏感授权头信息

'authorization',
'x-amz-access-token',
'x-amz-security-token',
'proxy-authorization',
'www-authenticate',
'proxy-authenticate',

您也可以添加您自己的忽略头信息

$configuration->loggingAddSkippedHeader('some-sensitive-key');

扩展

每个SDK都允许您注册在发送API请求之前和之后执行的自定义扩展。

<?php

$configuration->registerExtension(new class implements \AmazonPHP\SellingPartner\Extension {
    public function preRequest(string $api, string $operation, RequestInterface $request): void
    {
        echo "pre: " . $api . "::" . $operation . " " . $request->getUri() . "\n";
    }

    public function postRequest(string $api, string $operation, RequestInterface $request, ResponseInterface $response): void
    {
        echo "post: " . $api . "::" . $operation . " " . $request->getUri() . " "
            . $response->getStatusCode() . " rate limit: " . implode(' ', $response->getHeader('x-amzn-RateLimit-Limit')) . "\n";
    }
});

沙箱

可以使用配置开启沙箱模式

$configuration->setSandbox();

一些API端点在功能测试中进行了覆盖。要运行使用沙箱模式的测试,您需要创建.env文件并填写您的凭证

cp .env.dist .env

然后您可以通过运行composer test:functional来进入并执行沙箱测试套件。