使用GoogleAPI的OAuth出现'invalid_grant'错误

3
我正在使用PHP创建一个内部应用程序,该应用程序使用Google Analytics报告API。该应用程序将始终使用相同的Google帐户连接到Analytics,因此我希望只在我的数据库中保留访问和刷新令牌。
我使用了 Google教程来设置OAuth。我采取了以下步骤: 引导代码(每个步骤都需要)
$client = new apiClient();
$client->setApplicationName("Stat-robot");
$client->setApprovalPrompt("force");            
$client->setAccessType('offline');
$client->setClientId("CLIENT_ID");
$client->setClientSecret("CLIENT_SECRET");
$client->setDeveloperKey("DEV_KEY");
$client->setRedirectUri("http://localhost/statistics/api");
$client->setScopes("https://www.googleapis.com/auth/analytics.readonly");

步骤 1

Redirect to the URL retrieved from $client->createAuthUrl())

步骤2。
//Get a redirect from Google with a GET-variable 'code'
$client->authenticate();
$accessToken = $client->getAccessToken
//This gives me a JSON-format access-token

步骤3
//Set the access token retrieved in previous request
$client->setAccessToken($accessToken);
//set the refresh token from the JSON response
$client->refreshToken($refreshToken);

现在,最后一部分(refreshToken)给我一个错误:invalid_grant。 我在Stack Overflow和其他互联网上读到,我应该将我的访问类型设置为offline,并将我的批准提示设置为force。但是我认为我已经这样做了(看上面的内容)。
那么出了什么问题? 编辑:我正在阅读Google API本身的源代码。 OAuth类中的sign()方法指定如下:
if ($expired) {
    if (! array_key_exists('refresh_token', $this->accessToken)) {
        throw new apiAuthException("The OAuth 2.0 access token has expired, "
            . "and a refresh token is not available. Refresh tokens are not "
            . "returned for responses that were auto-approved.");
      }
      $this->refreshToken($this->accessToken['refresh_token']);
    }
}

所以实际上不需要调用$client->refreshToken()


看起来像是一个错误信息/代码。当出现这个消息时,请检查供应商的文档并与您的代码进行比较。 - hakre
你说得很对。但是供应商说我应该添加access_type=offline。 我想我已经这样做了。 - Bart Vangeneugden
好的,我没有谈论第三方,我谈论的是供应商。供应商(Google Inc.)对这个错误代码有什么说法? - hakre
该供应商(即 Google Developers)在其有关刷新令牌的文档中没有讨论这个错误。 - Bart Vangeneugden
联系他们的支持团队并报告你缺少信息的问题。 - hakre
2
看看这个问题:https://dev59.com/sGXWa4cB1Zd3GeqPLlHD 似乎你需要从getAccessToken()的响应JSON中获取和存储刷新令牌。 - Jan Gerlinger
2个回答

0

0

为解决收到的错误"invalid_grant",谷歌建议更新服务器时钟,并检查是否达到了API调用的最大限制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接