首页 > 解决方案 > 刷新令牌的 Google Oauth - invalid_grant

问题描述

我正在尝试使用 PHP 和来自 Google 的 curl 获取刷新令牌。我一直在关注这个文档

成功地按照说明获取了最终获取刷新令牌所需的“代码”,因此我知道设置正确并且我使用了正确的重定向 uri。使用 Google 提供的值来填写我的 curl 代码,我创建了以下代码:

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

我得到的日志文件是这样的:

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

我浪费了两天时间,真的可以使用一些方向。我遵循谷歌的指示,但它对我来说失败了。任何见解都会非常有帮助。谢谢!!

标签: apioauthtokenrefreshgoogle-api-php-client

解决方案


这令人沮丧,但结果却相当直截了当。尝试获取刷新令牌时,您必须从 google 获取用于获取刷新令牌的“代码”。这个“代码”只适用于一种用途! 如果您尝试使用它并且代码中存在错误,则必须生成新的“代码”才能重试。无论成功或失败,你只能得到一枪。我的印象是我可以继续使用它,直到它成功。这是不正确的。


推荐阅读