Hello Analytics API: JavaScript-Kurzanleitung für Webanwendungen

In dieser Anleitung werden die Schritte beschrieben, die erforderlich sind, um auf ein Google Analytics-Konto zuzugreifen, die Analytics APIs abzufragen, die API-Antworten zu verarbeiten und die Ergebnisse auszugeben. In dieser Anleitung werden die Core Reporting API v3.0, die Management API v3.0 und OAuth 2.0 verwendet.

Schritt 1: Analytics API aktivieren

Bevor Sie die Google Analytics API verwenden können, müssen Sie zuerst das Einrichtungstool verwenden. Dieses Tool führt Sie durch die Erstellung eines Projekts in der Google API Console, die Aktivierung der API und die Erstellung von Anmeldedaten.

Client-ID erstellen

Auf der Seite „Anmeldedaten“:

  1. Klicken Sie auf Anmeldedaten erstellen und wählen Sie OAuth-Client-ID aus.
  2. Wählen Sie Webanwendung als ANWENDUNGSTYP aus.
  3. Benennen Sie die Anmeldedaten.
  4. Legen Sie für AUTORISIERTE JAVASKRIPTIONEN http://localhost:8080 fest.
  5. Legen Sie für AUTORISIERTE WEITERLEITUNGS-URIS den Wert http://localhost:8080/oauth2callback fest.
  6. Klicken Sie auf Erstellen.

Schritt 2: Beispiel einrichten

Sie müssen eine Datei mit dem Namen HelloAnalytics.html erstellen, die den HTML- und JavaScript-Code für unser Beispiel enthält.

  1. Kopieren oder laden Sie den folgenden Quellcode in HelloAnalytics.html herunter.
  2. Ersetzen Sie '<YOUR_CLIENT_ID>' durch Ihre Client-ID. oben erstellt.
<!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>

Schritt 3: Beispiel ausführen

Nachdem Sie die Analytics API aktiviert und den Beispielcode eingerichtet haben, kann das Beispiel ausgeführt werden.

  1. Veröffentlichen Sie HelloAnalytics.html auf Ihrem Webserver und laden Sie die Seite in Ihrem Browser.
  2. Klicken Sie auf die Schaltfläche Autorisieren und autorisieren Sie den Zugriff auf Google Analytics.

Wenn Sie diese Schritte ausgeführt haben, werden im Beispiel der Name der ersten Google Analytics-Datenansicht (Profil) des autorisierten Nutzers und die Anzahl der Sitzungen in den letzten sieben Tagen ausgegeben.

Mit dem autorisierten Analytics-Dienstobjekt können Sie jetzt beliebige Codebeispiele ausführen, die in den Referenzdokumenten zur Management API enthalten sind. Sie könnten beispielsweise versuchen, den Code mit der Methode accountSummaries.list zu ändern.