이 튜토리얼에서는 Google 애널리틱스 계정에 액세스하고, 애널리틱스 API를 쿼리하고, API 응답을 처리하고, 결과를 출력하는 데 필요한 단계를 안내합니다. 이 가이드에서는 Core Reporting API v3.0, Management API v3.0, OAuth2.0을 사용합니다.
1단계: Analytics API 사용 설정
Google 애널리틱스 API를 사용하려면 먼저 설정 도구를 사용해야 합니다. 이 도구는 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 방법을 안내합니다.
클라이언트 ID 만들기
- 서비스 계정 페이지를 엽니다. 메시지가 표시되면 프로젝트를 선택합니다.
- 서비스 계정 만들기를 클릭한 다음 서비스 계정의 이름과 설명을 입력합니다. 기본 서비스 계정 ID를 사용하거나 다른 고유한 ID를 선택할 수도 있습니다. 완료하면 만들기를 클릭합니다.
- 이어지는 서비스 계정 권한(선택사항) 섹션은 선택하지 않아도 됩니다. 계속을 클릭합니다.
- 사용자에게 이 서비스 계정에 대한 액세스 권한 부여 화면에서 키 만들기 섹션이 나올 때까지 아래로 스크롤합니다. 키 만들기를 클릭합니다.
- 표시되는 측면 패널에서 키에 사용할 형식을 선택합니다. JSON을 사용하는 것이 좋습니다.
- 만들기를 클릭합니다. 새로운 공개 키/비공개 키 쌍이 생성되어 기기에 다운로드됩니다. 생성된 파일은 이 키의 유일한 사본으로 사용됩니다. 키를 안전하게 보관하는 방법을 자세히 알아보려면 서비스 계정 키 관리를 참조하세요.
- 비공개 키가 컴퓨터에 저장됨 대화상자에서 닫기를 클릭한 다음 완료를 클릭하여 서비스 계정 표로 돌아갑니다.
Google 애널리틱스 계정에 서비스 계정 추가
새로 만든 서비스 계정에는 <projectId>-<uniqueId>@developer.gserviceaccount.com
이라는 이메일 주소가 포함됩니다. 이 이메일 주소를 사용하여 API를 통해 액세스할 Google 애널리틱스 계정에 사용자를 추가합니다.
이 튜토리얼에서는 읽기 및 분석 권한만 있으면 됩니다.
2단계: Google 클라이언트 라이브러리 설치
PHP용 Google API 클라이언트 라이브러리 버전을 다운로드하거나 Composer를 사용하여 얻을 수 있습니다.
composer require google/apiclient:^2.0
3단계: 샘플 설정
아래의 샘플 코드를 포함하는 HelloAnalytics.php
라는 단일 파일을 만들어야 합니다.
- 다음 소스 코드를
HelloAnalytics.php
로 복사하거나 다운로드합니다. - 이전에 다운로드한
service-account-credentials.json
를 샘플 코드와 동일한 디렉터리로 이동합니다.
HelloAnalytics.php
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; $analytics = initializeAnalytics(); $profile = getFirstProfileId($analytics); $results = getResults($analytics, $profile); printResults($results); function initializeAnalytics() { // Creates and returns the Analytics Reporting service object. // 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_Analytics($client); return $analytics; } 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 "First view (profile) found: $profileName\n"; print "Total sessions: $sessions\n"; } else { print "No results found.\n"; } }
4단계: 샘플 실행
Analytics API를 사용 설정한 후 PHP용 Google API 클라이언트 라이브러리를 설치하고 샘플을 실행할 수 있는 샘플 소스 코드를 설정합니다.
다음을 사용하여 샘플을 실행합니다.
php HelloAnalytics.php
이 단계를 완료하면 샘플에서 승인된 사용자의 첫 번째 Google 애널리틱스 보기 (프로필) 이름과 지난 7일간의 세션수를 출력합니다.
이제 승인된 애널리틱스 서비스 객체를 사용하여 Management API 참조 문서에 있는 코드 샘플을 실행할 수 있습니다. 예를 들어 accountSummaries.list 메서드를 사용하도록 코드를 변경할 수 있습니다.