본문 바로가기

PHP

구글 애널리틱스 API 연동

사실 아래 링크에 잘 나와있다.

 

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php

 

Hello Analytics Reporting API v4; PHP quickstart for service accounts  |  Analytics Reporting API v4  |  Google Developers

This tutorial walks through the steps required to access the Analytics Reporting API v4. Note: The purpose of these quickstart guides is to help you get through the initial hurdles of API authorization with the Google API Client Libraries. As these librari

developers.google.com

그대로 하기만 하면 된다.

 

근데 일단 간단히 요약을 하자면,

 

크게 두종류의 접근 방법이 있다.

 

Google Analytics의 정보를 볼 수 있는 계정으로 로그인하여 인증을 받거나,

 

서비스계정을 만들어서 Google Analytics에 추가하여 매번 로그인 인증을 피하는 방법이 있다.

 

클라이언트앱을 만들어서 다양한 사람이 각자 자기 정보를 보는 앱을 만든다면,

 

첫번째 방법을 쓰면 될 것이고,

 

그냥 자기가 만든 홈페이지인데 정보를 뽑아놓고 다른곳에서 볼 때는 두번째 방법을 쓰면 된다.

 

나같은 경우는 내가 만든 웹사이트의 관리자 페이지에서 특정 조건 만을 뽑아서 보려고,

 

두번째 방식을 택했다.

 

 

1. 구글 개발자 콘솔에서 서비스계정 생성

 

 > 말 그대로 '서비스 계정' 이라는 항목이 있다. 생성하면 된다. 

 > 필요한 것은 만들어진 이메일 계정과 .json 키파일이다.

 

2. Google Analytics 사용자에 서비스 계정의 이메일 주소를 등록한다.

 

3. .json 키파일을 웹서버의 적당한 위치에 저장해둔다.

 

4. 구글 api 라이브러리 파일을 불러온다

  > composer require google/apiclient:^2.0

 

5. 그 다음에는 아래 코드를 응용하여 필요한 대로 적용한다.

 

<?php

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

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);


/**
 * Initializes an Analytics Reporting API V4 service object.
 *
 * @return An authorized Analytics Reporting API V4 service object.
 */
function initializeAnalytics()
{

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_AnalyticsReporting($client);

  return $analytics;
}


/**
 * 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");
        }
      }
    }
  }
}