7

我一直在試圖讓Google API在我的網站上工作好幾天,但沒有得到它的工作。在我搜索的任何地方,我都找到了過時的示例......我需要它來處理codeigniter,我想要做的就是從Google Analytics獲取數據,以便在我的codeigniter網站上的管理控制檯中顯示。Codeigniter網站上的Google Analytics API

我明白,我需要一個服務帳戶,如果我不希望被認證,每次我看儀表盤(?)

誰能請幫助我得到這個工作?提前感謝你!

我想要做的是:從谷歌分析獲取數據,返回數據可能是JSON,然後我想我可以用一個插件製作一個圖表(也許一些jQuery插件已經存在,或者我可以使用谷歌自己的圖表抽屜?)並顯示給管理員。我只是想要非常簡單的數據,例如上個月有多少用戶...

+1

我不明白爲什麼有人會低估這一點,因爲更多的人可能有這個問題!我已經嘗試過Sparks for Codeigniter的插件,但那個是兩年前的,這意味着api已經過時了,並且所有在Google網站上的示例中的命名約定都是錯誤的... – Michael 2014-09-04 14:35:56

回答

16

大約一週後 - 當然,在同一天我發佈這個問題,我終於設法自己解決這個問題。

這是我如何去:

我從their github下載了最新的谷歌客戶端API(對於PHP)。

我在我的應用程序/ third_party文件夾中添加了Google文件夾(src)。

在我的控制我包括所需的文件做:

require_once(BASEPATH . '../application/third_party/Google/Client.php'); 
require_once(BASEPATH . '../application/third_party/Google/Service/Analytics.php'); 

然後我在下面,下面的代碼進行授權與服務帳戶(你從Google Console獲取和選擇項目>的API & AUTH >憑據>然後創建一個新的客戶端ID,選擇服務帳戶,完成後,點擊「生成新的P12鍵」和鍵添加到您的THIRD_PARTY /谷歌文件夾:

session_start(); 

$client_id = '<YOUR_CLIENT_ID>'; //Client ID 
$service_account_name = '<YOUR_CLIENT_EMAIL>'; //Email Address 
$key_file_location = BASEPATH . '../application/third_party/Google/<YOUR KEY.p12>'; //key.p12 

$client = new Google_Client(); 
$client->setApplicationName("ApplicationName"); 
$service = new Google_Service_Analytics($client); 

if (isset($_SESSION['service_token'])) { 
    $client->setAccessToken($_SESSION['service_token']); 
} 

$key = file_get_contents($key_file_location); 
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name, 
    array(
     'https://www.googleapis.com/auth/analytics', 
    ), 
    $key, 
    'notasecret' 
); 
$client->setAssertionCredentials($cred); 
if($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion($cred); 
} 
$_SESSION['service_token'] = $client->getAccessToken(); 

下面的代碼是FO從上31天

$analytics = new Google_Service_Analytics($client); 

$profileId = "ga:<YOUR_PROFILE_ID>"; 
$startDate = date('Y-m-d', strtotime('-31 days')); // 31 days from now 
$endDate = date('Y-m-d'); // todays date 

$metrics = "ga:sessions"; 

$optParams = array("dimensions" => "ga:date"); 
$results = $analytics->data_ga->get($profileId, $startDate, $endDate, $metrics, $optParams); 

$data['report'] = $results->rows; //To send it to the view later 

[R越來越會話(頁面訪問量)要獲得所有可以使用的維度和指標,use this link。關於如何將其發送到視圖 實施例:

$this->view->load('your_view', $data); 

要寫入它作爲我只是用Google charts一個圖表,在JS(在視圖中)我剛剛從$循環數據的數據[「報告」 ]繪製圖表。

希望這將有助於未來這個問題的人。

+1

感謝您的代碼...我和你的qs一樣。你的回答顯示了我的一切開始結束:) – Penny 2015-01-28 14:29:21

+0

這真的很有幫助,謝謝!不幸的是,我收到了錯誤消息「(403)用戶沒有任何Google Analytics帳戶。」...這是你偶然發現的嗎? – 2015-07-10 15:34:23

+0

不,對不起,我沒有這個問題。 – Michael 2015-08-24 08:42:07

相關問題