Google PHP SDK - not getting refresh token

214 Views Asked by At

I am trying to get a refresh token for the Google API's, using the PHP SDK. I am authenticating the user with Javascript, retrieving a code, and exchanging it for an access_token server side, but this doesn't grant me an access token. What am I doing wrong? Here is the code I use:

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->addScope('https://www.googleapis.com/auth/plus.me');
$client->addScope('https://www.google.com/m8/feeds');
$client->setRedirectUri('postmessage');
$client->setAccessType('offline');

if (isset($_REQUEST['code'])) {
    $client->authenticate($_REQUEST['code']);
    if ($client->getAccessToken()) {
        $_SESSION['access_token'] = $client->getAccessToken();
        $token_data = $client->verifyIdToken()->getAttributes();
        $result['data']=$token_data;
        $result['access_token']=json_decode($_SESSION['access_token']);
    }
}

debug($result); //my own function, var_dumps the content of an array

Here is the result of the array:

$result['access_token'] contains:

access_token: TOKEN
created: 1434380576
expires_in: 3594
id_token: IDTOKEN
token_type:"Bearer"

If I am not mistaken the first access token should also contain the refresh token, what am I doing wrong?

2

There are 2 best solutions below

3
On BEST ANSWER

First check the settings in the developer console of Google to see if your RedirectUri is the same and that the API is activated (although if you already got that .json, then I assume it is.

You have to go through the Google Auth Prompt Screen at least 1 time to get a refresh token in your .json, and if your RedirectUri is taking you nowhere, you won't be able to get your refresh token or even the access validated.

You can also try a service account if you're doing small file transactions and don't need a user validation for the process of your script. Good Luck.

0
On

The problem was that I had to specify that I want offline access in the authentication process, the client side... The Google API's are horribly documented!!!