本教學課程逐步介紹存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應,並輸出結果的必要步驟。本教學課程使用 Core Reporting API 3.0 版、Management API v3.0 和 OAuth2.0。
步驟 1:啟用 Analytics (分析) API
如要開始使用 Google Analytics API,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。
建立用戶端 ID
- 開啟「服務帳戶」頁面。如果出現系統提示,請選取您要使用的專案。
- 按一下 [ 建立服務帳戶],然後輸入服務帳戶的名稱和說明。您可以使用預設的服務帳戶 ID,也可以自行選擇其他不重複的名稱。完成後,請按一下 [建立]。
- 系統會隨即顯示「服務帳戶權限」部分,不過您不一定要設定這些權限。請按一下 [繼續]。
- 在「將這個服務帳戶的存取權授予使用者」畫面中,向下捲動至「建立金鑰」部分。按一下 [ 建立金鑰]。
- 在隨即顯示的側邊面板中選取金鑰格式;建議您選擇 [JSON]。
- 按一下 [建立],接著,系統就會為您產生一對新的公開/私密金鑰,並下載至您的電腦中;這是金鑰的唯一副本,如要瞭解安全儲存的方式,請參閱管理服務帳戶金鑰。
- 在 [已將私密金鑰儲存至您的電腦中] 對話方塊中按一下 [關閉],然後再按一下 [完成],即可返回您的服務帳戶表格。
將服務帳戶新增至 Google Analytics (分析) 帳戶
新建立的服務帳戶將擁有以下電子郵件地址:<projectId>-<uniqueId>@developer.gserviceaccount.com
;請使用這個電子郵件地址來新增使用者,並加入您要透過 API 存取的 Google Analytics (分析) 帳戶。在本教學課程中,您只需要「檢視及分析」權限。
步驟 2:安裝 Google 用戶端程式庫
您可以取得 PHP 適用的 Google API 用戶端程式庫 下載版本或使用 Composer:
composer require google/apiclient:^2.0
步驟 3:設定範例
您必須建立名為 HelloAnalytics.php
的單一檔案,其中包含下方的程式碼範例。
- 將下列原始碼複製或下載至
HelloAnalytics.php
。 - 將先前下載的
service-account-credentials.json
移至與程式碼範例相同的目錄中。
HelloAnalytics.php
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; $analytics = initializeAnalytics(); $profile = getFirstProfileId($analytics); $results = getResults($analytics, $profile); printResults($results); function initializeAnalytics() { // Creates and returns the Analytics Reporting service object. // 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_Analytics($client); return $analytics; } function getFirstProfileId($analytics) { // Get the user's first view (profile) ID. // Get the list of accounts for the authorized user. $accounts = $analytics->management_accounts->listManagementAccounts(); if (count($accounts->getItems()) > 0) { $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); // Get the list of properties for the authorized user. $properties = $analytics->management_webproperties ->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0) { $items = $properties->getItems(); $firstPropertyId = $items[0]->getId(); // Get the list of views (profiles) for the authorized user. $profiles = $analytics->management_profiles ->listManagementProfiles($firstAccountId, $firstPropertyId); if (count($profiles->getItems()) > 0) { $items = $profiles->getItems(); // Return the first view (profile) ID. return $items[0]->getId(); } else { throw new Exception('No views (profiles) found for this user.'); } } else { throw new Exception('No properties found for this user.'); } } else { throw new Exception('No accounts found for this user.'); } } function getResults($analytics, $profileId) { // Calls the Core Reporting API and queries for the number of sessions // for the last seven days. return $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions'); } function printResults($results) { // Parses the response from the Core Reporting API and prints // the profile name and total sessions. if (count($results->getRows()) > 0) { // Get the profile name. $profileName = $results->getProfileInfo()->getProfileName(); // Get the entry for the first entry in the first row. $rows = $results->getRows(); $sessions = $rows[0][0]; // Print the results. print "First view (profile) found: $profileName\n"; print "Total sessions: $sessions\n"; } else { print "No results found.\n"; } }
步驟 4:執行範例
啟用 Analytics API 後, 已安裝 PHP 適用的 Google API 用戶端程式庫, 然後設定可執行範例的原始碼。
使用以下工具執行範例:
php HelloAnalytics.php
完成這些步驟後,範例會輸出授權使用者的第一個 Google Analytics (分析) 資料檢視 (設定檔) 名稱,以及最近七天的工作階段數。
現在,您可以使用已授權的 Analytics (分析) 服務物件,執行 Management API 參考文件中的任何程式碼範例。例如,您可以嘗試變更程式碼,改用 accountSummaries.list 方法。