本教學課程將逐步介紹存取 Analytics (分析) Reporting API v4 的必要步驟。
1. 啟用 API
如要開始使用 Analytics Reporting API v4,請先使用設定工具。這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。
建立憑證
- 開啟「服務帳戶」頁面。如果出現系統提示,請選取您要使用的專案。
- 按一下 [ 建立服務帳戶],然後輸入服務帳戶的名稱和說明。您可以使用預設的服務帳戶 ID,也可以自行選擇其他不重複的名稱。完成後,請按一下 [建立]。
- 系統會隨即顯示「服務帳戶權限」部分,不過您不一定要設定這些權限。請按一下 [繼續]。
- 在「將這個服務帳戶的存取權授予使用者」畫面中,向下捲動至「建立金鑰」部分。按一下 [ 建立金鑰]。
- 在隨即顯示的側邊面板中選取金鑰格式;建議您選擇 [JSON]。
- 按一下 [建立],接著,系統就會為您產生一對新的公開/私密金鑰,並下載至您的電腦中;這是金鑰的唯一副本,如要瞭解安全儲存的方式,請參閱管理服務帳戶金鑰。
- 在 [已將私密金鑰儲存至您的電腦中] 對話方塊中按一下 [關閉],然後再按一下 [完成],即可返回您的服務帳戶表格。
將服務帳戶新增至 Google Analytics (分析) 帳戶
新建立的服務帳戶會具備類似這樣的電子郵件地址:
quickstart@PROJECT-ID.iam.gserviceaccount.com
使用此電子郵件地址,新增使用者至您要透過 API 存取的 Google Analytics (分析) 資料檢視。在本教學課程中,您只需要「檢視及分析」權限。
2. 安裝用戶端程式庫
您可以使用 Composer 取得 PHP 適用的 Google API 用戶端程式庫:
composer require google/apiclient:^2.0
3. 設定範例
您需要建立名為 HelloAnalytics.php
的單一檔案,其中含有下方的程式碼範例。
- 複製或下載下列原始碼至
HelloAnalytics.php
。 - 將先前下載的
service-account-credentials.json
移至與程式碼範例相同的目錄。 - 取代
VIEW_ID
的值。您可以使用帳戶多層檢視找出資料檢視 ID。
HelloAnalytics.php
<?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 = "<REPLACE_WITH_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"); } } } } }
4. 執行範例
使用下列指令執行範例:
php HelloAnalytics.php
完成這些步驟後,範例會輸出最近七天內的指定資料檢視數量。