Google API客户端刷新OAuth2令牌

时间:2015-10-11 10:26:18

标签: php oauth-2.0 google-analytics-api

我使用Google API检索分析数据并将其显示在我的网站上。它工作正常一个月,但过去四天我收到此错误:

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

以下是代码:

<?php
require_once ('src/Google/autoload.php');
$client = new Google_Client();
$client->setApplicationName( 'GAFetchData' );

$client->setAssertionCredentials(
  new Google_Auth_AssertionCredentials( 
    // Google client ID email address
    'xxxxx-xxxxxxxxxx@developer.gserviceaccount.com',
    array('https://www.googleapis.com/auth/analytics.readonly'),

    file_get_contents( $Path.'gapii/'.'GAFetchData-xxxxxxxx.p12' )
  )
);

$client->setClientId( 'xxxxx-xxxxxxxxxx.apps.googleusercontent.com' );
$client->setAccessType( 'offline_access' );  
$analytics = new Google_Service_Analytics( $client );
$analytics_id = 'ga:xxxxxx';

try {
  $optParams = array();
  $metrics    = 'ga:pageviews';
  $start_date = '7daysAgo';
  $end_date   = 'today';

   $optParams['dimensions']  = 'ga:pagePath';
   $optParams['filters']      = 'ga:pagePath!@=rech;';           
   $optParams['max-results'] = '10000';

  $result = $analytics->data_ga->get( $analytics_id, $start_date, $end_date, $metrics, $optParams);

  if( $result->getRows() ) { $items = $result->getRows(); }
} 
catch(Exception $e) { echo $e->getMessage();} 
?>

1 个答案:

答案 0 :(得分:0)

问题解决了!

这是由服务器的时钟引起的,我只是使用以下命令(在我的情况下是Ubuntu)与NTP服务器同步:

sudo ntpdate 3.pool.ntp.org

您可以从中找到时间服务器列表 public NTP time server list

希望有所帮助!