Analytics Reporting API v4 入门:适用于 Web 应用的 PHP 快速入门

本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。

1. 启用 API

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

注意:要创建网络客户端 ID 或已安装的应用客户端,您需要在同意屏幕中设置一个产品名称。如果您尚未设置,系统会提示您配置同意屏幕

创建凭据

  • 打开“凭据”页面
  • 点击创建凭据并选择 OAuth 客户端 ID
  • 对于应用类型,选择网络应用
  • 将客户端 ID 命名为 quickstart,然后点击创建
  • 将“已获授权的 JavaScript 来源”留空,因为本教程不需要该内容。
  • 已获授权的重定向 URI 设置为 http://localhost:8080/oauth2callback.php
  • 点击创建

“凭据”页面中,点击新创建的客户端 ID,然后点击下载 JSON 并将其保存为 client_secrets.json;在本教程的后面,您将需要用到该 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

当您完成这些步骤后,示例代码就会输出给定数据视图过去 7 天内的会话数。