PHP code example of fotografde / oauth-client

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

    

fotografde / oauth-client example snippets




$provider = new Getphoto\Oauth2\OauthProvider([
    'clientId'                => 'testclient',
    'clientSecret'            => 'testclient'
]);


try {
    // Try to get an access token using the client credentials grant.
    $token=$provider->getAccessToken( 'client_credentials', ['scope'=>'testscope'] );
    
} catch (\Exception $e) {
    // Failed to get the access token
    exit($e->getMessage());
}




$provider = new Getphoto\Oauth2\OauthProvider([
    'clientId'                => 'testclient',
    'clientSecret'            => 'testclient'
]);


try {
    // Try to get an access token using the password grant.
    $token=$provider->getAccessToken( 'password', [
                    'scope'=>'testscope',
                    'username' => '[email protected]',
                    'password' => 'password'
                ]));                    
    
} catch (\Exception $e) {
    // Failed to get the access token
    exit($e->getMessage());
}

//we can then use getResorceOwner to get user data
$data['resource_owner']=$provider->getResourceOwner($token);                
$username=$data['resource_owner']->getName();




$provider = new Getphoto\Oauth2\OauthProvider([
    'clientId'                => 'testclient',
    'clientSecret'            => 'testclient'
]);


try {
    // Try to get an access token using the password grant.
    $token=$provider->getAccessToken( 'password_ftp', [
                    'scope'=>'testscope',
                    'username' => 'test',
                    'password' => 'password'
                ]));                    
    
} catch (\Exception $e) {
    // Failed to get the access token
    exit($e->getMessage());
}

//we can then use getResorceOwner to get user data
$data['resource_owner']=$provider->getResourceOwner($token);                
$username=$data['resource_owner']->getName();




$provider=new OauthProvider([
    'clientId'                => 'testclient',
    'clientSecret'            => 'testclient',
    'redirectUri'             => 'here_goes_current_url'               
]);


// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl(['scope' => 'testscope']);

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

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

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    // State is invalid, possible CSRF attack in progress
    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    try {
        // Try to get an access token using the authorization code grant.
        $token=$provider->getAccessToken( 'authorization_code', [
            'scope' => 'testscope',
            'code'  => $_GET['code']
        ]);

    } catch (\Exception $e) {
        // Failed to get the access token
        exit('ERROR: '.$e->getMessage());
    }
}

//we can then use getResorceOwner to get user data
$data['resource_owner']=$provider->getResourceOwner($token);                
$username=$data['resource_owner']->getName();




$resource_owner=$provider->getResourceOwner($token);                
$user_name=$resource_owner->getName();
$user_email=$resource_owner->getEmail();
$user_id=$resource_owner->getId();
$user_data=$resource_owner->getUserData(); //gets related user data
/*
 [
   "id" => 7053
   "name" => "tre"
   "email" => "[email protected]"
   "created_at" => null
   "updated_at" => "2017-05-15 10:03:10"
   "core_user_id" => 20128
   "photographer_id" => 47911
 ]
*/

$user_scopes=$resource_owner->getScopes(); //get scopes token hass access to
/*
 [
   "payment.settings.read" => [
     "id" => "payment.settings.read"
     "description" => "Some nice description"
   ]
 ]
*/


public function __construct(array $options = [], array $collaborators = [])


public function clearTokenCache($prefix = '')


$this->oauthProvider = new OauthProvider(
    [
        'clientId' => 'some_clinet',
        'clientSecret' => 'some_secret',
        'cachePrefix' => 'userApi'
    ],
    [
        'cacher' => new OauthCakeCacher(), //implemented using native cake cache
        'logger' => new OauthCakeLogger()  //implemented using native cake log
    ]
);


$token = $this->oauthProvider->getAccessTokenSmart('client_credentials', [
    'scope' => 'some_scope'
]);


... //some call to protected API with your token goes here
$response = $request->send();
...

//clear token if invalid
if ($response->getStatusCode() == 403 || $response->getStatusCode() == 401) {
    //forget invalid token
    $this->oauthProvider->clearTokenCache();
}


$this->oauthProvider->expireAccessToken("g2WvRwXDQrIEmi0Qkcs0Qt11ch4AbkW2Yakh8BqI");