Introduzione all'API Analytics: guida rapida a JavaScript per le applicazioni web

Questo tutorial illustra i passaggi necessari per accedere a un account Google Analytics, eseguire query sulle API Analytics, gestire le risposte dell'API e generare i risultati. In questo tutorial vengono utilizzate l'API di reporting principale v3.0, l'API di gestione v3.0 e OAuth2.0.

Passaggio 1: attiva l'API Analytics

Per iniziare a utilizzare l'API Google Analytics, devi prima utilizzare lo strumento di configurazione, che ti guida nella creazione di un progetto nella console API di Google, nell'attivazione dell'API e nella creazione delle credenziali.

Crea un ID client

Dalla pagina Credenziali:

  1. Fai clic su Crea credenziali e seleziona ID client OAuth.
  2. Seleziona Applicazione web per TIPO DI APPLICAZIONE.
  3. Assegna un nome alla credenziale.
  4. Imposta ORIGINI JAVASCRIPT AUTORIZZATE su http://localhost:8080
  5. Imposta gli URI DI REINDIRIZZO AUTORIZZATI su http://localhost:8080/oauth2callback
  6. Fai clic su Crea.

Passaggio 2: configura l'esempio

Devi creare un file denominato HelloAnalytics.html, che conterrà il codice HTML e JavaScript del nostro esempio.

  1. Copia o scarica il seguente codice sorgente in HelloAnalytics.html.
  2. sostituisci '<YOUR_CLIENT_ID>' con il tuo ID client. creati in precedenza.
<!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>

Passaggio 3: esegui l'esempio

Dopo aver abilitato l'API Analytics e configurato il codice sorgente di esempio, l'esempio è pronto per essere eseguito.

  1. Pubblica HelloAnalytics.html sul tuo server web e carica la pagina nel browser.
  2. Fai clic sul pulsante Autorizza e autorizza l'accesso a Google Analytics.

Al termine di questi passaggi, l'esempio restituisce il nome della prima vista (profilo) Google Analytics dell'utente autorizzato e il numero di sessioni negli ultimi sette giorni.

Con l'oggetto di servizio Analytics autorizzato ora puoi eseguire qualsiasi esempio di codice trovato nei documenti di riferimento dell'API Management. Ad esempio, potresti provare a modificare il codice per utilizzare il metodo accountSummaries.list.