cloudadic/twin23-oauth2-php-sdk

此包的最新版本(v1.0)没有可用的许可证信息。

v1.0 2017-03-30 14:46 UTC

This package is not auto-updated.

Last update: 2024-09-15 02:27:18 UTC


README

此包使您轻松地将应用程序集成到 Twin23 OAuth 2.0 服务。

此包符合 PSR-1PSR-2PSR-4PSR-7。如果您注意到合规性问题,请通过拉取请求发送补丁。如果您有兴趣为此库做出贡献,请参阅我们的 贡献指南

要求

以下版本的 PHP 受支持。

  • PHP 5.5
  • PHP 5.6
  • PHP 7.0
  • PHP 7.1
  • HHVM

安装

通过 Composer

$ composer require cloudadic/twin23-oauth2-php-sdk

或者

将以下行添加到您的 composer.json 文件中

"cloudadic/twin23-oauth2-php-sdk":"*"

授权代码授予

授权代码授予类型是验证第三方服务用户时最常用的授权类型。此授权类型使用客户端(此库)、服务器(服务提供商)和资源所有者(具有受保护或拥有资源的凭证的用户)来请求访问用户拥有的资源。这通常被称为 三脚 OAuth,因为涉及三个实体。

现在,对于在 Twin23 上没有账户的用户,他们将被要求输入用户信息。一旦填写完表格,他们就可以登录了。

以下是配置客户端的方式。

// In order to get your OAuth 2 credentials you need to register your app at 

$client = new Twin23\OAuth2\Client([
    // The client ID assigned to you by the provided
    'client_id' => 'YOUR_CLIENT_ID',
    // The client secret provided
    'client_secret' => 'YOUR_CLIENT_SECRET',
    // Redirect URL
    'redirect_uri' => 'http://my.website.com/redirect-page',
    // Permissions to the data that you would like to retrieve
    'scope' => ['name', 'email', 'photo', 'phone']
]);

生成授权 URL

// Fetch the authorization URL. You can assign this to link on your web page.
$authorizationUrl = $client->getAuthorizationUrl();

生成访问令牌

if (!empty($_GET['code'])) {
    try {

        // Try to get an access token using the authorization code grant.
        $accessToken = $client->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);

        // We have an access token, which we may use in authenticated
        // requests against the service provider's 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>";

        // Using the access token, we may look up details about the user

    } catch (\Twin23\Exception\ResponseException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}

刷新令牌

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

$existingAccessToken = $client->getAccessToken('authorization_code', [
    'code' => $code
]);

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

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

获取身份信息

$identity = $client->getIdentity($accessToken->getToken());

许可证

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