Obtain Google API Access Token Through Command Line Using PHP

| July 10, 2022 | 1,312 views | Google Sheets API PHP Client

To test your Google Credential OAuth Client ID, you can quickly make a php script to see if you can obtain an access token. You will be using this access token to call Google Sheets API to send request to edit, create, and delete Google Sheets spreadsheets.

Requirements:

Step 1.

Inside your working directory, create a file (obtain-access-token.php), and copy/paste the following code.

<?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;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Google\Client();
    $client--->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/spreadsheets');
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $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.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // 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($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

// Get the API client and construct the service object.
$client = getClient();

Step 2.

Execute the following command to obtain a Google API Access Token.

$ php obtain-access-token.php

It will prompt you to authorize access, and as stated, open the given link in your browser.

Sign in to your Google Account.

Make sure the email account you are signing in to is added as user when you Created A Google OAuth Consent Screen – see Step 5 of Create A Google OAuth Consent Screen.

For this is a test google sheets web application, a warning “This app isn’t verified” will be displayed, just click continue.

Check the access being requested, and click “Done“, and click “Continue“.

Step 3.

You will be redirected to the Authorized Redirect URI you have set when you Created A Google Credential OAuth Client ID – see Step 4 of Create A Google Credential OAuth Client ID.

Copy the given code, and paste it on the command line, and then click enter.

Done.

The Google API Access token has been obtained from the command line using PHP. Now, check your working directory for the saved file token.json.

The file contains the following, and you will be using this file (token.json) when you send API Requests to Google Sheets API.

  • access_token
  • expires_in
  • refresh_token
  • scope
  • token_type
  • created

References:

0 Comments

Leave a Reply

Your email address will not be published.