PHP code example of ely / oauth2-client

1. Go to this page and download the library: Download ely/oauth2-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ely / oauth2-client example snippets



$provider = new \Ely\OAuth2\Client\Provider([
    'clientId'     => '{elyby-client-id}',
    'clientSecret' => '{elyby-client-secret}',
    'redirectUri'  => 'http://example.com/callback-uri',
]);


$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit();


$authUrl = $provider->getAuthorizationUrl([
    'scope' => ['account_info', 'account_email'],
    'description' => 'My super application!',
]);


if (isset($_GET['error'])) {
    echo 'Oh no! The error ' . $_GET['error'] . ' with message ' . $_GET['message'];
} elseif (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
    unset($_SESSION['oauth2state']);
    echo 'Invalid state value.';
} else {
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken(new \League\OAuth2\Client\Grant\AuthorizationCode(), [
        'code' => $_GET['code'],
    ]);

    // Optional: Now you have a token you can look up a users account data
    try {
        // We got an access token, let's now get the user's details
        $account = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $account->getUsername());
    } catch (\Ely\OAuth2\Client\Exception\IdentityProviderException $e) {
        // Failed to get user details
        echo 'Cannot get user account identity. The error is ' . $e->getMessage();
    }

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


$authUrl = $provider->getAuthorizationUrl([
    'scope' => ['account_info', 'account_email', 'offline_access'],
]);


$token = $provider->getAccessToken('authorization_code', [
    'code' => $code
]);

// persist the token in a database
$refreshToken = $token->getRefreshToken();


$token = $provider->getAccessToken(new League\OAuth2\Client\Grant\RefreshToken(), [
    'refresh_token' => $refreshToken,
]);