本教學課程將逐步說明存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應及輸出結果的必要步驟。本教學課程使用 Core Reporting API v3.0、Management API v3.0 和 OAuth2.0。
步驟 1:啟用 Analytics API
如要開始使用 Google Analytics (分析) API,請先使用設定工具,這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。
建立用戶端 ID
在「Credentials」(憑證) 頁面:
- 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」。
- 針對「應用程式類型」選取「網頁應用程式」。
- 為憑證命名。
- 將「AUTHORIZED JAVAscript ORIGINS」留空,本教學課程不需要。
- 將「授權重新導向 URI」設為 http://localhost:8080/oauth2callback.php
- 點選「建立」。
選取您剛建立的憑證,然後按一下「下載 JSON」。將下載的檔案儲存為 client_secrets.json
,稍後在教學課程中會用到。
步驟 2:安裝 Google 用戶端程式庫
您可以取得 PHP 適用的 Google API 用戶端程式庫 下載版本或使用 Composer:
composer require google/apiclient:^2.0
步驟 3:設定範例
您必須建立兩個檔案:
index.php
會成為使用者造訪的主網頁。oauth2callback.php
會處理 OAuth 2.0 回應。
index.php
這個檔案包含查詢 Google Analytics (分析) API 並顯示結果的主要邏輯。將第一個程式碼範例複製或下載至 index.php
。
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; // Start a session to persist credentials. session_start(); // Create the client object and set the authorization configuration // from the client_secretes.json you downloaded from the developer console. $client = new Google_Client(); $client->setAuthConfig(__DIR__ . '/client_secrets.json'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // If the user has already authorized this app then get an access token // else redirect to ask the user to authorize access to Google Analytics. if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { // Set the access token on the client. $client->setAccessToken($_SESSION['access_token']); // Create an authorized analytics service object. $analytics = new Google_Service_Analytics($client); // Get the first view (profile) id for the authorized user. $profile = getFirstProfileId($analytics); // Get the results from the Core Reporting API and print the results. $results = getResults($analytics, $profile); printResults($results); } else { $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } 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 "<p>First view (profile) found: $profileName</p>"; print "<p>Total sessions: $sessions</p>"; } else { print "<p>No results found.</p>"; } } ?>
oauth2callback.php
這個檔案會處理
OAuth 2.0 回應。將第二個程式碼範例複製或
下載至 oauth2callback.php
。
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; // Start a session to persist credentials. session_start(); // Create the client object and set the authorization configuration // from the client_secrets.json you downloaded from the Developers Console. $client = new Google_Client(); $client->setAuthConfig(__DIR__ . '/client_secrets.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // Handle authorization flow from the server. if (! isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); }
步驟 4:執行範例
啟用 Analytics API 之後,請安裝 PHP 適用的 Google API 用戶端程式庫,並設定可以執行的程式碼範例。
使用設定為提供 PHP 的網路伺服器執行範例。如果您使用 PHP 5.4 以上版本,可以執行下列指令,使用 PHP 的內建測試網路伺服器:
php -S localhost:8080 /path/to/sample
然後透過瀏覽器造訪 http://localhost:8080。
完成這些步驟後,範例會輸出授權使用者第一個 Google Analytics (分析) 資料檢視 (設定檔) 的名稱,以及過去七天的工作階段數量。
有了已授權的 Analytics (分析) 服務物件,您現在可以執行 Management API 參考文件中列出的任何程式碼範例。舉例來說,您可以嘗試將程式碼變更為使用 accountSummaries.list 方法。