Google Analytics Reporting API V4 を使う②

シリーズ2回目は、サーバーでの作業とサンプルを実行してみます。

① Google API Console と Google Analytics での作業
② Google API PHPクライアントインストールとデモ
③ WordPressで使えそうなものを作成する

***

今回は、サーバーにGoogle API PHPクライアントライブラリをインストールします。
※ここではバリューサーバーにインストールします。

composer

バリューサーバーにcomposer はインストールされているのですが、WP-CLI 同様にphp cli版をあてるべく、aliasをセットします。

~/.bashrc#alias composer='php71cli /usr/bin/composer'
alias composer='php56cli /usr/bin/composer'

※後のインストールで、php extention 不足でエラーになる場合は、php56cli をあてます。

PHPのエクステンションを確認するには?

command$ composer show -p

PHP用のGoogle APIクライアント取得

インストールするディレクトリに移動し、composerを使用して取得します。

※想定
・/vitual/xxx/yyy/google-api-php-client/ ここにGoogleAPIクライアントをインストール

command[google-api-php-client]$ composer require google/apiclient:^2.0

/vitual/xxx/yyy/google-api-php-client/vender/... が作成されます。

※APIをダウンロードする場合はこちら。
https://github.com/google/google-api-php-client.git

command[google-api-php-client]$ git clone -b
[インストールするディレクトリの上]$ git clone https://github.com/google/google-api-php-client.git
[インストールするディレクトリの上]$ cd ..
[google-api-php-client]$ ls
CONTRIBUTING.md README.md composer.json phpunit.xml.dist style
LICENSE UPGRADING.md examples src tests
[google-api-php-client]$ composer install

サービスアカウント秘密鍵JSONファイルの配置

前回認証情報の作成でダウンロードされた秘密鍵JSONファイルをサーバーへ配置します。

ここでは、以下↓ にアップしました。
・/vitual/xxx/yyy/google-api-php-client/xxxxx.json

※配置場所やファイル名は変更してもそのままでもok。後のプログラムで requiare できればokです。

デモ

ソースコード

はじめてのアナリティクス Reporting API V4: サービス アカウント向け PHP クイックスタート より
・HelloAnalytics.php
を試してみます。

ソースコード(HelloAnalytics.php)
ソースコード(HelloAnalytics.php)<!--?php

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

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);

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_AnalyticsReporting($client);

return $analytics;
}

function getReport($analytics) {

// Replace with your view ID, for example XXXX.
$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 );
}

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( $metricHeaders ) && $j < count( $metrics ); $j++) { $entry = $metricHeaders[$j]; $values = $metrics[$j]; print("Metric type: " . $entry->getType() . "\n" );
for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
$value = $values->getValues()[ $valueIndex ];
print($entry->getName() . ": " . $value . "\n");
}
}
}
}
}

■変更箇所
・4行目:インストールしたGoogleAPIクライアントライブラリのautoload.phpをあてます。
【変更前】require_once __DIR__ . '/vendor/autoload.php';
【変更後】require_once '/virtual/xxx/yyy/google-api-php-client/vendor/autoload.php';

・17行目:秘密鍵JSONファイルをあてます。
【変更前】$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
【変更後】$KEY_FILE_LOCATION = '/virtual/xxx/yyy/google-api-php-client/service-account-credentials.json';

・32行目:前回Google Analytics の View ID を確認で確認した View ID をセットします。
【変更前】$VIEW_ID = "";
【変更後】$VIEW_ID = "xxxxx";

動かしてみる!

変更したHelloAnalytics.phpをサーバーへアップして実行します。

■コマンドから

command$ php56cli HelloAnalytics.php

過去7日間(ソース36-37行目で指定)のセッション数が表示されます!

■公開エリアにアップして、ブラウザで確認
https://sakidesign.com/demo/HelloAnalytics.php

以上、お疲れさまでした。
次回 Google Analytics Reporting API V4 を使う③ は、「WordPressで使えそうなものを作成する」の予定です。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です