带有PHP的Google AnalyticsAPI V3返回空白页面

时间:2014-11-14 10:53:49

标签: php google-analytics

我尝试使用Google Analytics Reporting API和Oauth 2.0显示有关我网站的一些基本Google Analytics信息。我一直试图让它工作几个小时,但是徒劳无功。

我已经复制并编辑了this topic中的代码。一切都应该正常工作,但不知何故,当我在浏览器中查看页面时,我只看到一个空白页面。

我有:

  • 在Google API控制台中创建了一个服务帐户。
  • 在Google API控制台中启用了Google AnalyticsAPI。
  • 将服务帐户的电子邮件地址添加到Google Analytics。

代码(' XXXX'表示我已过滤掉个人信息):

<?php

require_once 'google-api/src/Google/Client.php';
require_once 'google-api/src/Google/Service/Analytics.php';

$keyfile = 'XXXX.p12';

// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Application Name');

$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        'XXXX@developer.gserviceaccount.com',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents($keyfile)
    )
);

// Get this from the Google Console, API Access page
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);

// We have finished setting up the connection,
// now get some data and output the number of visits this week.

// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id   = 'XXXX';
$lastWeek       = date('Y-m-d', strtotime('-1 week'));
$today          = date('Y-m-d');

try {
    $results = $analytics->data_ga->get($analytics_id,
                        $lastWeek,
                        $today,'ga:visits');
    echo '<b>Number of visits this week:</b> ';
    echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
    echo 'There was an error : - ' . $e->getMessage();
}

?>

我很长时间以来一直在努力,任何帮助都将不胜感激!

0 个答案:

没有答案