Hello Analytics API:服務帳戶的 PHP 快速入門導覽課程

本教學課程將逐步說明存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應及輸出結果的必要步驟。本教學課程使用 Core Reporting API v3.0Management API v3.0OAuth2.0

步驟 1:啟用 Analytics API

如要開始使用 Google Analytics (分析) API,請先使用設定工具,這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

建立用戶端 ID

  1. 開啟「服務帳戶」頁面。如果出現系統提示,請選取您要使用的專案。
  2. 按一下 [ 建立服務帳戶],然後輸入服務帳戶的名稱和說明。您可以使用預設的服務帳戶 ID,也可以自行選擇其他不重複的名稱。完成後,請按一下 [建立]
  3. 系統會隨即顯示「服務帳戶權限」部分,不過您不一定要設定這些權限。請按一下 [繼續]。
  4. 在「將這個服務帳戶的存取權授予使用者」畫面中,向下捲動至「建立金鑰」部分。按一下 [ 建立金鑰]
  5. 在隨即顯示的側邊面板中選取金鑰格式;建議您選擇 [JSON]
  6. 按一下 [建立],接著,系統就會為您產生一對新的公開/私密金鑰,並下載至您的電腦中;這是金鑰的唯一副本,如要瞭解安全儲存的方式,請參閱管理服務帳戶金鑰
  7. 在 [已將私密金鑰儲存至您的電腦中] 對話方塊中按一下 [關閉],然後再按一下 [完成],即可返回您的服務帳戶表格。

在 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 的單一檔案,其中包含下方的程式碼範例。

  1. 將下列原始碼複製或下載HelloAnalytics.php
  2. 將先前下載的 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 方法。