layered / oauth2-wordpress-com
WordPress.com OAuth 2.0 客户端提供者,用于 PHP League OAuth 2.0 客户端
v1.1
2019-01-07 14:02 UTC
Requires
- league/oauth2-client: ^2.0
Requires (Dev)
- mockery/mockery: ~1.2
- phpunit/phpunit: ~7.0
This package is auto-updated.
Last update: 2024-09-29 04:36:54 UTC
README
此软件包为 PHP League 的 WordPress.com OAuth 2.0 提供支持。
要求
此软件包使用 WordPress.com Connect 来验证用户使用 WordPress.com 账户。
使用此软件包的要求
- PHP >= 5.6
- WordPress 客户端 ID 和客户端密钥,分别称为
{wordpress-client-id}和{wordpress-client-secret}。请按照 WordPress Apps 指示创建所需的凭证
安装
使用 composer 安装
composer require layered/oauth2-wordpress-com
用法
用法与 The League 的 Abstract OAuth 客户端相同,使用 \Layered\OAuth2\Client\Provider\WordPressCom 作为提供者。
授权代码流
use Layered\OAuth2\Client\Provider\WordPressCom; $provider = new WordPressCom([ 'clientId' => '{wordpresscom-client-id}', 'clientSecret' => '{wordpresscom-client-secret}', 'redirectUri' => 'https://example.com/callback-url', 'blog' => 'https://example.com' // optional - request auth for a specific blog ]); if (isset($_GET['error'])) { // Got an error, probably user denied access exit('Error: ' . htmlspecialchars($_GET['error_description'] . ' (' . $_GET['error_description'] . ')', ENT_QUOTES, 'UTF-8')); } elseif (!isset($_GET['code'])) { // If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth2state'] = $provider->getState(); header('Location: '. $authUrl); exit; } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { // Check given state against previously stored one to mitigate CSRF attack unset($_SESSION['oauth2state']); exit('Invalid state'); } else { // Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // If auth was for a single site or global access, token contains extra blog info $tokenValues = $token->getValues(); echo 'Blog ID: ' . $tokenValues['blog_id'] . '<br>'; echo 'Blog URL: ' . $tokenValues['blog_url'] . '<br>'; // Get user profile data try { // We got an access token, let's now get the user's details $user = $provider->getResourceOwner($token); // Use these details to create a new profile printf('Hello %s!', $user->getName()); } catch (\Exception $e) { // Failed to get user details exit('Something went wrong: ' . $e->getMessage()); } // Use this to interact with an API on the users behalf echo $token->getToken(); }
可用选项
WordPressCom 提供者有以下 选项
blog可以是 WordPress.com 博客或 Jetpack 站点的博客 URL 或博客 IDscope请求访问额外的数据
作用域
在创建授权 URL 时,指定应用程序可以授权的作用域。WordPress.com 的可用作用域
auth仅用于认证,授予对 /me 端点的访问权限global访问所有用户的站点和数据- '' (空) 访问请求中指定的单个博客或用户选择的博客
获取用户资料访问权限
$provider->getAuthorizationUrl([ 'scope' => 'auth' ]);
获取用户资料和单个博客的访问权限
$provider->getAuthorizationUrl([ 'scope' => '' ]);
测试
composer test
致谢
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。