使用 PHP 从 Google Analytics API 获取事件数据

Get events data from Google Analytics API with PHP

我想获取我的其中一个使用 Google Analytics 的应用程序的事件。 我对 the official documentation 中给出的例子有点困惑。我让它工作,但我不明白如何在我的案例中使用它。

require_once 'GA/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('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_Analytics($client);

在这段代码之后我想获取事件数据 - 我应该如何指定计数器 ID 和事件信息?

使用查询资源管理器我设法创建了我需要的查询:

googleapis.com/analytics/v3/data/ga?ids=ga%3A111111&start-date=30daysAgo&end-date=2016-05-11&metrics=ga%3AtotalEvents&dimensions=ga%3AeventLabel

我不确定您所说的计数器 ID 是什么意思。您拥有分析服务,现在只需提出请求即可。

$params = array('dimensions' => 'ga:AeventLabel');  
// requesting the data  
$data = $analytics->data_ga->get("ga:89798036", "30daysAgo", "2016-05-11", "ga:totalEvents", $params );
// displaying the data
foreach ($data->getRows() as $row) {        
            print "ga:AeventLabel ".$row[0]." ga:totalEvents ".$row[1]";     
        }

我将 this class 与以下代码一起使用,效果很好:

require 'GoogleAPI/gapi.class.php';
define('ga_profile_id','YOUR-DEV-ID');

$ga = new gapi('YOUR-DEV-ID@developer.gserviceaccount.com','GoogleAPI/cert.p12');

$ga->requestReportData('YOUR-APP-ID',array('eventAction'),array('visitors'),null,"eventAction==loginViaWebsite",$"2016-05-11","2016-05-11");
$logins = $ga->getResults();
if($logins) $logins = $logins[0]->getMetrics();