Google 刷新令牌的 Oauth - invalid_grant

Google Oauth for Refresh Token - invalid_grant

我正在尝试使用 PHP 获取刷新令牌并从 Google 卷曲。我一直在关注这个documentation

按照说明成功获得 "code" 我需要最终获得我的刷新令牌,所以我知道它设置正确并且我正在使用正确的重定向 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"
}

我浪费了两天时间,真的需要一些指导。我正在按照 Google 的指示进行操作,但它对我来说是失败的。任何见解都会非常有帮助。谢谢!!

这个过程令人沮丧,但结果却相当简单。尝试获取刷新令牌时,您必须从 google 获取用于获取刷新令牌的 "code"。这个 "code" 只适合 一次使用! 如果你尝试使用它并且你的代码中有一个错误,你必须在你之前生成一个新的 "code"可以再试一次。无论成功与否,你只有一次机会。我的印象是我可以继续使用它直到它成功。这是不正确的。