歡迎使用 Analytics Reporting API v4;網頁應用程式的 PHP 快速入門導覽課程

本教學課程將逐步介紹存取 Analytics (分析) Reporting API v4 的必要步驟。

1. 啟用 API

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

注意:您必須在同意畫面中設定產品名稱,才能建立網路用戶端 ID 或已安裝的應用程式用戶端。如果尚未設定,系統會提示你設定同意畫面

建立憑證

  • 開啟「Credentials」(憑證) 頁面
  • 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
  • 在「應用程式類型」部分,選取「網頁應用程式」
  • 將用戶端 ID 命名為 quickstart,然後點選「Create」(建立)
  • 將「已授權的 JavaScript 來源」留空,但本教學課程不需要。
  • 將「Authorized redirect URIs」(已授權的重新導向 URI) 設為 http://localhost:8080/oauth2callback.php
  • 點選「建立」

在「憑證」頁面中,按一下新建立的用戶端 ID,然後點選「下載 JSON」,並將其儲存為 client_secrets.json;後續步驟將會用到。

2. 安裝用戶端程式庫

您可以使用 Composer 取得 PHP 適用的 Google API 用戶端程式庫

composer require google/apiclient:^2.0

3. 設定範例

您需要建立兩個檔案:

  • index.php 是使用者造訪的主網頁。
  • oauth2callback.php 會處理 OAuth 2.0 回應

index.php

這個檔案包含查詢 Google Analytics (分析) API 及顯示結果的主要邏輯。

  • 將第一個程式碼範例複製或下載index.php
  • 取代 VIEW_ID 的值。您可以使用帳戶多層檢視找出資料檢視 ID。
<?php

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

session_start();

$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_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.
  printResults($response);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


/**
 * 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");
        }
      }
    }
  }
}


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. 執行範例

在設定為提供 PHP 的網路伺服器執行範例。如果您使用 PHP 5.4 以上版本,可以執行下列指令,使用 PHP 的內建測試網路伺服器:

php -S localhost:8080 -t /path/to/sample

然後透過瀏覽器造訪 http://localhost:8080

完成這些步驟後,範例會輸出最近七天內的指定資料檢視數量。