Search code examples
phpoauth-2.0google-api

How to fetch auth token for service account using google API?


I have a Wordpress site (running PHP) that needs to display its own analytics data to visitors using the google-api. I want to create the charts in Javascript, so I need to fetch an auth token from the PHP code and then pass that to the Javascript code. I can't figure out how to get the auth token.

So far, I have code similar to this working using my service account: https://github.com/google/google-api-php-client/blob/master/examples/service-account.php

My code:

$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);

$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");


$analytics = new Google_Service_Analytics($client);
$ga = $analytics->data_ga;

$start = date('Y-m-d', strtotime('-7 days'));
$end   = date('Y-m-d');

$views = $ga->get('ga:'.$myAnalyticsId,
                $start,
                $end,
                'ga:pageviews,ga:sessions,ga:newUsers',
                array(
                    'dimensions' => 'ga:date',
                    'sort' => 'ga:date'
                ));

This all works, and I'm able to connect to Google_Service_Analytics and fetch analytics data. However, I can't figure out how to fetch a service access token using my credentials, that I can hand off to the Javascript code so I can use the Google Analytics API from Javascript.

This doesn't work:

$token = $client->getAccessToken();

Token just ends up being null. What do I need to do to fetch a token?


Solution

  • Here is the working code for me. The service account has a different type of process for generating access token. It is not following oauth client api.

    //include_once 'vendor/autoload.php';
    $credentialsFilePath = 'test.json';
    $client = new Google_Client();
    $client->setAuthConfig($credentialsFilePath);
    
    $client->addScope('https://www.googleapis.com/auth/analytics.readonly');
    $client->setApplicationName("GoogleAnalytics");
    $client->refreshTokenWithAssertion();
    $token = $client->getAccessToken();
    print_r($token);
    $accessToken = $token['access_token'];