承接 shipstream/ups-rest-php-sdk 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

shipstream/ups-rest-php-sdk

Composer 安装命令:

composer require shipstream/ups-rest-php-sdk

包简介

PHP SDK for UPS REST API

README 文档

README

A PHP SDK for the UPS REST API, brought to you by ShipStream.

Installation

composer require shipstream/ups-rest-php-sdk

Note: The latest version supports PHP 8.2 or above. For PHP 7.4 support, please append the ^1.0 version constraint to the above command.

Basic Usage

Create a UPS Client instance using a configuration object:

$config = new \ShipStream\Ups\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,
    // The grant type to use for obtaining an access token. Available options: 'client_credentials', 'authorization_code'.
    // Optional, defaults to 'client_credentials'.
    'grant_type' => \ShipStream\Ups\Config::GRANT_TYPE_CLIENT_CREDENTIALS,
    // 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',
]);

$client = \ShipStream\Ups\ClientFactory::create($config);

The Client object contains methods for every endpoint available in the UPS OpenAPI definition files with PHPDoc comments that describe the parameters and return types, as well as any thrown exceptions. Method names for each endpoint is based on the operationId property of the OpenAPI specification.

Here's an example using the Tracking API:

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

Authentication

Client Credentials

Using Client Credentials flow works out of the box and requires no additional steps as the access token generation and refresh is handled internally.

Authorization Code

To start using the Authorization Code flow set grant_type config to Config::GRANT_TYPE_AUTHORIZATION_CODE, then call the authorizeClient endpoint and redirect the user to the returned login URL:

$response = $client->authorizeClient([
    'client_id' => $client->getConfig()->getClientId(),
    'redirect_uri' => $client->getConfig()->getRedirectUri(),
    'response_type' => 'code'
]);

// Redirect the user to the login page
header('Location: ' . $response->getLocation());

The user will be redirected back to your app after login with the authorization code that will be used to generate an access token:

$client->exchangeAuthorizationCode($_GET['code']);

The access token refresh will be handled internally so long that the refresh token is still valid. You can check if the client is authenticated at any time by calling $client->getAccessToken() which attempts to retrieve the access token from the cache and refresh it if it has already expired, otherwise it throws an AuthenticationException.

Preventing race conditions when refreshing expired tokens

When multiple PHP processes attempt to call an endpoint while the access token is expired, a race condition may occur resulting in one process refreshing the token successfully, while the other processes will fail with Invalid Refresh Token or a similar error. To help prevent this, locking can be enabled by passing a third argument to Client factory that can be any class implementing the AccessTokenLock interface. A built-in implementation called FileAccessTokenLock is provided for convenience, it takes a writable file path and uses it for locking. Example:

$client = \ShipStream\Ups\ClientFactory::create(
    $config,
    null,
    new \ShipStream\Ups\Authentication\FileAccessTokenLock('/tmp/ups-sdk-token.lock')
);

Caching Access Tokens

The library uses an in-memory cache for access tokens by default which is useful when doing quick tests, but for a production environment you'd want to use something like Redis or a filesystem cache to avoid doing round trips to generate an access token on every request. To achieve this, the Client factory accepts a second parameter which can be any object that implements the AccessTokenCache interface. For example, a Redis implementation could look like this:

class RedisAccessTokenCache implements \ShipStream\Ups\Authentication\AccessTokenCache
{
    private $predis;

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

Using a custom HTTP Client

If you wish to customize how HTTP requests are made, perhaps for logging or to add additional headers, the Client factory supports a third parameter that can be any HTTP Client that implements the PSR-18 standard. E.g.:

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

Note that the HTTP Client must not throw exceptions for 4xx and 5xx responses, as those should be handled by the SDK.

Development

The classes under the ShipStream\Ups\Api namespace are all generated using janephp.

ARM/Docker Setups:
Run the generate.sh script to regenerate the classes when needed.

AMD64 (WSL/Linux) Setups:
Run the generate-amd64.sh script to regenerate the classes when needed.

shipstream/ups-rest-php-sdk 适用场景与选型建议

shipstream/ups-rest-php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 63.42k 次下载、GitHub Stars 达 21, 最近一次更新时间为 2023 年 10 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 63.42k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 21
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 21
  • Watchers: 4
  • Forks: 11
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2023-10-26