Home > OS >  How to get Google OAuth2 access token and refresh token using PHP
How to get Google OAuth2 access token and refresh token using PHP

Time:10-04

I need to get Google OAuth2 access token in cron job and I want to get listCommentThreads which moderations status is heldForReview. Problem is I can't write the redirect URL in cron job How can I fix this issue? please help me

CodePudding user response:

The only possibility is to get the refresh_token. You can get it after requesting to google an offline access, and after the user authenticate itself.

With the refresh_token, you can ask for an access_token. It's something like does thunderbird : it stores refresh_token and the user email to get new access_token before the IMAP authentification.

CodePudding user response:

The following is a basic example altered from the google drive quickstart.

It uses an installed application and will store your token in 'token.json'

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

use Google\Client;
use Google\Service\YouTube;

const CREDENTIALS = 'C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json';
const SCOPES = [Google_Service_YouTube::YouTube];   // scope must be configured in workspace.
const USERTOKENPATH = 'token.json';

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 * @throws \Google\Exception
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('YouTube API PHP Quickstart');
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CREDENTIALS);
    $client->setAccessType('offline');
    $client->setRedirectUri("http://127.0.0.1");
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.

    if (file_exists(USERTOKENPATH)) {

        // Load stored tokens
        $tokens = json_decode(file_get_contents(USERTOKENPATH), true);
        $client->fetchAccessTokenWithRefreshToken($tokens["refresh_token"]);
    }

    // If there is no previous token, or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname(USERTOKENPATH))) {
            mkdir(dirname(USERTOKENPATH), 0700, true);
        }
        file_put_contents(USERTOKENPATH, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
try {
    $client = getClient();
} catch (Exception $e) {

    echo 'Message: ' . $e->getMessage();

    // if authorization failed we delete token file and try again.
    unlink(USERTOKENPATH);
    $client = getClient();
}

$service = new YouTube($client);

// call api here.
  • Related