0
我正尝试使用服务帐户访问我的Google Analytics数据。我在Developers Console中创建了一个,并且在同一个控制台中启用了Google Analytics API,但不知何故,我无法从API中获取数据。使用服务帐户访问Google Analytics API不起作用
我在this page上使用了脚本。
我的代码如下:
<?php
$keyfile = 'google/key.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('MyNAME');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'[email protected]', array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($keyfile)
)
);
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
$analytics_id = 'ga:UA-XXXXXX-1'; // http://productforums.google.com/forum/#!topic/analytics/dRuAr1K4waI
// get data for the last 2 weeks
$lastWeek = date('Y-m-d', strtotime('-2 week'));
$today = date('Y-m-d');
// Test connection
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();
}
?>
注:如果它说:“XXXX”,这意味着我已经字符串用于安全目的的去除的部分;正确的字符串在我的实际脚本中。
它应该显示用户数量或错误,但我只是得到一个空白屏幕。我确定密钥文件的URL是正确的。
有没有人有如何解决这个问题的建议?这将非常感激。