pjcdawkins/guzzle-oauth2-plugin

为 Guzzle(源自 commerceguys/guzzle-oauth2-plugin)提供的 OAuth2 插件(订阅者)

v2.4.1 2024-05-23 15:23 UTC

README

提供 OAuth2 插件(订阅者)供 Guzzle 使用。

Build Status Code Coverage

2.x 版本(位于 master 分支)是为 Guzzle 5 设计的

        "commerceguys/guzzle-oauth2-plugin": "~2.0"

Guzzle 3 的兼容性在 1.0 分支中继续

        "commerceguys/guzzle-oauth2-plugin": "~1.0"

特性

  • 通过支持的授权类型之一(代码、客户端凭证、用户凭证、刷新令牌)获取访问令牌。或者您可以自己设置访问令牌。
  • 支持刷新令牌(存储并使用它们来获取新的访问令牌)。
  • 处理令牌过期(获取新的令牌并重试失败的请求)。

运行测试

首先确保已通过运行 composer install --prefer-dist 安装了所有依赖项,然后只需运行 ./bin/phpunit

示例

use GuzzleHttp\Client;
use CommerceGuys\Guzzle\Oauth2\GrantType\RefreshToken;
use CommerceGuys\Guzzle\Oauth2\GrantType\PasswordCredentials;
use CommerceGuys\Guzzle\Oauth2\Oauth2Subscriber;

$base_url = 'https://example.com';

$oauth2Client = new Client(['base_url' => $base_url]);

$config = [
    'username' => 'test@example.com',
    'password' => 'test password',
    'client_id' => 'test-client',
    'scope' => 'administration',
];

$token = new PasswordCredentials($oauth2Client, $config);
$refreshToken = new RefreshToken($oauth2Client, $config);

$oauth2 = new Oauth2Subscriber($token, $refreshToken);

$client = new Client([
    'defaults' => [
        'auth' => 'oauth2',
        'subscribers' => [$oauth2],
    ],
]);

$response = $client->get('https://example.com/api/user/me');

print_r($response->json());

// Use $oauth2->getAccessToken(); and $oauth2->getRefreshToken() to get tokens
// that can be persisted for subsequent requests.