Search code examples
phpgoogle-analyticsgoogle-apiservice-accounts

Get Google Analytics API token / Google_Client getAccessToken returns null / empty


I'm trying to get a Google access token for a service account so I can access the Analytics API from the client side.

On the server side I have the following code:

    $keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxxxx.json';
    $client = new Google_Client();
    $client->setApplicationName('Analytics Demo');
    $client->setAuthConfig($keyFile);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

    $token = $client->getAccessToken();  // Returns null

At some point it returned a token, but after a couple of calls it started returning null.

Trying to get the $client->getRefreshToken() also returns null.

When I put $client in a Google_Service_Analytics object everything seems to work just fine, so I know the key file is correct and properly read:

    $analytics = new Google_Service_Analytics($client);
    $accounts = $analytics->management_accounts->listManagementAccounts(); // Returns proper data

Any ideas on what might be going wrong?

UPDATE:

Calling $client->isAccessTokenExpired() results in true so I guess I have to refresh the token, but I have no clue how.


Solution

  • After a lot of trial and error I found that I had to use $client->fetchAccessTokenWithAssertion() instead of $client->getAccessToken().

    public static function getGoogleServiceToken():?string {
        $keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxx.json';
        $client = new Google_Client();
        $client->setAuthConfig($keyFile);
        $client->setApplicationName('Analytics Demo');
        $client->setAccessType('access_type');
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    
        if ($client->isAccessTokenExpired()) {
            $token = $client->fetchAccessTokenWithAssertion();
        }
        else {
            $token = $client->getAccessToken();
        }
    
        return $token['access_token'];
    }
    

    Client side:

    ...
    private _handleGetResponse(response) {
        ...
        gapi.analytics.auth.authorize({
                serverAuth: {
                    access_token: response.token,
                }
            });
        ...
    

    Not sure why there is no decent documentation on this at all. Even knowing that I have to use this method I can't find documentation on what this method is actually doing. Any explanation or links to some documentation are still welcome!