Hello Analytics API:網頁應用程式 JavaScript 快速入門導覽課程

本教學課程逐步介紹存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應,並輸出結果的必要步驟。本教學課程使用 Core Reporting API 3.0 版Management API v3.0OAuth2.0

步驟 1:啟用 Analytics (分析) API

如要開始使用 Google Analytics API,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

建立用戶端 ID

在「憑證」頁面中:

  1. 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
  2. 應用程式類型選取「網頁應用程式」
  3. 輸入憑證名稱。
  4. 已授權的 JAVAScript 從設為 http://localhost:8080
  5. 授權重新導向 URI 設為 http://localhost:8080/oauth2callback
  6. 點選「建立」

步驟 2:設定範例

您必須建立名為 HelloAnalytics.html 的檔案,其中會有範例中的 HTML 和 JavaScript 程式碼。

  1. 將下列原始碼複製或 下載HelloAnalytics.html
  2. '<YOUR_CLIENT_ID>' 替換成您的用戶端 ID。
<!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>

步驟 3:執行範例

啟用 Analytics (分析) API 之後, 請設定可開始執行的範例原始碼。

  1. HelloAnalytics.html 發布至網路伺服器,並在瀏覽器中載入頁面。
  2. 按一下「授權」按鈕,然後授權存取 Google Analytics (分析)。

完成這些步驟後,範例會輸出授權使用者的第一個 Google Analytics (分析) 資料檢視 (設定檔) 名稱,以及最近七天的工作階段數。

現在,您可以使用已授權的 Analytics (分析) 服務物件,執行 Management API 參考文件中的任何程式碼範例。例如,您可以嘗試變更程式碼,改用 accountSummaries.list 方法。