oliverschloebe/oauth2-steadyhq

PHP League's OAuth 2.0 Client 的稳定 OAuth 2.0 包

1.0.0 2023-06-21 21:42 UTC

This package is auto-updated.

Last update: 2024-09-25 13:18:53 UTC


README

此包为 PHP League 的 OAuth 2.0 Client 提供稳定的 OAuth 2.0 支持。

StyleCI License Latest Stable Version Latest Version Source Code

安装

composer require oliverschloebe/oauth2-steadyhq

稳定API

https://developers.steadyhq.com/#oauth-2-0

使用

在 steadyhq.com 上注册您的应用程序 以获取 clientIdclientSecret

OAuth2 认证流程

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

//session_start(); // optional, depending on your used data store

$steadyProvider = new \OliverSchloebe\OAuth2\Client\Provider\Steady([
	'clientId'	=> 'yourId',          // The client ID of your Steady app
	'clientSecret'	=> 'yourSecret',      // The client password of your Steady app
	'redirectUri'	=> 'yourRedirectUri'  // The return URL you specified for your app on Steady
]);

// Get authorization code
if (!isset($_GET['code'])) {
	// Options are optional, scope defaults to ['read']
	$options = [ 'scope' => ['read'] ];
	// Get authorization URL
	$authorizationUrl = $steadyProvider->getAuthorizationUrl($options);

	// Get state and store it to the session
	$_SESSION['oauth2state'] = $steadyProvider->getState();

	// Redirect user to authorization URL
	header('Location: ' . $authorizationUrl);
	exit;
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { // Check for errors
	if (isset($_SESSION['oauth2state'])) {
		unset($_SESSION['oauth2state']);
	}
	exit('Invalid state');
} else {
	// Get access token
	try {
		$accessToken = $steadyProvider->getAccessToken(
			'authorization_code',
			[
				'code' => $_GET['code']
			]
		);
		
		// We have an access token, which we may use in authenticated
		// requests against the Steady API.
		echo 'Access Token: ' . $accessToken->getToken() . "<br />";
		echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br />";
		echo 'Expired in: ' . $accessToken->getExpires() . "<br />";
		echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br />";
	} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
		exit($e->getMessage());
	}

	// Get resource owner
	try {
		$resourceOwner = $steadyProvider->getResourceOwner($accessToken);
	} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
		exit($e->getMessage());
	}
        
	// Store the results to session or whatever
	$_SESSION['accessToken'] = $accessToken;
	$_SESSION['resourceOwner'] = $resourceOwner;
    
	var_dump(
		$resourceOwner->getId(),
		$resourceOwner->getName(),
		$resourceOwner->getEmail(),
		$resourceOwner->getAttribute('email'), // allows dot notation, e.g. $resourceOwner->getAttribute('group.field')
		$resourceOwner->toArray()
	);
}

刷新令牌

一旦您的应用程序获得授权,您可以使用刷新令牌刷新已过期的令牌,而不是通过获取全新的令牌的整个过程。为此,只需从您的数据存储中重用此刷新令牌以请求刷新。

$steadyProvider = new \OliverSchloebe\OAuth2\Client\Provider\Steady([
	'clientId'	=> 'yourId',          // The client ID of your Steady app
	'clientSecret'	=> 'yourSecret',      // The client password of your Steady app
	'redirectUri'	=> 'yourRedirectUri'  // The return URL you specified for your app on Steady
]);

$existingAccessToken = getAccessTokenFromYourDataStore();

if ($existingAccessToken->hasExpired()) {
	$newAccessToken = $steadyProvider->getAccessToken('refresh_token', [
		'refresh_token' => $existingAccessToken->getRefreshToken()
	]);

	// Purge old access token and store new access token to your data store.
}

发送认证的 API 请求

Steady OAuth 2.0 提供商提供了一种使用访问令牌获取服务的认证 API 请求的方法;它返回一个符合 Psr\Http\Message\RequestInterface 的对象。

$mySubscriptionsRequest = $steadyProvider->getAuthenticatedRequest(
	'GET',
	'https://steadyhq.com/api/v1/subscriptions/me', // see https://developers.steadyhq.com/#current-subscription
	$accessToken
);

// Get parsed response of current authenticated user's subscriptions; returns array|mixed
$mySubscriptions = $steadyProvider->getParsedResponse($mySubscriptionsRequest);

var_dump($mySubscriptions);

发送非认证的 API 请求

向 Steady API 的公共端点发送非认证的 API 请求;它返回一个符合 Psr\Http\Message\RequestInterface 的对象。

$httpClient = new \GuzzleHttp\Client([
	'headers' => [
		'X-Api-Key' => '<Your REST API Key>',
	],
]);

$steadyProvider = new Steady([
	// Your client options here (clientId, clientSecret etc)
], [
	'httpClient' => $httpClient
]);

$subscriptionsParams = [ 'filter[subscriber][email]' => 'alice@example.com' ];
$subscriptionsRequest = $steadyProvider->getRequest(
	'GET',
	'https://steadyhq.com/api/v1/subscriptions?' . http_build_query($subscriptionsParams)
);

// Get parsed response of non-authenticated API request; returns array|mixed
$subscriptions = $steadyProvider->getParsedResponse($subscriptionsRequest);

var_dump($subscriptions);

使用代理

可以使用代理来调试发送给 Steady 的 HTTP 调用。您需要做的所有事情是在创建 Steady OAuth2 实例时设置代理和验证选项。确保在代理中启用 SSL 代理。

$steadyProvider = new \OliverSchloebe\OAuth2\Client\Provider\Steady([
	'clientId'	=> 'yourId',          // The client ID of your Steady app
	'clientSecret'	=> 'yourSecret',      // The client password of your Steady app
	'redirectUri'	=> 'yourRedirectUri'  // The return URL you specified for your app on Steady
	'proxy'		=> '192.168.0.1:8888',
	'verify'	=> false
]);

要求

PHP 8.0 或更高版本。

测试

$ ./vendor/bin/parallel-lint src test
$ ./vendor/bin/phpunit --coverage-text
$ ./vendor/bin/phpcs src --standard=psr2 -sp

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅许可证文件