Google Analytics(分析)API 入门:适用于网络应用的 JavaScript 快速入门

本教程详细介绍了访问 Google Analytics(分析)帐户、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0Management API v3.0OAuth2.0

第 1 步:启用 Google 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. '&ltYOUR_CLIENT_ID&gt' 替换为上面创建的客户端 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 步:运行示例代码

在您启用了 Google Analytics(分析)API 并设置了示例源代码后,该示例代码就可以运行了。

  1. HelloAnalytics.html 发布到您的网络服务器并在浏览器中加载该页。
  2. 点击“授权”按钮,然后授予访问 Google Analytics(分析)的权限。

当您完成上述步骤后,示例代码就会输出已获授权用户的首个 Google Analytics(分析)数据视图(配置文件)的名称以及过去 7 天内的会话数。

现在,借助已授权的 Google Analytics(分析)服务对象,您可以运行 Management API 参考文档中的任何代码示例。例如,您可以尝试更改代码来使用 accountSummaries.list 方法。