Hello Analytics Reporting API v4; 웹 애플리케이션용 PHP 빠른 시작

이 튜토리얼에서는 Analytics Reporting API v4에 액세스하는 데 필요한 단계를 안내합니다.

1. API 사용 설정

애널리틱스 Reporting API v4를 사용하려면 먼저 설정 도구를 사용하여 Google API 콘솔에서 프로젝트를 만들고 API를 사용 설정하며 사용자 인증 정보를 만드는 과정을 진행합니다.

참고: 웹 클라이언트 ID 또는 설치된 애플리케이션 클라이언트를 만들려면 동의 화면에서 제품 이름을 설정해야 합니다. 아직 구성하지 않았다면 동의 화면 구성하라는 메시지가 표시됩니다.

사용자 인증 정보 만들기

  • 사용자 인증 정보 페이지를 엽니다.
  • 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
  • 애플리케이션 유형으로 웹 애플리케이션을 선택합니다.
  • 클라이언트 ID의 이름을 quickstart로 지정하고 만들기를 클릭합니다.
  • 승인된 자바스크립트 원본은 비워 둡니다. 이 튜토리얼에는 필요하지 않습니다.
  • 승인된 리디렉션 URIhttp://localhost:8080/oauth2callback.php로 설정합니다.
  • 만들기를 클릭합니다.

사용자 인증 정보 페이지에서 새로 만든 클라이언트 ID를 클릭하고 JSON 다운로드를 클릭하여 client_secrets.json로 저장합니다. 이 튜토리얼의 뒷부분이 필요합니다.

2. 클라이언트 라이브러리 설치하기

Composer를 사용하여 PHP용 Google API 클라이언트 라이브러리를 가져올 수 있습니다.

composer require google/apiclient:^2.0

3. 샘플 설정

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

  • index.php은 사용자가 방문하는 기본 페이지입니다.
  • oauth2callback.php에서 OAuth 2.0 응답을 처리합니다.

index.php

이 파일에는 Google 애널리틱스 API를 쿼리하고 결과를 표시하는 기본 로직이 포함되어 있습니다.

  • 첫 번째 샘플 코드를 index.php에 복사하거나 다운로드합니다.
  • VIEW_ID의 값을 바꿉니다. 계정 탐색기를 사용하여 보기 ID를 찾을 수 있습니다.
<?php

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

session_start();

$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_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.
  printResults($response);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */
function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("7daysAgo");
  $dateRange->setEndDate("today");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}


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. 샘플 실행

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

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

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

이 단계를 완료하면 샘플에서는 지정된 뷰의 지난 7일 동안의 세션 수를 출력합니다.