Google Analytics API v4自定义报告

时间:2019-06-06 11:14:10

标签: php google-analytics

我正在尝试使我们的应用程序网站的Google Analytics(分析)报告自动化,例如55左右。

我需要的是

avg time
users new/returning
direct/referral/search
users per day (based on 1st of the month to the last day)

我正在使用Google的指南

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php

我的报告功能如下:

function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "XXXX";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2019-05-01");
  $dateRange->setEndDate("2019-05-31");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  $users = new Google_Service_AnalyticsReporting_Metric();
  $users->setExpression("ga:users");
  $users->setAlias("users");

  $newSessions = new Google_Service_AnalyticsReporting_Metric();
  $newSessions->setExpression("ga:percentNewSessions");
  $newSessions->setAlias("newSessions");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions,$users,$newSessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}

当然不是我要尝试的一些指标。

我正试图每天这样吸引用户

  $monthusers = new Google_Service_AnalyticsReporting_Metric();
  $monthusers->setExpression("ga:30dayUsers");
  $monthusers->setAlias("monthusers");

然后在请求中

$request->setMetrics(array($sessions,$users,$newSessions,$monthusers));

但是它抛出500错误,关于每天如何吸引用户的任何想法?并基于:

$dateRange->setStartDate("2019-05-01");
$dateRange->setEndDate("2019-05-31");

1 个答案:

答案 0 :(得分:0)

根据Dimensions & Metrics Explorer for the metric "ga:30dayUsers"中所述:

  

必须将ga:nthDay,ga:date或ga:day中的至少一个指定为   维度以查询该指标。

您可以在报表请求中使用ga:day维度来解决此问题:

$day = new Google_Service_AnalyticsReporting_Dimension();
$day->setName("ga:day");

$request->setDimensions(array($day));