はじめてのアナリティクス Reporting API v4: ウェブ アプリケーション向け PHP クイックスタート

このチュートリアルでは、アナリティクス Reporting API v4 にアクセスする手順を詳しく説明します。

1. API を有効にする

アナリティクス Reporting API v4 を使用するには、まずセットアップ ツールの手順に沿って Google API Console でプロジェクトを作成し、API を有効にして、認証情報を作成する必要があります。

注: ウェブ クライアント ID またはインストール済みアプリケーション クライアントを作成するには、同意画面でプロダクト名を設定する必要があります。まだ行っていない場合は、同意画面を設定するように求められます。

認証情報を作成

  • [認証情報] ページを開きます。
  • [認証情報を作成] をクリックし、[OAuth クライアント ID] を選択します。
  • [アプリケーションの種類] で [ウェブ アプリケーション] を選択します。
  • クライアント ID に「quickstart」という名前を付け、[作成] をクリックします。
  • [承認済みの JavaScript 生成元] は空欄のままにしておきます。このチュートリアルでは必要ありません。
  • [承認済みのリダイレクト URI] を http://localhost:8080/oauth2callback.php に設定します。
  • [作成] をクリックします。

[認証情報] ページで、新しく作成したクライアント ID をクリックし、[JSON をダウンロード] をクリックして、client_secrets.json という名前で保存します。このファイルは、チュートリアルの後半で使用します。

2. クライアント ライブラリをインストールする

Composer を使用して PHP 用の Google API クライアント ライブラリを取得できます。

composer require google/apiclient:^2.0

3. サンプルをセットアップする

次の 2 つのファイルを作成する必要があります。

  • index.php は、ユーザーがアクセスするメインページです。
  • oauth2callback.phpOAuth 2.0 レスポンスを処理します。

index.php

このファイルには、Google アナリティクス API へのクエリ送信と、結果の表示を行うメインロジックが含まれます。

  • 最初のサンプルコードを index.php にコピーまたはダウンロードします。
  • VIEW_ID の値を置き換えます。ビュー ID は、Account Explorer で確認できます。
<?php

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

session_start();

$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.
  printResults($response);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


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


oauth2callback.php

このファイルは、OAuth 2.0 レスポンスを処理します。2 つ目のサンプルコードをコピーするかダウンロードして、oauth2callback.php に保存します。

<?php

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

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


4. サンプルの実行

PHP を提供するように構成されたウェブサーバーでサンプルを実行します。PHP 5.4 以降を使用している場合は、次のコマンドを実行して、PHP の組み込みテスト ウェブサーバーを使用できます。

php -S localhost:8080 -t /path/to/sample

次に、ブラウザで http://localhost:8080 にアクセスします。

以上の手順が完了すると、サンプルコードによって、指定されたビューの過去 7 日間のセッション数が出力されます。