PHP code example of bybrand / oauth2-frontapp

1. Go to this page and download the library: Download bybrand/oauth2-frontapp 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/ */

    

bybrand / oauth2-frontapp example snippets


use Bybrand\OAuth2\Client\Provider\FrontApp as ProviderFrontApp;

$params = $_GET;

$provider = new ProviderFrontApp([
    'clientId'    => 'key-id',
    'redirectUri' => 'your-url-redirect'
]);

if (!isset($params['code']) or empty($params['code'])) {
    // If we don't have an authorization code then get one
    $authorizationUrl = $provider->getAuthorizationUrl();

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

    header('Location: '.$authorizationUrl);
    exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($params['state']) || ($params['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);

    // Set error and redirect.
    echo 'Invalid stage';
} else {
    try {
        // Try to get an access token (using the authorization code grant)
        $token = $provider->getAccessToken('client_credentials', [
            'code' => $params['code']
        ]);
    } catch (\Exception $e) {
        // Error, make redirect or message.
    }

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