Search code examples
apioauthtokenrefreshgoogle-api-php-client

Google Oauth for Refresh Token - invalid_grant


I'm trying to get a refresh token using PHP and curl from Google. I have been following this documentation

The followed the instructions successfully to get the "code" that I need to eventually get my refresh token, so I know that is set up correctly and I am using a proper redirect uri. Using the values that Google gives me to fill in my curl code, I created the following code:

$post = ["grant_type" => "authorization_code", "code" => "my recovered google code", "client_id" => "my oauth id", "client_secret" => "my client secret", "redirect_uri" => "my redirect id"];

$ch = curl_init('https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// log my returned tokens
file_put_contents('./tokenLogger-'.date("H.i.s").'.log', $result, FILE_APPEND);

All that I am getting my my log file is this:

{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}

I have wasted two days and could really use some direction. I am following Google's directions, and yet it is failing for me. Any insight would be extemely helpful. Thank you!!


Solution

  • This one was frustrating, but turned out to be fairly straight forward. When trying to obtain a refresh token, you must get a "code" from google that you use to obtain the refresh token. This "code" is only good for one use! If you try to use it and you have a bug in your code, you must generate a new "code" before you can try again. Whether it succeeds or fails, you only get one shot. I was under the impression that I could keep using it until it succeeded. That is not correct.