このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。このチュートリアルでは、Core Reporting API v3.0、Management API v3.0、OAuth2.0 を使用します。
ステップ 1: アナリティクス 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
という名前のファイルを 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: サンプルを実行する
Analytics API を有効にして、PHP 用の Google API クライアント ライブラリをインストールし、サンプル ソースコードを設定したら、サンプルを実行できるようになります。
次のコマンドを使用してサンプルを実行します。
php HelloAnalytics.php
以上の手順が完了すると、サンプルは、承認済みユーザーの最初の Google アナリティクス ビュー(プロファイル)の名前と、過去 7 日間のセッション数を出力します。
承認済みの Analytics サービス オブジェクトを使用して、 Management API リファレンス ドキュメントにあるコードサンプルをすべて実行できます。たとえば、 accountSummaries.list メソッドを使用するようにコードを変更してみましょう。