Hello Analytics API: 웹 애플리케이션용 JavaScript 빠른 시작

이 튜토리얼에서는 Google 애널리틱스 계정에 액세스하고, 애널리틱스 API를 쿼리하고, API 응답을 처리하고, 결과를 출력하는 데 필요한 단계를 안내합니다. 이 튜토리얼에서는 Core Reporting API v3.0, Management API v3.0, OAuth2.0이 사용됩니다.

1단계: Analytics API 사용 설정

Google 애널리틱스 API를 사용하려면 먼저 설정 도구를 사용해야 합니다. 설정 도구는 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 과정을 안내합니다.

클라이언트 ID 만들기

사용자 인증 정보 페이지에서 다음을 수행합니다.

  1. 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
  2. 애플리케이션 유형으로 웹 애플리케이션을 선택합니다.
  3. 사용자 인증 정보의 이름을 지정합니다.
  4. 승인된 자바스크립트 출처http://localhost:8080으로 설정합니다.
  5. 승인된 리디렉션 URIhttp://localhost:8080/oauth2callback으로 설정합니다.
  6. 만들기를 클릭합니다.

2단계: 샘플 설정

이름이 HelloAnalytics.html인 파일을 하나 만들어야 합니다. 이 파일에는 이 예시의 HTML 및 자바스크립트 코드가 포함됩니다.

  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 애널리틱스에 대한 액세스를 승인합니다.

이 단계를 완료하면 샘플에서 승인된 사용자의 첫 번째 Google 애널리틱스 보기 (프로필) 이름과 지난 7일간의 세션수를 출력합니다.

이제 승인된 애널리틱스 서비스 객체를 사용하여 Management API 참조 문서에 있는 모든 코드 샘플을 실행할 수 있습니다. 예를 들어 accountSummaries.list 메서드를 사용하도록 코드를 변경할 수 있습니다.