Hello Analytics API: 웹 애플리케이션을 위한 PHP 빠른 시작

이 튜토리얼에서는 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. 승인된 자바스크립트 출처는 비워 둡니다. 이 가이드에서는 필요하지 않습니다.
  5. 승인된 리디렉션 URIhttp://localhost:8080/oauth2callback.php로 설정합니다.
  6. 만들기를 클릭합니다.

방금 만든 사용자 인증 정보를 선택하고 JSON 다운로드를 클릭합니다. 다운로드한 파일을 client_secrets.json로 저장합니다. 이 파일은 가이드의 후반부에 필요합니다.

2단계: Google 클라이언트 라이브러리 설치

PHP용 Google API 클라이언트 라이브러리 버전을 다운로드하거나 Composer를 사용하여 얻을 수 있습니다.

composer require google/apiclient:^2.0

3단계: 샘플 설정

다음 두 파일을 만들어야 합니다.

  1. index.php이(가) 사용자가 방문하는 기본 페이지가 됩니다.
  2. oauth2callback.php에서 OAuth 2.0 응답을 처리합니다.

index.php

이 파일에는 Google 애널리틱스 API를 쿼리하고 결과를 표시하기 위한 기본 로직이 포함되어 있습니다. 첫 번째 샘플 코드를 index.php에 복사하거나 다운로드합니다.

<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);

  // Get the first view (profile) id for the authorized user.
  $profile = getFirstProfileId($analytics);

  // Get the results from the Core Reporting API and print the results.
  $results = getResults($analytics, $profile);
  printResults($results);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getFirstProfileId($analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($properties->getItems()) > 0) {
      $items = $properties->getItems();
      $firstPropertyId = $items[0]->getId();

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

      } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No properties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults($analytics, $profileId) {
  // Calls the Core Reporting API and queries for the number of sessions
  // for the last seven days.
  return $analytics->data_ga->get(
      'ga:' . $profileId,
      '7daysAgo',
      'today',
      'ga:sessions');
}

function printResults($results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    // Print the results.
    print "<p>First view (profile) found: $profileName</p>";
    print "<p>Total sessions: $sessions</p>";
  } else {
    print "<p>No results found.</p>";
  }
}

?>

oauth2callback.php

이 파일은 OAuth 2.0 응답을 처리합니다. 두 번째 샘플 코드를 oauth2callback.php에 복사하거나 다운로드합니다.

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


4단계: 샘플 실행

Analytics API를 사용 설정한 후 PHP용 Google API 클라이언트 라이브러리를 설치하고 샘플을 실행할 수 있는 샘플 소스 코드를 설정합니다.

PHP를 제공하도록 구성된 웹 서버를 사용하여 샘플을 실행합니다. PHP 5.4 이상을 사용하는 경우 다음 명령어를 실행하여 PHP의 내장 테스트 웹 서버를 사용할 수 있습니다.

php -S localhost:8080 /path/to/sample

그런 다음 브라우저에서 http://localhost:8080을 방문합니다.

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

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