本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。
1. 启用 API
要开始使用 Analytics Reporting API V4,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目、启用 API 以及创建凭据。
创建凭据
- 打开服务帐号页面。如果看到提示,请选择项目。
- 点击 创建服务帐号,并输入服务帐号的名称和说明。您可以使用默认服务帐号 ID,也可以选择其他唯一的帐号 ID。完成后,点击创建。
- 后面的服务帐号权限(可选)部分无需设置。点击继续。
- 在向用户授予访问此服务帐号的权限屏幕上,向下滚动到创建密钥部分。点击 创建密钥。
- 在随即显示的侧面板中,选择密钥的格式:建议使用 JSON。
- 点击创建。您的新公钥/私钥对随后会生成并下载到您的计算机上;该密钥仅此一份。要了解如何安全地存储密钥,请参阅管理服务帐号密钥。
- 点击私钥已保存到您的计算机对话框中的关闭,然后点击完成以返回服务帐号表格。
将服务帐号添加到 Google Analytics(分析)帐号
新创建的服务帐号将拥有一个类似以下所示的电子邮件地址:
quickstart@PROJECT-ID.iam.gserviceaccount.com
使用此电子邮件地址将用户添加到要通过 API 访问的 Google Analytics(分析)数据视图。在本教程中,仅需要读取和分析权限。
2. 安装客户端库
您可以使用 Composer 获取适用于 PHP 的 Google API 客户端库:
composer require google/apiclient:^2.0
3. 设置示例
您需要创建一个名为 HelloAnalytics.php
的单个文件,其中将包含以下示例代码。
- 将以下源代码复制或下载到
HelloAnalytics.php
中。 - 将之前下载的
service-account-credentials.json
移到示例代码所在的目录中。 - 替换
VIEW_ID
的值。您可以使用帐号浏览器找到数据视图 ID。
HelloAnalytics.php
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; $analytics = initializeAnalytics(); $response = getReport($analytics); printResults($response); /** * Initializes an Analytics Reporting API V4 service object. * * @return An authorized Analytics Reporting API V4 service object. */ function initializeAnalytics() { // 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_AnalyticsReporting($client); return $analytics; } /** * 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"); } } } } }
4. 运行示例
使用以下文件运行示例应用:
php HelloAnalytics.php
当您完成这些步骤后,示例代码就会输出给定数据视图过去 7 天内的会话数。