API de Hello Analytics: guía de inicio rápido de JavaScript para aplicaciones web

En este instructivo, se explican los pasos necesarios para acceder a una cuenta de Google Analytics, consultar las APIs de Analytics, manejar las respuestas de la API y generar los resultados. En este instructivo, se usan la API de Core Reporting v3.0, la API de Management v3.0 y OAuth2.0.

Paso 1: Habilita la API de Analytics

Para comenzar a usar la API de Google Analytics, 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.

Crea un ID de cliente

En la página Credenciales, sigue estos pasos:

  1. Haz clic en Crear credenciales y selecciona ID de cliente de OAuth.
  2. Selecciona Aplicación web para TIPO DE APLICACIÓN.
  3. Asigna un nombre a la credencial.
  4. Configura los ORIGENES DE JAVASCRIPT AUTORIZADOS como http://localhost:8080.
  5. Configura los URI REDIRECT AUTORIZADOS como http://localhost:8080/oauth2callback.
  6. Haz clic en Crear.

Paso 2: Configura la muestra

Deberás crear un archivo llamado HelloAnalytics.html, que contendrá el código HTML y JavaScript de nuestro ejemplo.

  1. Copia o descarga el siguiente código fuente en HelloAnalytics.html.
  2. reemplaza '<YOUR_CLIENT_ID>' por tu ID de cliente. que creaste anteriormente.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>

<button id="auth-button" hidden>Authorize</button>

<h1>Hello Analytics</h1>

<textarea cols="80" rows="20" id="query-output"></textarea>

<script>

  // Replace with your client ID from the developer console.
  var CLIENT_ID = '<YOUR_CLIENT_ID>';

  // Set authorized scope.
  var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];


  function authorize(event) {
    // Handles the authorization flow.
    // `immediate` should be false when invoked from the button click.
    var useImmdiate = event ? false : true;
    var authData = {
      client_id: CLIENT_ID,
      scope: SCOPES,
      immediate: useImmdiate
    };

    gapi.auth.authorize(authData, function(response) {
      var authButton = document.getElementById('auth-button');
      if (response.error) {
        authButton.hidden = false;
      }
      else {
        authButton.hidden = true;
        queryAccounts();
      }
    });
  }


function queryAccounts() {
  // Load the Google Analytics client library.
  gapi.client.load('analytics', 'v3').then(function() {

    // Get a list of all Google Analytics accounts for this user
    gapi.client.analytics.management.accounts.list().then(handleAccounts);
  });
}


function handleAccounts(response) {
  // Handles the response from the accounts list method.
  if (response.result.items && response.result.items.length) {
    // Get the first Google Analytics account.
    var firstAccountId = response.result.items[0].id;

    // Query for properties.
    queryProperties(firstAccountId);
  } else {
    console.log('No accounts found for this user.');
  }
}


function queryProperties(accountId) {
  // Get a list of all the properties for the account.
  gapi.client.analytics.management.webproperties.list(
      {'accountId': accountId})
    .then(handleProperties)
    .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProperties(response) {
  // Handles the response from the webproperties list method.
  if (response.result.items && response.result.items.length) {

    // Get the first Google Analytics account
    var firstAccountId = response.result.items[0].accountId;

    // Get the first property ID
    var firstPropertyId = response.result.items[0].id;

    // Query for Views (Profiles).
    queryProfiles(firstAccountId, firstPropertyId);
  } else {
    console.log('No properties found for this user.');
  }
}


function queryProfiles(accountId, propertyId) {
  // Get a list of all Views (Profiles) for the first property
  // of the first Account.
  gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': propertyId
  })
  .then(handleProfiles)
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProfiles(response) {
  // Handles the response from the profiles list method.
  if (response.result.items && response.result.items.length) {
    // Get the first View (Profile) ID.
    var firstProfileId = response.result.items[0].id;

    // Query the Core Reporting API.
    queryCoreReportingApi(firstProfileId);
  } else {
    console.log('No views (profiles) found for this user.');
  }
}


function queryCoreReportingApi(profileId) {
  // Query the Core Reporting API for the number sessions for
  // the past seven days.
  gapi.client.analytics.data.ga.get({
    'ids': 'ga:' + profileId,
    'start-date': '7daysAgo',
    'end-date': 'today',
    'metrics': 'ga:sessions'
  })
  .then(function(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  })
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}

  // Add an event listener to the 'auth-button'.
  document.getElementById('auth-button').addEventListener('click', authorize);
</script>

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>

</body>
</html>

Paso 3: Ejecuta la muestra

Después de habilitar la API de Analytics y configurar el código fuente de muestra, la muestra estará lista para ejecutarse.

  1. Publica HelloAnalytics.html en tu servidor web y carga la página en tu navegador.
  2. Haz clic en el botón Autorizar y autoriza el acceso a Google Analytics.

Cuando termines estos pasos, la muestra mostrará el nombre de la primera vista (perfil) de Google Analytics del usuario autorizado y la cantidad de sesiones de los últimos siete días.

Con el objeto de servicio autorizado de Analytics, ahora puedes ejecutar cualquiera de las muestras de código que se encuentren en los documentos de referencia de la API de Management. Por ejemplo, podrías intentar cambiar el código para usar el método accountSummaries.list.