Google Analytics Reporting API - Get Activity data via Client ID

Viewed 680

I am trying to get user activity data via his client id using Google Analytics api. Take a look at the below image:

enter image description here

Now highlighted text is users client id, it could be user id too, and when I trying to get it via Google's playground, I get the correct response and activity data which is required, like:

enter image description here

and this is the response: enter image description here

which is required and OK.

but I want this data via API, and have searched the web to get it, but nothing helped me.

Here is sample code Google showing i.e.

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

I do found a class for adding user to request i.e.

$user = new Google_Service_AnalyticsReporting_User();
$user->setType("CLIENT_ID");
$user->setUserId("660467279.1539972080");

but this class Google_Service_AnalyticsReporting_ReportRequest which accepts conditions/filters for query does not have such method to accept user object.

How can I achieve this?

1 Answers

You should use this function $analytics->userActivity->search().

$search = new Google_Service_AnalyticsReporting_SearchUserActivityRequest();

$search->setViewId($VIEW_ID);

$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
$search->setDateRange($dateRange);    

$user = new Google_Service_AnalyticsReporting_User();
$user->setType("USER_ID");
$user->setUserId($user_id);

$search->setPageSize(10);
$search->setUser($user);

return $analytics->userActivity->search($search);
Related