user10725404
user10725404

Reputation:

why my Google analytics api 4 return an error

Hello i'm working on a small project using PHP and Google Client API. i don't know why i get this error message :

Message: Undefined property: Google_Service_Analytics::$reports

since my code is correct is the same one on the Google documentation web page.

This is my code :

$client = new Google_Client();
    $client->setApplicationName("Hello Analytics Reporting");
    $client->setAuthConfig(FCPATH.'trim-tide-225210-c7xxxxssz7f4c.json');
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_Analytics($client);
    $VIEW_ID = "ga:159882843";

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

Upvotes: 2

Views: 1360

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116868

You are mixing Google Analtyics core reporting v3 and Google Analytics reporting v4 APIs

For creating an analytics service using Google Analytics core reporting api v3

$analytics = new Google_Service_Analytics($client);

For creating an analytics service for use with Google analytics reporting api v4

$analytics = new Google_Service_AnalyticsReporting($client);

You have created a service to connect the Google Analytics core reporting v3 yet your code is attempting to connect to the Google Analytics reporting v4 APIs

Upvotes: 7

Related Questions