UPS REST API 的 PHP SDK

1.0.1 2024-08-01 09:29 UTC

This package is auto-updated.

Last update: 2024-09-01 09:38:31 UTC


README

由 BeSmartAnd.Pro 提供的 UPS REST API 的 PHP SDK,基于 ShipStream 分支。

安装

composer require besmartand-pro/ups-api

基本用法

使用配置对象创建 UPS 客户端实例

$config = new \BesmartandPro\UpsApi\Config([
    // Whether to send the requests to the UPS Customer Integration Environment instead of the production environment.
    // Optional, defaults to false.
    'use_testing_environment' => true,
    // Your Client ID obtained from UPS Developer portal.
    'client_id' => 'your_client_id',
    // Your Client Secret obtained from UPS Developer portal.
    'client_secret' => 'your_client_secret',
    // The URL to redirect to after authenticating with UPS using Authorization Code flow.
    // Required only when using Authorization Code flow, defaults to an empty string.
    'redirect_uri' => 'https://example.com/oauth/callback',
    // Merchant identifier sent with OAuth authentication requests.
    // Optional, defaults to null.
    'merchant_id' => 'your_unique_merchant_id'
]);

$client = \BesmartandPro\UpsApi\ClientFactory::create($config);

客户端对象包含 UPS OpenAPI 定义文件中每个端点的方法,这些方法具有 PHPDoc 注释,描述参数和返回类型,以及抛出的任何异常。每个端点的方法名称基于 OpenAPI 规范的 operationId 属性。

以下是一个使用跟踪 API 的示例

try {
    $response = $client->getSingleTrackResponseUsingGET('1ZXXXXXXXXXXXXXXXX', $queryParams = [], $headers = [
        'transId' => 'Track-1ZXXXXXXXXXXXXXXXX-'.time(),
        'transactionSrc' => 'testing'
    ]);
    // Do something with the response
} catch (
    \BesmartandPro\UpsApi\Generated\Exception\GetSingleTrackResponseUsingGETNotFoundException |
    \BesmartandPro\UpsApi\Exception\GetSingleTrackResponseUsingGETBadRequestException |
    \BesmartandPro\UpsApi\Exception\GetSingleTrackResponseUsingGETInternalServerErrorException |
    \BesmartandPro\UpsApi\Exception\GetSingleTrackResponseUsingGETServiceUnavailableException $e
) {
    $errors = $e->getErrorResponse()->getResponse()->getErrors();
    $errors = array_map(fn ($error) => $error->getMessage(), $errors);
    echo 'Error: '.implode(' - ', $errors)."\n";
} catch (\BesmartandPro\UpsApi\Exception\UnexpectedStatusCodeException $e) {
    echo "Unexpected response received from UPS: {$e->getMessage()}\n";
} catch (\BesmartandPro\UpsApi\Exception\AuthenticationException $e) {
    echo "Authentication error: {$e->getMessage()}\n";
}

身份验证

客户端凭证

使用客户端凭证流程直接可用,无需额外步骤,因为访问令牌的生成和刷新由内部处理。

授权代码

待办事项

缓存访问令牌

默认情况下,库使用内存缓存访问令牌,这对于快速测试很有用,但为了生产环境,您可能希望使用 Redis 或文件系统缓存等,以避免在每次请求时都生成访问令牌。为此,客户端工厂接受第二个参数,该参数可以是实现 AccessTokenCache 接口的对象。例如,Redis 实现可能如下所示

class RedisAccessTokenCache implements \BesmartandPro\UpsApi\Authentication\AccessTokenCacheInterface
{
    private $predis;

    public function __construct(\Predis\Client $predis)
    {
        $this->predis = $predis;
    }
    public function save(\BesmartandPro\UpsApi\Authentication\AccessToken $accessToken)
    {
        $clientId = $accessToken->getClientId();
        $accessTokenKey = "access_token:$clientId";
        $this->predis->set($accessTokenKey, serialize($accessToken));
    }
    public function retrieve(string $clientId): ?\BesmartandPro\UpsApi\Authentication\AccessToken
    {
        $accessTokenKey = "access_token:$clientId";
        $cachedAccessToken = $this->predis->get($accessTokenKey);
        if ($cachedAccessToken !== false) {
            return unserialize($cachedAccessToken, ['allowed_classes' => [\BesmartandPro\UpsApi\Authentication\AccessToken::class]]);
        }
        return null;
    }
}
$client = \BesmartandPro\UpsApi\ClientFactory::create($config, new RedisAccessTokenCache(new \Predis\Client()));

使用自定义 HTTP 客户端

如果您希望自定义如何进行 HTTP 请求,例如进行记录或添加额外的头,则客户端工厂支持第三个参数,该参数可以是实现 PSR-18 标准的任何 HTTP 客户端。例如

$client = \BesmartandPro\UpsApi\ClientFactory::create($config, null, new \GuzzleHttp\Client());

请注意,HTTP 客户端 不允许 对于 4xx 和 5xx 响应抛出异常,因为这些应由 SDK 处理。

开发

位于 BesmartandPro\UpsApi 命名空间下的类都是使用 janephp 生成的。

运行 generate.sh 脚本来在需要时重新生成类。