PHP code example of joseayram / oauth2-lichess

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

    

joseayram / oauth2-lichess example snippets




session_start();

use CrudSys\OAuth2\Client\Provider\Lichess;

$clientId = 'api-lichess-test';
$clientSecret = '{your-secret-client}';
$redirectUri = '{your-redirect-uri}';

if (!isset($_SESSION['codeVerifier'])) {
    $verifier = createVerifier();
    $_SESSION['codeVerifier'] = $verifier;
} else {
    $verifier = $_SESSION['codeVerifier'];
}

$provider = new Lichess([
    'clientId'      => $clientId,
    'clientSecret'  => $clientSecret,
    'redirectUri'   => $redirectUri,
]);

if (!isset($_GET['code']) && !isset($_GET['error'])) {
    $challenge = createChallenge($verifier);

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl([
        'code_challenge' => $challenge,
    ]);

    $_SESSION['oauth2state'] = $provider->getState();

    echo "<a href='{$authUrl}'>Login with Lichess</a>";
} elseif ((isset($_GET['error']) && !empty($_GET['error']) ) &&
        (isset($_GET['error_description']) && !empty($_GET['error_description']) )
) {
    unset($_SESSION['oauth2state']);
    exit($_GET['error'].': '.$_GET['error_description']);
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    exit('Invalid state, make sure HTTP sessions are enabled.');
} else {
    // Try to get an access token (using the authorization code grant)
    try {
        $token = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code'],
            'code_verifier' => $_SESSION['codeVerifier'],
        ]);
    } catch (\Exception $e) {
        exit('Failed to get access token: '.$e->getMessage());
    }

    // 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
        $user = $provider->getResourceOwner($token);
        // Use these details to create a new profile
        printf('Hello %s!\n<br>', $user->getUsername());
        echo "<pre>" . print_r($user, true) . "</pre>";
    } catch (\Exception $e) {
        exit('Failed to get resource owner: '.$e->getMessage());
    }

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

$options = [
    'scope' => [Lichess::SCOPE_EMAIL, Lichess::SCOPE_PREFERENCE_READ]
];

$authorizationUrl = $provider->getAuthorizationUrl($options);