このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。チュートリアルでは、Core Reporting API v3.0、Management API v3.0、 OAuth 2.0 を使用しています。
ステップ 1: アナリティクス API を有効にする
Google アナリティクス API を使用するには、最初に セットアップ ツールを使用して Google API コンソールでプロジェクトを 作成し、API を有効にして認証情報を作成する必要があります。
クライアント ID を作成する
- [サービス アカウント] ページを開きます。 画面のメッセージに従って、プロジェクトを選択します。
- [サービス アカウントを作成] をクリックします。
- [サービス アカウントの作成] ウィンドウで、サービス アカウントの名前を入力し、[新しい秘密鍵の提供] を選択します。サービス アカウントに Google Workspace ドメイン全体の権限を付与する場合、[Google Workspace ドメイン全体の委任を有効にする] も選択します。選択したら、[保存] をクリックします。
新しい公開鍵 / 秘密鍵のペアが生成され、マシンにダウンロードされます。この鍵には他のコピーはありません。安全に保管してください。
Google アナリティクス アカウントへのサービス アカウントの追加
新しく作成したサービス アカウントには、メールアドレス(<projectId>-<uniqueId>@developer.gserviceaccount.com
)が含まれます。このメールアドレスを使用して、API 経由でアクセスしたい Google アナリティクス アカウントにユーザーを追加します。このチュートリアルで必要な権限は、表示と分析のみです。
ステップ 2: Google クライアント ライブラリをインストールする
PHP 用の Google API クライアント ライブラリを入手するには、リリースをダウンロードするか、Composer を使用します。
composer require google/apiclient:^2.0
ステップ 3: サンプルを設定する
HelloAnalytics.php
という名前のファイルを 1 つ作成する必要があります。このファイルには下記のサンプルコードを記述します。
- 次のソースコードを
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: サンプルを実行する
アナリティクス API を有効にして、PHP 用 Google API クライアント ライブラリをインストールし、サンプル ソースコードを設定したら、サンプルの実行準備は完了です。
次のコマンドを使用してサンプルを実行します。
php HelloAnalytics.php
以上の手順が完了すると、サンプルコードによって、認証済みユーザーの最初の Google アナリティクス ビュー(旧プロファイル)の名前と、過去 7 日間のセッション数が出力されます。
承認済みの Analytics サービス オブジェクトを使用すると、Management API リファレンス ドキュメントに記載されているサンプルコードをすべて実行できます。たとえば、コードを変更して accountSummaries.list メソッドを試すことができます。