2014-09-29 172 views
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是正確的。

有沒有人有如何解決這個問題的建議?這將非常感激。

回答

0

看起來您正在使用您的媒體資源ID(UA-XXXXX-1)來代替您的視圖(個人資料)ID。如果你去Google Analytics Query Explorer它可以很容易地看到你的實際ga:XXXX視圖(配置文件)ID是什麼。任何給定的屬性都可以有多個視圖(配置文件)。 This reference guide給出了這個請求需要的參數的很好的描述。