yusefauto1/guzzle-oauth2-plugin-compat

适用于 guzzle 的 OAuth2 插件

1.0.2 2020-03-11 14:24 UTC

This package is not auto-updated.

Last update: 2024-09-20 11:08:08 UTC


README

Guzzle 提供 OAuth2 插件。

功能

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

使用方法

只需设置访问令牌并发出请求。

use Guzzle\Http\Client;
use CommerceGuys\Guzzle\Plugin\Oauth2\Oauth2Plugin;

$accessToken = array(
  'access_token' => 'e72758a43e1646969f9f7bd7737d0cd637ed17ae',
  'expires' => '1391617481', // Optional.
);
$oauth2Plugin = new Oauth2Plugin();
$oauth2Plugin->setAccessToken($accessToken);

$client = new Client('https://mysite.com/api');
$client->addSubscriber($oauth2Plugin);
$request = $client->get('me');

或使用授权类型。可选地,添加刷新令牌授权类型,用于刷新过期的访问令牌。

use Guzzle\Http\Client;
use CommerceGuys\Guzzle\Plugin\Oauth2\Oauth2Plugin;
use CommerceGuys\Guzzle\Plugin\Oauth2\GrantType\PasswordCredentials;
use CommerceGuys\Guzzle\Plugin\Oauth2\GrantType\RefreshToken;

$oauth2Client = new Client('https://mysite.com/oauth2/token');
$config = array(
    'username' => 'myusername',
    'password' => 'mypassword',
    'client_id' => 'myclient',
    'client_secret' => 'mysecret',
    'scope' => 'administration', // Optional.
);
$grantType = new PasswordCredentials($oauth2Client, $config);
$refreshTokenGrantType = new RefreshToken($oauth2Client, $config);
$oauth2Plugin = new Oauth2Plugin($grantType, $refreshTokenGrantType);

$client = new Client('https://mysite.com/api');
$client->addSubscriber($oauth2Plugin);
$request = $client->get('me');
// $oauth2Plugin->getAccessToken() and $oauth2Plugin->getRefreshToken() can be
// used to export the tokens so that they can be persisted for next time.