【サクッと始める】PHPでGoogle Analytics API【バッチ | Google認証画面を経由しないで認証】
2015/05/28
注意
本記事で使っているライブラリ「google-api-php-client」はバージョン0.6.6です。
GitHubにある最新の物は動かないようです。
古いライブラリ(0.6.6)は下記リンクからダウンロードできます。
Downloads – google-api-php-client – Google APIs Client Library for PHP – Google Project Hosting
ここから本題
webじゃなくてバッチプログラムを動かして、GAのデータを取得するような場合に利用するパターン。(cronに仕込むとか。)
※webアプリからの実行は下記のリンクからどうぞ
【サクッと始める】PHPでGoogle Analytics API(WEBアプリケーション) – For Want Of A Better Word
事前準備
APIのON とかはWEBアプリ編の事前準備参照。(こちら)
クライアントIDとかが、WEBとは違う。
アプリケーションを登録してClientIDを。。というのではなくて、
サービスアカウントなるものを作成して、そのアカウントの
- 秘密鍵ファイル(private key)
- クライアントID(Client ID)
- メールアドレス(Email Adress)
を持って認証する方式らしい。
サービスアカウントの作成方法はこちら(2014/09/26更新:画面が変わっていた…)
【PHP】【Google Api】(バッチ)接続情報取得のためサービスアカウントの作成 – For Want Of A Better Word
ということで、Google Apis Console(ここ)から、Service Accountを作成する。
これで必要な情報が揃う。
ソースコード
WEBアプリケーション編のチュートリアルの認証部分だけService Accoutnでの認証に変更したのが下記。
※ライブラリはこちら
(1)〜(5)までを設定してもらえれば動くはず。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<?php // STEP1 require_once("google-api-php-client/src/Google_Client.php"); require_once("google-api-php-client/src/contrib/Google_AnalyticsService.php"); /*---- サービスアカウントでの認証部分 -----*/ // Set your client id, service account name, and the path to your private key. // For more information about obtaining these keys, visit: // https://developers.google.com/console/help/#service_accounts const CLIENT_ID= '';//★(1) APIsコンソール ServiceアカウントのClient ID const SERVICE_ACCOUNT_NAME = '';//★(2)APIsコンソールのEmail address // Make sure you keep your key.p12 file in a secure location, and isn't // readable by others. const KEY_FILE = ''; //(3)★Serviceアカウント作成時にダウンロードした秘密鍵 // Load the key in PKCS 12 format (you need to download this from the // Google API Console when the service account was created. $client = new Google_Client(); $key = file_get_contents(KEY_FILE); $client->setClientId(CLIENT_ID); $client->setAssertionCredentials(new Google_AssertionCredentials( SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/analytics'), //★Service Accountのsampleだと"auth/prediction"となっている所をanalyticsに修正 $key) ); /*---- /サービスアカウントでの認証部分 -----*/ $analytics = new Google_AnalyticsService($client); runMainDemo($analytics); function runMainDemo(&$analytics) { try { // Step 2. Get the user's first view (profile) ID. $profileId=''; //(4)★取得したいプロファイルID if (isset($profileId)) { // Step 3. Query the Core Reporting API. $results = getResults($analytics, $profileId); // Step 4. Output the results. var_dump($results); } } catch (apiServiceException $e) { // Error from the API. print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage(); } catch (Exception $e) { print 'There wan a general error : ' . $e->getMessage(); } } function getFirstprofileId(&$analytics) { $accounts = $analytics->management_accounts->listManagementAccounts(); if (count($accounts->getItems()) > 0) { $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); $webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId); if (count($webproperties->getItems()) > 0) { $items = $webproperties->getItems(); $firstWebpropertyId = $items[0]->getId(); $profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId); if (count($profiles->getItems()) > 0) { $items = $profiles->getItems(); return $items[0]->getId(); } else { throw new Exception('No views (profiles) found for this user.'); } } else { throw new Exception('No webproperties found for this user.'); } } else { throw new Exception('No accounts found for this user.'); } } function getResults(&$analytics, $profileId) { //(5)★適当にmetricsとdimentionsを設定 $optParams = array( 'dimensions'=> 'ga:pageTitle,ga:pagePath', 'sort'=> '-ga:visits', 'max-results' => '25' ); return $analytics->data_ga->get( 'ga:' . $profileId, //ids 必須 '2013-06-03', //start-date 必須 '2013-08-03', //end-date 必須 'ga:visits',//metrics必須 $optParams ); } |
関連記事
-
-
Googleのクロスサイトスクリプティング勉強ページに挑戦
https://xss-game.appspot.com/ むむむ、なんとかLe …
-
-
【SEO】Google検索結果順位とクリック率の関係
WEBマスターツールを見ていてちょっと気になったので1-10位毎の平均クリック率 …
-
-
【Googleトレンド】【Casperjs】急上昇中キーワードをスクレイピングで取得 – (2) Casperjsのインストール
ということで続き。下記を参考に。 【参考】http://thesportsbus …
-
-
SEO_メモ_WEB担当フォーラム「SEOのエキスパート5人にいろいろ聞いてみた 2014」
タイトルに釣られて読んだ。気になった所メモ。 「SEOのエキスパート5人にいろい …
-
-
【サクッと始める】PHPでGoogle Analytics API(WEBアプリケーション)
注意 ①本記事で使っているGoogleAPI用PHPライブラリ「google-a …