imarasoft-ltd/amazon-sp-api-sdk

Amazon Selling Partner API - PHP SDK


README

此存储库不是官方的Amazon PHP库,用于他们的SP API。

social-preview

为什么需要下一个库?

此SDK的主要目标是提供一种方式,使应用程序能够通过Amazon审计。

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

已经有一些PHP sp api SDK可用于PHP,但是其中大多数都带有许多自动生成代码的问题。

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

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

安装

composer require amazon-php/sp-api-sdk

此库尚未处于稳定阶段,请谨慎使用。

版本

由于尝试通过在Open API规范中使用“标签”使Amazon的行为更有意义,因此该版本已过时。这次尝试失败了,为了保持向后兼容性承诺,必须在2.x中引入类名更改。1.0版本将不再更新,请迁移到版本2.0,该版本将与Amazon Models分支3.x保持一致。直到旧模型不会消失,分支2.x和3.x应并行维护。

4.x在以下Amazon api模型中引入了BC breaks

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

5.x迁移到目录项API版本2022-04-01,该版本正在替换版本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来进入并执行沙盒测试套件。