Hello Analytics API: Panduan memulai JavaScript untuk aplikasi web

Tutorial ini akan memandu langkah-langkah yang diperlukan untuk mengakses akun Google Analytics, membuat kueri Analytics API, menangani respons API, dan menampilkan hasilnya. Core Reporting API v3.0, Management API v3.0, dan OAuth2.0 digunakan dalam tutorial ini.

Langkah 1: Aktifkan Analytics API

Untuk mulai menggunakan Google Analytics API, Anda harus menggunakan alat penyiapan terlebih dahulu, yang memandu Anda menyelesaikan pembuatan project di Konsol API Google, mengaktifkan API, dan membuat kredensial.

Membuat client ID

Dari halaman Credentials:

  1. Klik Create Credentials, lalu pilih OAuth client ID.
  2. Pilih Web application untuk APPLICATION TYPE.
  3. Beri nama kredensial.
  4. Tetapkan ASLI JAVASCRIPT RESMI ke http://localhost:8080
  5. Tetapkan URI RESMI RESMI ke http://localhost:8080/oauth2callback
  6. Klik Create.

Langkah 2: Siapkan contoh

Anda harus membuat satu file bernama HelloAnalytics.html, yang akan berisi kode HTML dan JavaScript untuk contoh kami.

  1. Salin atau download kode sumber berikut ke HelloAnalytics.html.
  2. ganti '<YOUR_CLIENT_ID>' dengan client ID Anda. yang dibuat di atas.
<!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>

Langkah 3: Jalankan contoh

Setelah Anda mengaktifkan Analytics API, dan menyiapkan kode sumber contoh, contoh ini siap dijalankan.

  1. Publikasikan HelloAnalytics.html ke server web Anda dan muat halaman di browser Anda.
  2. Klik tombol Authorize, dan izinkan akses ke Google Analytics.

Setelah Anda menyelesaikan langkah-langkah ini, contoh menghasilkan nama tampilan (profil) Google Analytics pertama pengguna yang diotorisasi dan jumlah sesi selama tujuh hari terakhir.

Dengan objek layanan Analytics yang diotorisasi, kini Anda dapat menjalankan contoh kode apa pun yang ada di dokumen referensi Management API. Misalnya, Anda dapat mencoba mengubah kode untuk menggunakan metode accountSummaries.list.