PHP code example of worksection / oauth2-worksection

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

    

worksection / oauth2-worksection example snippets


use Worksection\OAuth2\Client\Provider\Worksection as WorksectionOauth2;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;

$provider = new WorksectionOauth2([
    'clientId'                => 'yourId',   
    'clientSecret'            => 'yourSecret',
    'redirectUri'             => 'https://redirecturl.com/query'
]);


if (!$_REQUEST['code']) {
    $authorizationUrl = $provider->getAuthorizationUrl(['scope' => 'projects_read users_write']);
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authorizationUrl);

} elseif ($_REQUEST['state']) {
    if ($_REQUEST['state'] !== $_SESSION['oauth2state']) {
        exit('Invalid state');
    } else {
        unset($_SESSION['oauth2state']);
    }
    
    // Access token
    try {
        $accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
    } catch (IdentityProviderException $e) {
        exit($e->getMessage());
    }

    // Resource info
    try {
        $resourceOwner = $provider->getResourceOwner($accessToken);
    } catch (IdentityProviderException $e) {
        exit($e->getMessage());
    }
    
    //echo 'Access Token: ' . $accessToken->getToken();
    //echo 'Refresh Token: ' . $accessToken->getRefreshToken();
    //echo 'Account URL: ' . $accessToken->getValues()['account_url'];
    //echo 'Expired in: ' . $accessToken->getExpires();
    //echo 'Resource Owners ID: ' . $resourceOwner->getId();
    //echo 'Resource Owners NAME: ' . $resourceOwner->getName();
    //echo 'Resource Owners EMAIL: ' . $resourceOwner->getEmail();
    //echo 'Resource Owners Account URL: ' . $resourceOwner->getAccountUrl();

    // Make some API request using Access Token
    $options = [
        'body' => json_encode([
            'action' => 'get_tasks',
            'page' => '/project/193/'
        ]),
        'headers' => [
            'Content-Type' => 'application/json'
        ]
    ];
    $request = $provider->getAuthenticatedRequest('POST', $resourceOwner->getAccountUrl() . '/api/oauth2', $accessToken, $options);
    try {
        $response = $provider->getParsedResponse($request);
    } catch (IdentityProviderException $e) {
        exit($e->getMessage());
    }
    var_dump($response);
}