2013-01-14 00:01
浏览 130

Google-api-php Refresh Token返回invalid_grant

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();

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

if (isset($_SESSION['token'])) {

if (isset($_REQUEST['logout'])) {

if ($client->getAccessToken()) {

    $jsonarray = json_decode($client->getAccessToken());

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



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

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

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


  // 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:


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

$client = new Google_Client();

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douzhao7014 2013-05-21 16:19

    Before Authenticate, there must be something like:

    解决 无用
    打赏 举报
  • dqjcb132285 2013-01-27 07:30

    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.

    解决 无用
    打赏 举报
  • ds3422222222 2014-04-24 18:50

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

    Instead of this:


    Use this:


    Once your token expires you refresh should work.

    解决 无用
    打赏 举报
  • dongxuanyi3406 2016-05-30 10:20

    The function that worked for me is as follows


    解决 无用
    打赏 举报
  • dsgd4654674 2016-09-26 03:38

    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题