Create a token in the google-api-php-client library

Viewed 537

I am currently having problems on the google-api-php-client library. when I use the fetchAccessTokenWithAuthCode() method I get a critical error. it would come from $httpHandler which should be a callback function $httpHandler = HttpHandlerFactory::build($this->getHttpClient()); which is actually an object... Has anyone had this problem before? thanks in advance.

    $gClient = new Google_Client();
    $GLOBALS['gClient'] = $gClient; 
    $gClient->setClientId( '' ); //omitted for privacy
    $gClient->setClientSecret( '' ); //omitted for privacy
    $gClient->setApplicationName( 'Mon application' );
    $gClient->setRedirectUri( 'http://localhost/vevweb/wp-admin/admin-ajax.php?action=vm_login_google' );
    $gClient->addScope( 'https://www.googleapis.com/auth/userinfo.email' );

    if( isset( $_GET['code'] ) ) {
                $gClient->authenticate($_GET['code']);//This code return critical error
    }
1 Answers

Why do you want to use fetchAccessTokenWithAuthCode why not just use $client->authenticate($_GET['code']);? I think it would be better to find out why you are having an error with the standard authorization method then to switch to a different one.

oauth2callback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Tbh i would check how you are building your client

function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

code ripped from Oauth2Authentication.php

Related