Just posting my answer in case it helps anyone as I spent an hour to figure it out :)
First of all two very helpful link related to google api and fetching data from any of google services:
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php
https://developers.google.com/identity/protocols/OAuth2WebServer
Furthermore, when using the following method:
$client->setAccessToken($token)
The $token
needs to be the full object returned by the google when making authorization request, not the only access_token
which you get inside the object so if you get the object lets say:
{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}
then you need to give:
$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')
Not
$client->setAccessToken('xyz')
And then even if your access_token
is expired, google will refresh it itself by using the refresh_token
in the access_token
object.