在進入Reporting API 前,先來搞清楚他到底是甚麼東西?

文長可略.....
在我研究如何取出我想要的GA data時,我先找到的頁面是這個
裡面介紹了如何設定GA,還有不同用途的API等,後來當我搞清楚我要用的是Core Reporting API後,
當然是開始研究它要怎麼用,目前官方第一推薦是 Reporting API v4,所以我就非常努力看文件,看了半天,我還是看不懂到底該如何用它,加上google系統與功能龐大又多元,點來點去常常是迷路收場...
後來我又想去網路上搜尋網友的介紹與範例,看能不能有所突破,不過找著找著覺得,奇怪,怎麼有個東西跟他很像,但是卻不一樣哩?
那東西就是 Reporting API v3 !!!

其實它就是Reporting API的上一個版本,目前網路上大部分文章都是v3的版本,那v3跟v4的差別在哪呢?
1. 據官方說法,v4比v3多了更多功能,至於多了哪些,其實我也不是很清楚 噗.....,不過有興趣還是可以去它們的Overview看一下
2. HTTP的方法與回應的內容結構也改了很多,v3的版本可直接利用HTTP Get,就可以取得資料,v4則需要利用POST ,Content-Type帶application/json才能取得資料,如果你想從v3升級成v4,可以參考此官方文件

看到這裡,還在用v3的朋友是否會擔心, 哪天舊版API 會不會被遺棄?
目前還不用太擔心,google 還是有在維護v3版本,只不過,之後有任何的新功能,都只會在v4版本開發。

所以廢話這麼多,今天要說的當然是Reporting API v4的版本,改天有空時,再來補一下v3版本。

呼...終於要進入主題了.....


在開始動手前,首先,我們必須要先處google理權限的問題。

當你寫google API時,一定都會遇到這個問題,在你向API get資料時,我們常常會看到跟下圖類似的狀況。


這就是代表你沒有access的權限去取得API資料,此時你就需要透過OAuth2.0去取得權限。

要如何取得 access權限呢?

Google 官方文件提供很多語言與方法,包含Java、Python等,文件敘述非常詳盡,還附有Sample Code,簡直太方便了。

但我今天只用PHP來做介紹。
官網上,提供了Service ApplicationsWeb Server Applications兩種方式,
這篇介紹的是利用Service Applications的方式存取得資料。


STEP 1
申請 Google Developer Console

到Google Developer Console申請一個帳號,並建立一個專案。

STEP 2
啟用APIAnalytics APIGoogle Analytics Reporting API


STEP 3
建立服務帳號憑證

至憑證頁面,建立一個服務帳號金鑰

選取服務帳號,沒有服務帳號就建一個,金鑰類型選擇JSON
建立完成後,它會直接幫你下載JSON憑據的檔案,請存在你的專案路徑下,待會認證時會到它。

如果一時失手,沒存到。你可以回到憑證頁面,點選管理帳戶
點選查看用戶, 就可以重新下載憑證了。
STEP 4
新增服務E-Mail帳號權限

點選管理帳戶,複製服務帳號ID
至GA管理員頁面,點選使用者管理, 將剛剛複製的服務帳號ID,貼在框框的欄位裡,並賦予權限。


STEP 5
安裝 Google APIs Client PHP Library

建立或是打開一個專案資料夾(專案需要在伺服器連線路徑下),在這個路徑下開terminal並輸入。
composer require google/apiclient:^2.0

STEP 6
建立測試資料夾與檔案

1. 建立一個 HelloAnalytics.php 檔案,將以下程式碼貼進檔案裡。
2. 將 service-account-credentials.json 換成剛剛下載的JSON金鑰檔案。
3. 置換成你的VIEW_ID,若你不知道你的VIEW_ID可以去Account Explorer取得。
php

// Load the Google API PHP Client Library.
require_once __DIR__
. '/vendor/autoload.php';

$analytics
= initializeAnalytics();
$response
= getReport($analytics);
printResults
($response);


/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
*/

function initializeAnalytics()
{

// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION
= __DIR__ . '/service-account-credentials.json';

// Create and configure a new client object.
$client
= new Google_Client();
$client
->setApplicationName("Hello Analytics Reporting");
$client
->setAuthConfig($KEY_FILE_LOCATION);
$client
->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics
= new Google_Service_AnalyticsReporting($client);

return $analytics;
}


/**
* Queries the Analytics Reporting API V4.
*
* @param service An authorized Analytics Reporting API V4 service object.
* @return The Analytics Reporting API V4 response.
*/

function getReport($analytics) {

// Replace with your view ID, for example XXXX.
$VIEW_ID
= "";

// Create the DateRange object.
$dateRange
= new Google_Service_AnalyticsReporting_DateRange();
$dateRange
->setStartDate("7daysAgo");
$dateRange
->setEndDate("today");

// Create the Metrics object.
$sessions
= new Google_Service_AnalyticsReporting_Metric();
$sessions
->setExpression("ga:sessions");
$sessions
->setAlias("sessions");

// Create the ReportRequest object.
$request
= new Google_Service_AnalyticsReporting_ReportRequest();
$request
->setViewId($VIEW_ID);
$request
->setDateRanges($dateRange);
$request
->setMetrics(array($sessions));

$body
= new Google_Service_AnalyticsReporting_GetReportsRequest();
$body
->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}


/**
* Parses and prints the Analytics Reporting API V4 response.
*
* @param An Analytics Reporting API V4 response.
*/

function printResults($reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report
= $reports[ $reportIndex ];
$header
= $report->getColumnHeader();
$dimensionHeaders
= $header->getDimensions();
$metricHeaders
= $header->getMetricHeader()->getMetricHeaderEntries();
$rows
= $report->getData()->getRows();

for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row
= $rows[ $rowIndex ];
$dimensions
= $row->getDimensions();
$metrics
= $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}

for ($j = 0; $j < count($metrics); $j++) {
$values
= $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry
= $metricHeaders[$k];
print($entry->getName() . ": " . $values[$k] . "\n");
}
}
}
}
}
STEP 6
測試它吧!!!

打開輸入專案在伺服器下的路徑
EX:
localhost:8080/myProject/HelloAnalytics.php
成功的話便會在畫面上顯示回傳結果。


參考資料