はじめてのアナリティクス API: ウェブ アプリケーション向け JavaScript クイックスタート

このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。チュートリアルでは、Core Reporting API v3.0Management API v3.0OAuth 2.0 を使用しています。

ステップ 1: アナリティクス API を有効にする

Google アナリティクス 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 という名前のファイルを 1 つ作成する必要があります。このファイルには 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: サンプルを実行する

アナリティクス API を有効にして、サンプル ソースコードを設定したら、サンプルの実行準備は完了です。

  1. HelloAnalytics.html をウェブサーバーで公開して、ページをブラウザで読み込みます。
  2. [承認] ボタンをクリックして、Google アナリティクスへのアクセスを承認します。

以上の手順が完了すると、サンプルコードによって、認証済みユーザーの最初の Google アナリティクス ビュー(旧プロファイル)の名前と、過去 7 日間のセッション数が出力されます。

承認済みの Analytics サービス オブジェクトを使用すると、Management API リファレンス ドキュメントに記載されているサンプルコードをすべて実行できます。たとえば、コードを変更して accountSummaries.list メソッドを試すことができます。