php - 使用 GoogleAPI 的 OAuth 给出 'invalid_grant'

标签 php oauth-2.0

我正在用 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/

相关文章:

php - 使用 php 进行数据库备份的 mysqldump 不起作用

go - 如何将自定义客户端传递给 Golang oauth2.Exchange

oauth-2.0 - "Resource Owner Password Flow"和 "Client Credentials Flow"之间的区别

angular - 如何使用正确的 header 使用 Angular 6 发送 OAuth2 POST 请求?

oauth-2.0 - 如何在 WPF 中使用 CEFSharp 浏览器登录 Google?

php - Laravel 5.1 PHPUnit 使用 JSON 测试 API

php - 如何在功能测试中模拟 Symfony 2 服务?

javascript - 如何通过 PHP post 请求获取 JavaScript 变量?

php - 如何将 CSS 类添加到 PHP 行?

oauth - 如何在 postman 收藏中保留OAuth2 token (或使用刷新 token )?