Google Analytics Reporting API - Get Activity data via Client ID

1k views Asked by At

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

There are 1 answers

1
Pavel On

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

$search = new Google_Service_AnalyticsReporting_SearchUserActivityRequest();

$search->setViewId($VIEW_ID); // Google Analytics 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"); // or CLIENT_ID if you are not using custom USER ID views
$user->setUserId($user_id); // The actual user's ID as stored in your DB passed to GA

$search->setPageSize(10); // Number of results you want to pull
$search->setUser($user);

return $analytics->userActivity->search($search); // Perform the search query.

Alternatively you can also pass the params to search() like:

$params = [
   'metrics' => //Your comma separated desired metrics
   'dimmensions' => //Your comma separated custom dimmentions
]

return $analytics->userActivity->search($search, $params);