简体   繁体   中英

GA4 run report setting metrics & dimenssion

Using php laravel i am implementing GA4 data analytics api to get metrics data of my GA4 client website but i am unable to find method setName in Google_Service_AnalyticsReporting_Metric class when running script with out adding name i am getting error

Metric.name is required and must not be the empty string

here is my code

$analytics=new Google_Service_AnalyticsData($client);

      // Create the ReportRequest object.
      $dateRange = new Google_Service_AnalyticsReporting_DateRange();
      $dateRange->setStartDate("7daysAgo");
      $dateRange->setEndDate("today");
    
      // Create the Metrics object.
      $metric = new Google_Service_AnalyticsReporting_Metric();
      $metric->setExpression("ga:city");
    
    
      // Create the Entity object.
      $entity=new Google_Service_AnalyticsData_Entity();
      $entity->setPropertyId("11111111");
    
      // Create the Request object.
      $request = new Google_Service_AnalyticsData_RunReportRequest();
      $request->setEntity($entity);
      $request->setDateRanges($dateRange);
      $request->setMetrics($metric);
      $data=$analytics->v1alpha->runReport($request);

Please replace "Google_Service_AnalyticsReporting_Metric" with "Google_Service_AnalyticsData_Metric". After replacing that variable, the setName method should be present.

If you want to retrieve metric data for GA4 property, you need to use the AnalyticsData API. If you want to retrieve metric data for Universal Analytics view, you can use the AnalyticsReporting API. There are separate PHP classes for each API.

In this code snippet, code for both APIs are present. Classes for these two separate APIs cannot be used interchangeably.

In the AnalyticsData API, the metric class has a name field: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/Metric

This is a reference for the AnalyticsReporting API: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php . All objects begin with "Google_Service_AnalyticsReporting_".

Also, "city" is a dimension and not a metric. In GA4, dimension and metric names are not prefixed by "ga:"; the dimension name is just "city" and not "ga:city". For the AnalyticsData API, these are the dimensions and metrics available in the API: https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM