thewirecutter/paapi5-php-sdk 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

thewirecutter/paapi5-php-sdk

Composer 安装命令:

composer require thewirecutter/paapi5-php-sdk

包简介

Amazon Creators API PHP SDK

README 文档

README

Version Total Downloads CircleCI

This repository contains the open source PHP SDK that allows you to access the Amazon Creators API from your PHP app.

Note: This package was previously the PAAPI5 PHP SDK. As of v2.0.0 it has been migrated to wrap Amazon's Creators API PHP SDK. Existing consumers should update their namespace references from Amazon\ProductAdvertisingAPI\v1\ to Amazon\CreatorsAPI\v1\ and switch from AWS Signature V4 credentials to OAuth 2.0 credentials (Client ID, Client Secret, Version).

Copy of Amazon's Provided Code

This is a near-identical public copy of Amazon's provided Creators API PHP SDK, as their version is not available through Packagist. The Composer package name remains thewirecutter/paapi5-php-sdk for backwards compatibility with existing consumers.

We have not changed the API behavior in any way. A listing of our additions and changes are provided below, which primarily enforce a code-sniff standard and support running an continuous integration pipeline.

Changes from Amazon

  • Added squizlabs/php_codesniffer dev dependency and PSR-2 CI linting.
  • Updated CircleCI configuration for automated builds.
  • Upgraded friendsofphp/php-cs-fixer to ^3.5 with updated .php_cs config.
  • Added integration tests that run the example scripts and verify they execute without any errors.
  • Added typehints to method signatures where possible (without breaking backwards compatibility).
  • Exposed the DefaultApi's buildAuthenticatedHeaders() method as protected so it can be overridden for caching tokens (see below for example).

Installation

The Creators API PHP SDK can be installed with Composer. The SDK is available via Packagist under the thewirecutter/paapi5-php-sdk package.

composer require thewirecutter/paapi5-php-sdk

Requirements

  • PHP 8.1 or greater
  • Guzzle 7.3+
  • Amazon Creators API credentials: Client ID, Client Secret, and Version

Authentication

This SDK uses OAuth 2.0 (not AWS Signature V4). You will need:

  • Credential ID (Client ID) — from the Amazon Associates program
  • Credential Secret (Client Secret)
  • Version — the credential version string
  • Marketplace — e.g. www.amazon.com
  • Partner Tag — your Amazon Associates tracking ID

The SDK handles token caching automatically via OAuth2TokenManager. This caching only persists as long as the same instance of DefaultApi is used.

Usage

Simple example for GetItems to retrieve product details for specific ASINs:

<?php

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

use Amazon\CreatorsAPI\v1\Configuration;
use Amazon\CreatorsAPI\v1\com\amazon\creators\api\DefaultApi;
use Amazon\CreatorsAPI\v1\com\amazon\creators\model\GetItemsRequestContent;
use Amazon\CreatorsAPI\v1\com\amazon\creators\model\GetItemsResource;
use Amazon\CreatorsAPI\v1\ApiException;

$config = new Configuration();
$config->setCredentialId('<YOUR CREDENTIAL ID>');
$config->setCredentialSecret('<YOUR CREDENTIAL SECRET>');
$config->setVersion('<YOUR CREDENTIAL VERSION>');

$api = new DefaultApi(null, $config);

$marketplace = 'www.amazon.com';

$resources = [
    GetItemsResource::IMAGES_PRIMARY_MEDIUM,
    GetItemsResource::ITEM_INFO_TITLE,
    GetItemsResource::OFFERS_V2_LISTINGS_PRICE,
];

$request = new GetItemsRequestContent();
$request->setPartnerTag('<YOUR PARTNER TAG>');
$request->setItemIds(['B0DLFMFBJW', 'B0BFC7WQ6R']);
$request->setResources($resources);

try {
    $response = $api->getItems($marketplace, $request);
    echo 'API called successfully' . PHP_EOL;
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
} catch (ApiException $e) {
    echo 'Error calling Creators API!' . PHP_EOL;
    echo $e . PHP_EOL;
} catch (Exception $e) {
    echo 'Unexpected error: ' . $e . PHP_EOL;
}

See the examples/ directory for additional sample scripts covering all supported operations:

  • SampleGetItems.php
  • SampleSearchItems.php
  • SampleGetVariations.php
  • SampleGetBrowseNodes.php
  • SampleGetFeed.php
  • SampleGetReport.php
  • SampleListFeeds.php
  • SampleListReports.php

Complete API documentation is available at https://affiliate-program.amazon.com/creatorsapi.

Caching Tokens

The DefaultApi class caches OAuth2 tokens in memory for the duration of the instance. To implement a more persistent caching mechanism (e.g. file-based, Redis, etc.), you can extend DefaultApi and override the buildAuthenticatedHeaders() method to first check your cache before making a request to Amazon's token endpoint.

Example code snippet for improved caching:

class CachedApi extends DefaultApi
{
    public function __construct(
        private readonly CachingTokenManager $cachingTokenManager, // Inject a caching token manager that extends OAuth2TokenManager.
        ?ClientInterface                     $client = null,
        ?Configuration                       $config = null,
        ?HeaderSelector                      $selector = null,
        int                                  $hostIndex = 0
    ) {
        parent::__construct($client, $config, $selector, $hostIndex);
    }

    protected function buildAuthenticatedHeaders(string $resourcePath): array
    {
        $token   = $this->cachingTokenManager->getToken(); // This will use the cached token if available, or fetch a new one if not.
        $version = $this->config->getVersion();

        if (str_starts_with($version, '3.')) {
            return ['Authorization' => "Bearer {$token}"];
        }

        return ['Authorization' => "Bearer {$token}, Version {$version}"];
    }

    public function clearToken(): void
    {
        $this->cachingTokenManager->clearToken();
    }
}

class CachingTokenManager extends OAuth2TokenManager
{
    // $cache is any PSR-16 CacheInterface implementation (files, Redis, Memcached, etc.)

    private const string CACHE_KEY = 'amazon_unique_token_cache_key'; // Use a unique cache key to avoid collisions with other cached data.
    private const int CACHE_TTL_SECONDS = 3300; // 55 minutes — 5 minutes less than Amazon's 60 minute token expiry

    public function __construct(
        private readonly \Psr\SimpleCache\CacheInterface $cache,
        OAuth2Config $config
    ) {
        parent::__construct($config);
    }

    public function getToken(): string
    {
        $cached = $this->cache->get(self::CACHE_KEY);

        if ($cached !== null) {
            return $cached;
        }

        $token = parent::getToken();
        $this->cache->set(self::CACHE_KEY, $token, self::CACHE_TTL_SECONDS);

        return $token;
    }

    public function clearToken(): void
    {
        $this->cache->delete(self::CACHE_KEY);
    }
}

License

This SDK is distributed under the Apache License, Version 2.0, see LICENSE.txt and NOTICE.txt for more information.

thewirecutter/paapi5-php-sdk 适用场景与选型建议

thewirecutter/paapi5-php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.82M 次下载、GitHub Stars 达 68, 最近一次更新时间为 2019 年 10 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「amazon」 「paapi5」 「paapi」 「pa-api」 「paapi5.0」 「paapi5-php-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 thewirecutter/paapi5-php-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 thewirecutter/paapi5-php-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 thewirecutter/paapi5-php-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.82M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 69
  • 点击次数: 31
  • 依赖项目数: 5
  • 推荐数: 0

GitHub 信息

  • Stars: 68
  • Watchers: 11
  • Forks: 32
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2019-10-17