このチュートリアルでは、アナリティクス Reporting API v4 にアクセスする手順を詳しく説明します。
1. API を有効にする
アナリティクス Reporting API v4 を使用するには、まずセットアップ ツールの手順に沿って Google API Console でプロジェクトを作成し、API を有効にして、認証情報を作成する必要があります。
認証情報を作成
- [サービス アカウント] ページを開きます。画面のメッセージに従って、プロジェクトを選択します。
- [ サービス アカウントを作成] をクリックして、サービス アカウントの名前と説明を入力します。デフォルトのサービス アカウント ID を使用することも、別の一意の ID を選択することもできます。入力したら、[作成] をクリックします。
- 以降の [サービス アカウントの権限(オプション)] セクションは必須ではありません。[続行] をクリックします。
- [ユーザーにこのサービス アカウントへのアクセスを許可] 画面で、[キーの作成] セクションまで下にスクロールします。[ キーを作成] をクリックします。
- 表示されたサイドパネルで、キーの形式を選択します。JSON をおすすめします。
- [作成] をクリックします。新しい公開鍵と秘密鍵のペアが生成され、パソコンにダウンロードされます。この鍵は再発行できませんので、安全に保管する方法については、サービス アカウント キーの管理をご覧ください。
- [秘密鍵がパソコンに保存されました] ダイアログで [閉じる] をクリックし、[完了] をクリックしてサービス アカウントの表に戻ります。
Google アナリティクス アカウントにサービス アカウントを追加
新規作成したサービス アカウントのメールアドレスは、次のようになります。
quickstart@PROJECT-ID.iam.gserviceaccount.com
このメールアドレスは、API を使ってアクセスする Google アナリティクスのビューにユーザーを追加する際に使用します。このチュートリアルでは、読み取りと分析の権限のみが必要です。
2. クライアント ライブラリをインストールする
PHP 用 Google API クライアント ライブラリは、Composer を使用して取得できます。
composer require google/apiclient:^2.0
3. サンプルをセットアップする
HelloAnalytics.php
という名前のファイルを 1 つ作成する必要があります。このファイルには下記のサンプルコードが含まれます。
- 次のソースコードをコピーするかダウンロードして、
HelloAnalytics.php
にします。 - 以前にダウンロードした
service-account-credentials.json
をサンプルコードと同じディレクトリに移動します。 VIEW_ID
の値を置き換えます。ビュー ID は、Account Explorer で確認できます。
HelloAnalytics.php
<?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"); } } } } }
4. サンプルを実行する
次のコマンドを使用してサンプルを実行します。
php HelloAnalytics.php
以上の手順が完了すると、サンプルコードによって、指定されたビューの過去 7 日間のセッション数が出力されます。