我正在尝试使用PHP和curl从Google获取刷新令牌。我一直关注这个documentation
成功遵循说明获取最终获得刷新令牌所需的“代码”,因此我知道设置正确并且我正在使用正确的重定向uri。使用Google为我填写卷曲代码的值,我创建了以下代码:
$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"
}
我浪费了两天,真的可以用一些方向。我正在遵循谷歌的指示,但它对我来说是失败的。任何见解都会非常有用。谢谢!!
这个令人沮丧,但事实证明是相当直接的。在尝试获取刷新令牌时,您必须从谷歌获取用于获取刷新令牌的“代码”。这个“代码”只适合一次使用!如果您尝试使用它并且代码中存在错误,则必须先生成新的“代码”,然后才能再次尝试。无论是成功还是失败,你只能得到一次。我的印象是我可以继续使用它直到它成功。这是不正确的。