Google AnalyticsのデータをAPI経由で取り出すとかできるらしい。しかも随分と昔から…Version4ってどんだけ昔からだったんだという…
これに従ってやっていきます。
Google Cloud Platformでプロジェクトを作る
最近のGoogleはみんなGoogle Cloud Platformですわー。
アカウントの追加
でこのプロジェクトを操作できるアカウントを追加する。
ときて
サービス アカウント名とサービス アカウントの説明を入力して作成。
で、このアカウントにロールを付与。とりあえずオーナー入れておけばいいんじゃないのっていう。
で、キーの作成→JSONでキーファイルがダウンロードされる。
これでアカウント追加完了。
Google Analyticsの管理画面で先ほど作成したアカウントに権限を与える
GoogleAnalyticsの管理画面に行き、ビューを選び「管理」の所から「ユーザー管理を表示」を選択。
右上の「+」から先ほど作ったアカウントのメールアドレスを入れる。権限は、「表示と分析」だけでいいでしょう。
PHPのライブラリをインストールして、サンプルを動かす
ファイルの設置
PHPが使えるサーバーに入って、コマンドラインからcomposerを使ってGoogleが提供してるPHPライブラリを
composer require google/apiclient:^2.0
とインストールする。
既にGoogleがサンプルを用意してくれてるので、ここから取得。HelloAnalytics.phpというファイルが得られるのでサーバーに送る。
アカウントのセットアップ
先ほどの「キーを作成」で取得したjsonファイルを service-account-credentials.json としてHelloAnalytics.phpと同じところにアップする。
HelloAnalytics.phpの44行目当たりにある、
<?php function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
の<REPLACE_WITH_VIEW_ID>を取得する。https://ga-dev-tools.appspot.com/account-explorer/?hl=ja に移動してIDを取得する。
この作業をしたら、HelloAnalytics.phpを動かす。
$ php HelloAnalytics.php PHP Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "Analytics Reporting API has not been used in project 32xxxxxxx8237 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=329609518237 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.", "errors": [ { "message": "Analytics Reporting API has not been used in project 32xxxxxxx8237 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=329609518237 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.", "domain": "usageLimits", "reason": "accessNotConfigured", "extendedHelp": "https://console.developers.google.com" } ], "status": "PERMISSION_DENIED" } }
…と、エラーが出る。
URLが表示されるので、アクセスすると
とでるので、「有効にする」を押す。
…と、ここまでで動くようになったけど、なんかデータ取れなかった。
なんか、サンプルのHelloAnalytics.phpがおかしい
このgetReportが
<?php function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "12345678"; // 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 ); }
ってなってるけど、この記事を見ると $dimentionと$orderbyを入れているし…
<?php function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "88097852"; // $VIEW_ID = "52492899"; // 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"); $dimention = new Google_Service_AnalyticsReporting_Dimension(); $dimention->setName( 'ga:landingPagePath' ); $orderby = new Google_Service_AnalyticsReporting_OrderBy(); $orderby->setFieldName( "ga:sessions" ); $orderby->setOrderType( "VALUE" ); $orderby->setSortOrder( "DESCENDING" ); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $request->setDimensions( array( $dimention ) ); $request->setOrderBys( $orderby ); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); }
これでPHP実行するとパスごとのセッション数が取得できた。