【问题标题】:Google API for analytics invalid grant but works sometimes用于分析的 Google API 授权无效,但有时有效
【发布时间】:2013-02-13 09:35:13
【问题描述】:

我已经解决这个问题 2 天了,并尝试在 google code 和 stackoverflow 下查找,但仍然可以找到答案。

我的问题是当我尝试使用我的谷歌分析 api 时,我收到“刷新 OAuth2 令牌时出错,消息:'{“error”:“invalid_grant”}'”

但奇怪的是,有时它会起作用。很少,但如果我刷新并继续尝试,它会输出。

我唯一能找到的是它可能是the refresh token limit has been exceeded

如果有人可以帮助我或指出正确的方向,请附上我的代码。

谢谢!

<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';


$keyFile = 'key.p12';


$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
   $client->setAccessToken($_SESSION['token']);
   }
 $client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
 );
 $client->setClientId(GOOGLE_CLIENT_ID);
 $client->setAccessType('offline');
 $client->setUseObjects(true);
 $service = new Google_AnalyticsService($client);
 try {
     $results = $service->data_ga->get(
    'ga:44444444',
    date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-    d'))))),
    date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
    'ga:visits,ga:newVisits',
    /*array(
        'dimensions' => 'ga:source,ga:keyword',
        'sort' => '-ga:visits,ga:keyword',
        'filters' => 'ga:medium==organic',
        'max-results' => '25'
    )*/
    array('dimensions' => 'ga:date')
  );
 } catch (Google_ServiceException $e) {
 // echo $e->getMessage();
  }
 if ($client->getAccessToken()) {
    $_SESSION['token'] = $client->getAccessToken();
   }

   $dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
  $dateParseReplacement = 'Date.parse("$1 UTC")';
  $allVisitsItems = array();
  $newVisitorsItems = array();
 if ($results && count($results->getRows()) > 0) {
    foreach ($results->getRows() as $row) {
    $date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
    $allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
    $newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
  header('Content-Type: application/json');
 ?>

<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>

编辑 - 这不是 NTP,当我回显 date('l jS \of F Y h:i:s A');它匹配。

【问题讨论】:

    标签: json google-analytics


    【解决方案1】:

    以下工作可生成输出 - 确保您运行的是 PHP 5.3 或更高版本。

    <?php
    require_once './src/Google_Client.php';
    require_once './src/contrib/Google_AnalyticsService.php';
    
     $path_to_keyfile = '.p12';
     $service_account_email = '7@developer.gserviceaccount.com';
     $client_id = '7.apps.googleusercontent.com';
     $analytics_profile_id = 'ga:IN URL OF ANALYTICS';
    
     $client = new Google_Client();
     $client->setApplicationName("API TEST");
     $client->setAssertionCredentials(
    new Google_AssertionCredentials(
        $service_account_email,
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents($path_to_keyfile)
    )
    );
    $client->setClientId($client_id);
    $client->setAccessType('offline_access');
    
    $service = new Google_AnalyticsService($client);
    
     $from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
     $to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
    
      $dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
      $dateParseReplacement = 'Date.parse("$1 UTC")';
       $allVisitsItems = array();
      $newVisitorsItems = array();
    
    try {
    $data = $service->data_ga->get(
        //
        $analytics_profile_id,
        $from,
        $to,
        'ga:visits,ga:newVisits',
        array('dimensions' => 'ga:date')
    );
    
    if($data && $data['totalResults'] > 0) {
        foreach($data['rows'] as $row) {
            $date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
            $allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
            $newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
        }
    }
    
    header('Content-Type: application/json');
    ?>
    
    <?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
    
    <?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
    
    <?php
     } catch(Exception $e) {
    echo 'There was an error : - ' . $e->getMessage();
     }
    

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 2015-01-19
      • 2015-07-17
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      相关资源
      最近更新 更多