waytohealth/oauth2-omron

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


README

本软件包为 PHP League 的 OAuth 2.0 客户端 提供Omron OAuth 2.0 支持。

本软件包符合 PSR-1PSR-2PSR-4PSR-7 标准。如果您注意到有任何不符合标准的地方,请通过 pull request 提交补丁。

要求

以下版本的 PHP 受支持。

  • PHP 5.6
  • PHP 7.0
  • PHP 7.1
  • HHVM

安装

要安装,请使用 composer

composer require waytohealth/oauth2-omron

用法

授权代码授予

use waytohealth\OAuth2\Client\Provider\Omron;

$provider = new Omron([
    'clientId'          => '{omron-oauth2-client-id}',
    'clientSecret'      => '{omron-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url'
]);

// start the session
session_start();

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

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

} else {

    try {

        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->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 $accessToken->getToken() . "\n";
        echo $accessToken->getRefreshToken() . "\n";
        echo $accessToken->getExpires() . "\n";
        echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

        // The provider provides a way to get an authenticated API request for
        // the service, using the access token; it returns an object conforming
        // to Psr\Http\Message\RequestInterface.
        $request = $provider->getAuthenticatedRequest(
            Withings::METHOD_GET,
            Withings::BASE_WITHINGS_API_URL . '/v2/user?action=getdevice',
            $accessToken,
            ['headers' => [Withings::HEADER_ACCEPT_LANG => 'en_US'], [Withings::HEADER_ACCEPT_LOCALE => 'en_US']]
            // Fitbit uses the Accept-Language for setting the unit system used
            // and setting Accept-Locale will return a translated response if available.
            // https://dev.fitbit.com/docs/basics/#localization
        );
        // Make the authenticated API request and get the parsed response.
        $response = $provider->getParsedResponse($request);

        // If you would like to get the response headers in addition to the response body, use:
        //$response = $provider->getResponse($request);
        //$headers = $response->getHeaders();
        //$parsedResponse = $provider->parseResponse($response);

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

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

    }

}

刷新令牌

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

$provider = new waytohealth\OAuth2\Client\Provider\Omron([
    'clientId'          => '{omron-oauth2-client-id}',
    'clientSecret'      => '{omron-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url',
    'authHostname'      => 'https://oauth.omronwellness.com',
    'apiUrl'            => 'https://api.omronwellness.com/api/measurement'
]);

$existingAccessToken = getAccessTokenFromYourDataStore();

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

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

测试

$ ./vendor/bin/phpunit

贡献

请参阅 CONTRIBUTING 以获取详细信息。

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 以获取更多信息。