php - 服务帐户的 Google Analytics API oauth 异常 "invalid_grant"。两台服务器上的相同代码。只有一个有效

标签 php api exception oauth google-analytics-api

我正在通过服务帐户查询 Analytics API。

我已经在开发服务器上编写了代码,它可以正常运行。 在生产服务器上运行相同的代码时,它会抛出:

Google_AuthException: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

我试过创建另一个服务帐户,行为是一样的。

oAuth IETF 草案 ( https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-31 ) 是这样描述错误的:

     invalid_grant
           The provided authorization grant (e.g. authorization
           code, resource owner credentials) or refresh token is
           invalid, expired, revoked, does not match the redirection
           URI used in the authorization request, or was issued to
           another client.

这是我写的代码:

$GA_CLIENT_ID = 'XX.apps.googleusercontent.com';
$GA_APP_EMAIL = 'XX@developer.gserviceaccount.com';
$GA_APP_NAME = 'XX';
$GA_KEY_FILE = 'XX';

// create client object and set app name
$client = new Google_Client();
$client->setApplicationName($GA_APP_NAME); // name of your app

// set assertion credentials
$client->setAssertionCredentials(
        new Google_AssertionCredentials(
            $GA_APP_EMAIL, // email you added to GA
            array('https://www.googleapis.com/auth/analytics.readonly'),
            file_get_contents($GA_KEY_FILE)  // keyfile you downloaded
            ));

// other settings
$client->setClientId($GA_CLIENT_ID);           // from API console
$client->setAccessType('offline_access');  // this may be unnecessary?

// create service and get data
$service = new Google_AnalyticsService($client);
$result = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
return $result;

我还尝试过这里 ( https://groups.google.com/forum/?fromgroups#!topic/gs-discussion/3y_2XVE2q7U%5B1-25%5D ) 使用 authenticatedRequest() 而不是 Google_AnalyticsService 推荐的解决方案:

$req = new Google_HttpRequest($apiUrl);
$resp = $client::getIo()->authenticatedRequest($req);
$result = json_decode($resp->getResponseBody(), true);

此替代方案也适用于开发服务器,但不适用于生产服务器。

我对这个一窍不通。有没有人看到这个/修复它?

谢谢!

最佳答案

显然问题是系统时间不对。通过 NTP 同步工作:

sudo ntpdate npt.ubuntu.com

sudo ntpdate pool.ntp.org

编辑

正如@RafaSashi 在下面建议的那样,pool.ntp.org 服务器更可靠。使用它而不是 ntp.ubuntu.com (这是我尝试的第一个可用的,因此是最初的选择)

关于php - 服务帐户的 Google Analytics API oauth 异常 "invalid_grant"。两台服务器上的相同代码。只有一个有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11973162/

相关文章:

php - 尝试动态填充选择列表时的 Json 结果 "undefined"

php - 表单功能注册不插入数据库

exception - listener.d : crashes upon unclean disconnect

c# - 由 MS Excel 和 COM 托管的 C#2 中的委托(delegate)中的异常行为

java - ClassNotFoundException 错误。 Eclipse IDE 出现问题

php salt 我每个用户的密码 sha512 - 我这样做对吗?

php - 非静态方法 Redis::get() 不能在 laravel 5.4 中静态调用?

php - 如何使用 paypal API 在美国和英国以外直接进行信用卡支付

java - 如何使用 Flickrj api 向 Flickr 发送简单的 ping 测试

c# - 编程语言/库如何与硬件通信?