geekdevs / oauth2-cronofy
The PHP League OAuth2-Client 的 Cronofy OAuth 2.0 客户端提供程序
2.0.2
2020-04-06 12:30 UTC
Requires
- php: ^7.4
- league/oauth2-client: ^2.4
- somoza/oauth2-client-middleware: ~0.3.0
Requires (Dev)
- mockery/mockery: ^1.3.1
- phpunit/phpunit: ^4.8.21
- squizlabs/php_codesniffer: ^2.5.1
README
此软件包为 PHP League 的 Cronofy 日历 OAuth 2.0 提供支持。
此软件包符合 PSR-1、PSR-2、PSR-4 和 PSR-7 规范。如果您发现不符合规范的地方,请通过拉取请求发送补丁。
要求
以下版本的 PHP 受支持。
- PHP 7.4
安装
将以下内容添加到您的 composer.json
文件中。
{ "require": { "geekdevs/oauth2-cronofy": "^2.0" } }
使用方法
授权码流
session_start(); $provider = new Geekdevs\OAuth2\Client\Provider\Cronofy([ 'clientId' => '{cronofy-app-id}', 'clientSecret' => '{cronofy-app-secret}', 'redirectUri' => 'https://example.com/callback-url' ]); if (!isset($_GET['code'])) { // If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl([ 'scope' => ['read_account', '...', '...'], ]); $_SESSION['oauth2state'] = $provider->getState(); echo '<a href="'.$authUrl.'">Log in with Cronofy!</a>'; exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); echo 'Invalid state.'; exit; } // Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // Optional: Now you have a token you can look up a users profile data try { // We got an access token, let's now get the account's details $account = $provider->getResourceOwner($token); // Use these details to create a new profile printf('Hello %s!', $account->getName()); echo '<pre>'; var_dump($account); # object(League\OAuth2\Client\Provider\CronofyAccount)#10 (1) { ... echo '</pre>'; } catch (Exception $e) { // Failed to get account details exit('Oh dear...'); } echo '<pre>'; // Use this to interact with an API on the users behalf var_dump($token->getToken()); # string(217) "CAADAppfn3msBAI7tZBLWg... // Number of seconds until the access token will expire, and need refreshing var_dump($token->getExpires()); # int(1436825866) echo '</pre>';
CronofyAccount 实体
当使用 getResourceOwner()
方法获取账户详情时,它将作为一个 CronofyAccount
实体返回。
$account = $provider->getResourceOwner($token); $id = $account->getId(); var_dump($id); # string(1) "acc_567236000909002" $name = $account->getName(); var_dump($name); # string(15) "Pavel Dubinin" $email = $account->getEmail(); var_dump($email); # string(15) "geekevs@gmail.com" $timezone = $account->getDefaultTimezone(); var_dump($timezone); # string(15) "Europe/London"
您也可以使用 toArray()
方法以纯 PHP 数组的形式从账户节点获取所有数据。
$accountData = $account->toArray();
测试
$ ./vendor/bin/phpunit
贡献
请参阅 CONTRIBUTING 以获取详细信息。
鸣谢
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。