API de Hello Analytics Reporting v4; guía de inicio rápido de PHP para aplicaciones web

En este instructivo, se explican los pasos necesarios para acceder a la API de Analytics Reporting v4.

1. Habilita la API

Para comenzar a usar la API de Analytics Reporting v4, primero debes usar la herramienta de configuración, que te guiará para crear un proyecto en la Consola de API de Google, habilitar la API y crear credenciales.

Nota: Para crear un ID de cliente web o un cliente de la aplicación instalada, debes establecer un nombre de producto en la pantalla de consentimiento. Si aún no lo hiciste, se te solicitará que configures la pantalla de consentimiento.

Crea credenciales

  • Abre la página Credenciales.
  • Haz clic en Crear credenciales y selecciona ID de cliente de OAuth.
  • En Tipo de aplicación, selecciona Aplicación web.
  • Asígnale el nombre quickstart al ID de cliente y haz clic en Create.
  • Deja en blanco Orígenes autorizados de JavaScript, ya que no es necesario para este instructivo.
  • Establece los URI de redireccionamiento autorizados en http://localhost:8080/oauth2callback.php.
  • Haz clic en Crear.

En la página de Credenciales, haz clic en el ID de cliente recién creado, luego en Descargar JSON y guárdalo como client_secrets.json. Lo necesitarás más adelante en el instructivo.

2. Instala la biblioteca cliente

Puedes obtener la biblioteca cliente de las APIs de Google para PHP con Composer:

composer require google/apiclient:^2.0

3. Configura la muestra

Deberás crear dos archivos:

  • index.php será la página principal que visitará el usuario.
  • oauth2callback.php controlará la respuesta de OAuth 2.0.

index.php

Este archivo contiene la lógica principal para consultar las APIs de Google Analytics y mostrar los resultados.

  • Copia o descarga el primer código de muestra en index.php.
  • Reemplaza el valor de VIEW_ID. Puedes utilizar el Explorador de cuentas para encontrar un ID de vista.
<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$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'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */
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 );
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
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");
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}


oauth2callback.php

Este archivo controla la respuesta de OAuth 2.0. Copia o descarga el segundo código de muestra en oauth2callback.php.

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


4. Ejecutar la muestra

Ejecuta la muestra con un servidor web configurado para entregar PHP. Si usas PHP 5.4 o una versión más reciente, puedes usar el servidor web de prueba integrado de PHP ejecutando el siguiente comando:

php -S localhost:8080 -t /path/to/sample

Luego, visita http://localhost:8080 en el navegador.

Cuando termines estos pasos, la muestra mostrará la cantidad de sesiones de los últimos siete días para la vista determinada.