LoginSignup
12
13

More than 5 years have passed since last update.

laravelでGoogle Analytics APIに挨拶してみた

Posted at

導入

laravel 4.2で作成したWebアプリケーションでアクセスランキングとか作りたいと思い、Google Analytics APIに挨拶してみました。

ぶっちゃけApacheさんのアクセスログ抽出するのが一番楽な気がしますが、アプリケーションサーバーになんでもやらせたくなかったし、天下のGoogleさんのサービスに聞いて分かるならそっちの方が楽だし安心じゃないですか!

下記の記事を参考にしたので基本的なところは一緒ですが、少し変更があります。

Google Analytics API v3をPHPから利用する方法

OAuthアカウント作成と権限の設定

  • 事前にGoogle Analyticsに登録してトラッキングコード埋め込み
  • Google Developers Console に登録してOAuth 2.0のサービスアカウント作成
    • Google Developers Consoleに登録
    • 新規プロジェクトを作成
      • 鍵のファイル名になるのでスペース無い方が良い
    • 「APIと認証」の「API」でGoogle Analyticsを検索、ステータスをONに
    • 「APIと認証」の「認証情報」でOAuthの「新しいクライアントIDを作成」
    • 「サービスアカウント」を選択して「クライアントIDを作成」
    • 秘密鍵ファイル(〜.p12)を保存(※1)
    • 秘密鍵のパスワードを保存
    • サービスアカウントのメールアドレスをメモ(※2)
  • Google Analyticsの設定でサービスアカウントでAPI接続できるように登録
    • Google Analyticsの「アナリティクス設定」から「ユーザー管理」を選択
    • 「権限を付与するユーザー」のメールアドレスに(※2)のアドレスを入力
    • 「表示と分析」が選択されている事を確認して「追加」
    • 同時に「アナリティクス設定」の「ビュー設定」にあるビューIDをメモ(※3)

あとで使う情報

※1 => service_account_name
※2 => secret_key_file
※3 => profile_id

にそれぞれ対応します。

Google APIs Client Library for PHP 導入

Composerを使用したインストールの方法はここに書いてあります。
https://developers.google.com/api-client-library/php/start/installation

composer.json
"require": {
  "google/apiclient": "1.0.*@beta"
}    

適当にcomposer.jsonを編集してcomposer update
ちょっと時間がかかりました。

導入確認

app/routes.php
Route::get('googletest', function() {
  $client = new Google_Client();
  return var_dump($client);
});

でGoogle_Clientがダンプされれば問題なし。

Google Analytics APIさんに挨拶

秘密鍵ファイルの転送

(※2)の秘密鍵をサーバーに転送してapp/config/google/XXXXX.p12とかに置いておきます。

scp -i XXXXX.pem path/to/secret_key_file.p12 user@yourhost.com:

config作成

app/config/google.php
<?php

return array(
  'service_account_name' => '※1',
  'secret_key_file' => __DIR__ . '/google/secret_keyfile.p12',
  'profile_id' => '※3',
);

いざ挨拶

さっき紹介した記事からクラス名が下記のように変わっています。

new old
Google_Auth_AssertionCredentials Google_AssertionCredentials
Google_Service_Analytics Google_AnalyticsService

という訳で挨拶してみる。

app/routes.php
Route::get('googletest', function() {
  $client = new Google_Client();
  $client->setApplicationName("Google Analytics PHP Starter Application");
  $client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
    Config::get('google.service_account_name'),
    array('https://www.googleapis.com/auth/analytics'),    file_get_contents(Config::get('google.secret_key_file'))
  ));

  $today = date("Y-m-d");
  $lastMonth = date("Y-m-d", strtotime("-1 month"));
  $service = new Google_Service_Analytics($client);
  $result = $service->data_ga->get(
    'ga:' . Config::get('google.profile_id'),
    $lastMonth,
    $today,
    'ga:pageviews',
    array(
      'dimensions'  => 'ga:pageTitle,ga:pagePath',
      'sort'        => '-ga:pageviews',
      'max-results' => '10'
    )
  );
  return d($result);
});

これでページ別のアクセス数が結果に挿入されていれば成功です。
d()Kint導入で使えます。便利です。

終わりに

とりあえず挨拶が成功したのと参考記事から変更があったので勢いで書いてみました。
間違いなどありましたら是非コメントお願いします。(おしまい)

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13