8

I've nearly searched every result of the first page of google for this. But can't seem to find the answer. I'm working with a refresh_token by Google's API and receiving:

Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }

What i'm doing. First: i'm creating and storing a persistant connection to the google api:

$client = new Google_Client();
$client->setClientId('xxxxxx-s73q0pa41aq3i2kcpatmpas6e6kkp99h.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxx');
$client->setRedirectUri('http://xxxxxxxx/generaterefreshtoken.php');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');


if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {

    $jsonarray = json_decode($client->getAccessToken());
    $arrGoogleAuth['access_token']=$jsonarray->access_token;
    $arrGoogleAuth['refresh_token']=$jsonarray->refresh_token;
    //filewrite

    $myFile = "refreshtoken.conf";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $client->getAccessToken());
    fclose($fh);


    /*

    die();

    $service = new Google_DriveService($client);
    $file = new Google_DriveFile();
    $file->setTitle('My document.txt');
    $file->setDescription('A test document');
    $file->setMimeType('text/plain');

    $data = file_get_contents('document.txt');

    $createdFile = $service->files->insert($file, array(
          'data' => $data,
          'mimeType' => 'text/plain',
        ));

    print_r($createdFile);
*/



  // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $auth = $client->createAuthUrl();
  header("Location: $auth");
}

So basicly everything runs and the token gets stored in a textfile:

{
"access_token":"xxxxxxxxxxxxxxxN4U0ys2wy5monxs0Xh5fu5ayKL0OIENo-d1sN6g3YA",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"xxxxxxxxxxxxDON-l90BNUcJgnkfZWDfg",
"created":1358120143
}

When i'm trying to auth using the following code:

$client = new Google_Client();
$client->setClientId($googleDriveConfig['clientid']);
$client->setClientSecret($googleDriveConfig['clientsecret']);
$client->setRedirectUri(curPageURL);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));
$client->authenticate();

I'm getting the following error: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }

Benjamin de Bos
  • 4,334
  • 4
  • 20
  • 30

5 Answers5

6

You'll get an "invalid_grant" error if you try to refresh when the token isn't expired.

Instead of this:

$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));

Use this:

$client->setAccessToken(file_get_contents('../_config/refreshtoken.conf'));

Once your token expires you refresh should work.

Steven McElveen
  • 429
  • 5
  • 6
3

The invalid_grant means either means that the authorization code has already been used (available in $GET['code']) or the type of application configured in the Google APIs Console is invalid.

Make sure you select "Web Application" when registering your app in the Google APIs Console.

Chirag Shah
  • 3,654
  • 22
  • 29
0

The function that worked for me is as follows

$client->setAccessType("refresh_token");

0

I ran into something similar and the problem for me was my system clock (inside the Docker VM where I was running the code) was not synchronized with the real time. So you are requesting a token with a created date too far in the past or future, which OAuth is rejecting.

I was tipped of by the report here.

Community
  • 1
  • 1
plowman
  • 13,335
  • 8
  • 53
  • 53
-4

Before Authenticate, there must be something like:

$client->grantType("refresh_token")
standup75
  • 4,734
  • 6
  • 28
  • 49
  • grantType is not a function on Google_Client, there is a refreshToken function, but it doesn't work either. – Mikushi Mar 19 '14 at 17:53
  • Why was this selected as correct if grantType isn't an actual function inside of Google_Client class? – EHerman Jul 16 '14 at 01:54
  • To anyone else looking to refresh their access token using a refresh token you can do ```$client->refreshToken( $refresh_token ); $_SESSION['token'] = $client->getAccessToken();``` You will get the invalid_grant returned if you are trying to refresh something other than you're most recently granted refresh token. – EHerman Jul 30 '14 at 13:15