Search code examples
google-analyticsgoogle-analytics-apigoogle-analytics-firebase

google analytics api need exact date, hour and minute


Im experimenting with the google reports api (v4), im using the goalCompletionsAll metric, and is bringing the info that i need, im passing as parameters ga:medium, ga:date, ga:hour however when i pass the ga:minute parameter as request it throws me the following error: "Selected dimensions and metrics cannot be queried together." I understand that the metrics have their own set of dimensions, but i found this weird, since when i use the query explorer i add all this dimensions and it returns the correct info, but as soon as i put in the code, it displays the error...

enter image description here

enter image description here

Here i attach my code to see if someone can point me into the right direction regarding this.

<?php
require_once 'google-api-php-client/src/Google/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('xxxxx');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.
  printResults($response);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/api/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getReport(&$analytics) {

  // Replace with your view ID. E.g., XXXX.
  $VIEW_ID = "xxxxxxxx";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2016-01-01");
  $dateRange->setEndDate("today");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:goalCompletionsAll");
  $sessions->setAlias("objetivos");
  
  //Create the Dimensions object.
  $medium = new Google_Service_Analyticsreporting_Dimension();
  $medium->setName("ga:medium");
  
  $minute = new Google_Service_Analyticsreporting_Dimension();
  $minute->setName("ga:minute");
  
  $hour = new Google_Service_Analyticsreporting_Dimension();
  $hour->setName("ga:hour");

  $date = new Google_Service_Analyticsreporting_Dimension();
  $date->setName("ga:date");

  $avgpageloadtime = new Google_Service_Analyticsreporting_Metric();
  $avgpageloadtime->setExpression("ga:avgpageloadtime");
  $avgpageloadtime->setAlias("average load time");

  $goals = new Google_Service_Analyticsreporting_Metric();
  $goals->setExpression("ga:goalStartsAll");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setDimensions(array($medium, $date, $hour, $minute));
  $request->setMetrics(array($sessions, $avgpageloadtime, $goals));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}


function printResults(&$reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");

      }

      echo "<br>";

      for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];

        $values = $metrics[$j];
        //print("Tipo de metrica: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
          //echo $values->getValues()[$valueIndex]."<br>";
          //print($entry->getName() . ": " . $value . "<br>");
        }
      }
    }
  }
}

?>

Thanks in advance.


Solution

  • The issue you are seeing is that in the query explorer you are querying for ga:goalCompletionsAll and the V4 API you are querying for ga:gaolStartsAll which happens to be incompatible with ga:avgPageLoadTime:

    See the Dimensions and Metrics Explorer for details of which dimensions are incompatible with others.

    Remove the ga:avgPageLoadTime and you should be able to get the information you need.

    TLDR: your V4 API request has different metrics than the Query Explorer Request.