oliverschloebe/oauth2-rbtv

PHP League OAuth 2.0 客户端的 Rocket Beans TV OAuth 2.0 包

1.1.1 2021-12-09 17:31 UTC

This package is auto-updated.

Last update: 2024-09-09 23:51:17 UTC


README

本包为 PHP League 的 OAuth 2.0 客户端提供了 Rocket Beans TV OAuth 2.0 支持。

CircleCI Build Status StyleCI License Latest Stable Version Latest Version Source Code

安装

composer require oliverschloebe/oauth2-rbtv

Rocket Beans TV API

https://github.com/rocketbeans/rbtv-apidoc

用法

在 rocketbeans.tv 上注册您的应用程序以获取 clientIdclientSecret

OAuth2 认证流程

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

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

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

// Get authorization code
if (!isset($_GET['code'])) {
	// Options are optional, scope defaults to ['user.info']
	$options = [ 'scope' => ['user.info', 'user.email.read', 'user.notification.list', 'user.notification.manage', 'user.subscription.manage', 'user.subscriptions.read', 'user.rbtvevent.read', 'user.rbtvevent.manage'] ];
	// Get authorization URL
	$authorizationUrl = $rbtvProvider->getAuthorizationUrl($options);

	// Get state and store it to the session
	$_SESSION['oauth2state'] = $rbtvProvider->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 = $rbtvProvider->getAccessToken(
			'authorization_code',
			[
				'code' => $_GET['code']
			]
		);
		
		// We have an access token, which we may use in authenticated
		// requests against the RBTV 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 = $rbtvProvider->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()
	);
}

刷新令牌

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

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

$existingAccessToken = getAccessTokenFromYourDataStore();

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

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

发送经过身份验证的 API 请求

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

$subscriptionsRequest = $rbtvProvider->getAuthenticatedRequest(
	'GET',
	'https://api.rocketbeans.tv/v1/subscription/mysubscriptions', // see https://github.com/rocketbeans/rbtv-apidoc#list-all-subscriptions
	$accessToken
);

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

var_dump($mySubscriptions);

发送未经身份验证的 API 请求

向 RBTV API 的公开端点发送未经身份验证的 API 请求;它返回一个符合 Psr\Http\Message\RequestInterface 的对象。

$blogParams = [ 'limit' => 10 ];
$blogRequest = $rbtvProvider->getRequest(
	'GET',
	'https://api.rocketbeans.tv/v1/blog/preview/all?' . http_build_query($blogParams)
);

// Get parsed response of non-authenticated API request; returns array|mixed
$blogPosts = $rbtvProvider->getParsedResponse($blogRequest);

var_dump($blogPosts);

使用代理

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

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

要求

PHP 5.6 或更高版本。

测试

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

许可证

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