本教程详细介绍了访问 Google Analytics(分析)账号、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0、Management API v3.0 和 OAuth2.0。
第 1 步:启用 Google Analytics(分析)API
要开始使用 Google Analytics(分析)API,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目,启用 API 以及创建凭据。
创建客户端 ID
- 打开服务账号页面。如果看到提示,请选择项目。
- 点击 创建服务账号,并输入服务账号的名称和说明。您可以使用默认服务账号 ID,也可以选择其他唯一的账号 ID。完成后,点击创建。
- 后面的服务账号权限(可选)部分无需设置。点击继续。
- 在向用户授予访问此服务账号的权限屏幕上,向下滚动到创建密钥部分。点击 创建密钥。
- 在随即显示的侧面板中,选择密钥的格式:建议使用 JSON。
- 点击创建。您的新公钥/私钥对随后会生成并下载到您的计算机上;该密钥仅此一份。要了解如何安全地存储密钥,请参阅管理服务账号密钥。
- 点击私钥已保存到您的计算机对话框中的关闭,然后点击完成以返回服务账号表格。
将服务账号添加到 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
的文件,其中将包含以下示例代码。
- 将以下源代码复制或下载到
HelloAnalytics.php
。 - 将之前下载的
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 方法。