为什么我的Google Analytics(分析)API 4返回错误

时间:2018-12-11 10:34:56

标签: php google-analytics google-api google-analytics-api google-api-php-client

您好,我正在使用PHP和Google Client API进行一个小项目。 我不知道为什么会收到此错误消息:

  

消息:未定义的属性:Google_Service_Analytics :: $ reports

因为我的代码正确,所以与Google文档网页上的代码相同。

这是我的代码:

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

1 个答案:

答案 0 :(得分:3)

您正在混合使用Google Analtyics核心报告v3和Google Analytics(分析)报告v4 API

用于使用Google Analytics(分析)核心报告API v3创建分析服务

  

$ analytics =新的Google_Service_Analytics($ client);

用于创建要与Google Analytics(分析)Reporting API v4配合使用的分析服务

  

$ analytics =新的Google_Service_AnalyticsReporting($ client);

您已经创建了连接Google Analytics(分析)核心报告v3的服务,但是您的代码正在尝试连接到Google Analytics(分析)报告v4 API