我正在用 PHP 创建一个使用 Google Analytics 报告 API 的内部应用程序。 该应用程序将始终使用相同的 Google 帐户连接到 Analytics,因此我只想在我的数据库中保留访问 token 和刷新 token 。
我使用了以下 Google tutorial设置 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");
第一步
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。
我在 SO 和其他互联网上阅读过,我应该将我的访问类型设置为 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()
最佳答案
为了解决收到的错误 “invalid_grant”,谷歌建议更新您的服务器时钟,检查您是否达到了 api 调用的最大值。
关于php - 使用 GoogleAPI 的 OAuth 给出 'invalid_grant',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11451444/