php - 使用 PHP 连接到 Google Analytics API

标签 php google-analytics google-api google-api-php-client

我正在尝试用 PHP 编写一个代码,它将连接到我的 Google Analytics 帐户,从那里提取数据,然后我需要在代码上处理它 - 插入 SQL 表等。

这是我下载的文件夹:https://github.com/google/google-api-php-client/releases (google-api-php-client-2.0.2.zip)

我使用了这个谷歌指南:https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php
这实际上是用于通过 URL 访问 API,所以我做了一些调整,以便在本地处理数据(例如刷新 token 等)。

这是我的代码:

<?php

define ("API_Key","MY_API_KEY");
define ("oAuth_Key","MY_oAUTH_KEY");

define ("refreshTokenKey","MY_REFRESH_TOKEN");
define('STORE_ON_DISK', true, true);

// Load the Google API PHP Client Library.
require_once dirname(__FILE__) . '/../Analytics/google-api-php-client-2.0.2/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("PrsstoAnalytics");
$client->setAuthConfigFile(dirname(__FILE__) . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');

$client->refreshToken(refreshTokenKey);


//----------------------------------------------------------------------------------------------------------------------
// 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);

function getReport(&$analytics) {

    // Replace with your view ID. E.g., XXXX.
    $VIEW_ID = "MY_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 );
}

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( $metricHeaders ) && $j < count( $metrics ); $j++) {
                $entry = $metricHeaders[$j];
                $values = $metrics[$j];
                print("Metric type: " . $entry->getType() . "\n" );
                for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
                    $value = $values->getValues()[ $valueIndex ];
                    print($entry->getName() . ": " . $value . "\n");
                }
            }
        }
    }
}

但是我测试了脚本,这是我得到的错误:
enter image description here

有谁知道为什么我不能连接到 API?

我在连接中做错了什么?我的凭据不正确吗?
我错过了某种 key 吗?
我真的很感激任何帮助。

谢谢!

最佳答案

我自己一直在研究这个。我必须进入 API 管理器(https://console.developers.google.com/apis),创建一个项目,创建一个服务帐户(这是用于构建这样的后端分析服务的帐户),并生成凭据。这将为您提供一个 .json 文件,您需要在代码中链接到该文件:$client->setAuthConfigFile(dirname(__FILE__) . '/{you-credential-file}.json');
在该凭据文件中,您将在 json 字段“client_email”中找到服务帐户电子邮件地址。您需要访问 analytics.google.com 并转到“管理员”以添加具有读取和分析权限的地址。

您还需要替换行 $VIEW_ID = "MY_VIEW_ID";使用您的 View ID。我在 https://ga-dev-tools.appspot.com/account-explorer/ 找到了我的

这足以让我最终启动并运行客户端库和 HelloAnalytics 示例。我对此并不积极,但如果您正在编写查询 GA 的后端服务,则不需要使用 OAuth。

关于php - 使用 PHP 连接到 Google Analytics API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38766991/

相关文章:

php - Magento 1.9 Helper 找不到错误

php - 仅针对登录用户的大型 POST 传输?

javascript - HTML 多选提交在已添加值时中断

Android 谷歌分析跟踪器 NoClassdefFoundError

javascript - 跨现代浏览器有条件地定义函数?特别是 Safari ?

php - preg_match 在搜索转义引号时返回 null

javascript - Google Analytics - 跟踪 Firefox 插件中的事件

android - Android 应用程序上的 Urlshortener 和 403 错误

google-api - 谷歌类 API 补丁

android - Android 中带有 Google API 的依赖性 apache HTTP 客户端