wheniwork/oauth2-square

为PHP League的OAuth2-Client提供的Square OAuth 2.0客户端提供者

v2.0.0-beta1 2015-08-05 17:52 UTC

README

Build Status Code Coverage Code Quality License Latest Stable Version

此包为PHP League的OAuth 2.0客户端提供了Square OAuth 2.0支持。

安装

要安装,请使用composer

composer require wheniwork/oauth2-square

使用方法

使用方法与The League的OAuth客户端相同,使用Wheniwork\OAuth2\Client\Provider\Square作为提供者。

要针对Square测试服务器进行请求,请将'debug' => true作为初始配置选项的一部分传递。

授权码流

$provider = new Wheniwork\OAuth2\Client\Provider\Square([
    'clientId'          => '{square-client-id}',
    'clientSecret'      => '{square-client-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();
    $_SESSION['oauth2state'] = $provider->state;
    header('Location: '.$authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    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']
    ]);

    // 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 user's details
        $userDetails = $provider->getUserDetails($token);

        // Use these details to create a new profile
        printf('Hello %s!', $userDetails->firstName);

    } catch (Exception $e) {

        // Failed to get user details
        exit('Oh dear...');
    }

    // Use this to interact with an API on the users behalf
    echo $token->accessToken;
}

刷新令牌

Square不提供刷新令牌。相反,在过期后15天内,访问令牌可以被“更新”。为了适应这一点,Square提供者提供了一个额外的授权,RenewToken

$provider = new Wheniwork\OAuth2\Client\Provider\Square([
    'clientId'          => '{square-client-id}',
    'clientSecret'      => '{square-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url'
]);

$token = $provider->getAccessToken('renew_token', ['access_token' => $accessToken]);

此授权也可以通过直接注入AccessToken实例来使用,而不是提供给getAccessToken的参数。

$grant = new Wheniwork\OAuth2\Client\Grant\RenewToken($token);
$token = $provider->getAccessToken($grant);