gn-office/oauth2-yahoo-japan

Yahoo Japan (Yconnect) OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1.1.0 2020-03-01 06:59 UTC

This package is auto-updated.

Last update: 2021-09-29 02:38:30 UTC


README

This package provides Yahoo! Japan OAuth 2.0 support for the PHP League's OAuth 2.0 Client.

Usage

<?php
use GNOffice\OAuth2\Client\Provider\YahooJapan;

session_start();

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

// Get authorization code
if (!isset($_GET['code'])) {

    // Get authorization URL
    $authorizationUrl = $provider->getAuthorizationUrl();

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

    // Get nonce and store it to the session.
    $_SESSION['oauth2nonce'] = $provider->getNonce();

    // Get code_verifier and store it to the session.
    $_SESSION['oauth2code_verifier'] = $provider->getCodeVerifier();

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

// Check for errors
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }

    exit('Invalid state');

} else {
    // Get access token
    try {
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code'],
            'code_verifier' => $_SESSION['oauth2code_verifier']
        ]);

        try {
            $nonce = $_SESSION['oauth2nonce'];

            $token_values = $accessToken->getValues();
            $id_token = $token_values['id_token'];
            $access_token = $accessToken->getToken();

            // Verify Token
            $verify_token = $provider->verifyToken($id_token, $access_token, $nonce);

            // Get resource owner
            $user = $provider->getResourceOwner($accessToken);

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

        } catch (GNOffice\OAuth2\Client\Provider\Exception\InvalidTokenException $e) {
            exit($e->getMessage());
        }

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

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

    }

    // Use this to interact with an API on the users behalf
    echo $accessToken->getToken();

}

Testing

$ ./vendor/bin/phpunit

License

The MIT License (MIT). Please see License File for more information.