Google Analytics(分析)API 入门:适用于服务帐号的 PHP 快速入门

本教程详细介绍了访问 Google Analytics(分析)帐号、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0Management API v3.0OAuth2.0

第 1 步:启用 Google Analytics(分析)API

要开始使用 Google Analytics(分析)API,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目,启用 API 以及创建凭据。

创建客户端 ID

  1. 打开服务帐号。如果看到相关提示,请选择项目。
  2. 点击创建服务帐号
  3. 创建服务帐号窗口中,键入服务帐号的名称,然后选择提供新的私钥。如果您希望将 Google Workspace 全网域权限授予该服务帐号,另请选中启用 Google Workspace 全网域委派功能。然后点击保存

您的新公钥/私钥对已生成并下载到您的计算机;该密钥仅此一份,您负责安全存储该密钥

将服务帐号添加到 Google Analytics(分析)帐号中

新建服务帐户的电子邮件地址为 &ltprojectId&gt-&ltuniqueId&gt@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 步:运行示例代码

在您启用了 Google Analytics(分析)API、安装了适用于 PHP 的 Google API 客户端库并设置了示例源代码后,该示例代码就可以运行了。

使用以下文件运行示例代码:

php HelloAnalytics.php

当您完成上述步骤后,示例代码就会输出已获授权用户的首个 Google Analytics(分析)数据视图(配置文件)的名称以及过去 7 天内的会话数。

现在,借助已授权的 Google Analytics(分析)服务对象,您可以运行 Management API 参考文档中的任何代码示例。例如,您可以尝试更改代码来使用 accountSummaries.list 方法。