闇雲に調べてもアレなので。。
公式リファレンスを参照して勉強することにしました。使用言語はJavaScriptでいきます。
前提条件
・GoogleアナリティクスAPIを使うために、client_idとapiKeyの取得に成功している。
・javascript_origin の項目には、動かすサーバのドメインに対応した値が入っているものとします。
例) htmlファイルがwww.example.com ドメインのサーバに格納されている場合、
javascript_originの値は、http://www.example.com
となります。
構成情報
必要なのは以下の3ファイルです。
・hello_analytics_api_v3.html – ボタン表示のためのhtmlです。
・hello_analytics_api_v3_auth.js – 認証ダイアログを使って、googleアカウントの認証を行うプログラムです。
・hello_analytics_api_v3.js – アナリティクスAPIの認証と、リクエストの発行、結果の表示を行うプログラムです。
プログラムの説明
以下にソースを示します(英語部分は拙訳)
hello_analytics_api_v3.html
<!DOCTYPE>
<html>
<head>
<title>Hello Google Analytics API</title>
</head>
<body>
<!-- ユーザの実行ボタン -->
<button id="authorize-button" style="visibility: hidden">Authorize</button><br/>
<button id="make-api-call-button" style="visibility: hidden">Get Sessions</button>
<!-- あとで作成するプログラム -->
<script src="hello_analytics_api_v3_auth.js"></script>
<script src="hello_analytics_api_v3.js"></script>
<!-- htmlが読み込まれたときに、最初に実行される関数を定義 -->
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>
hello_analytics_api_v3_auth.js
// アナリティクスAPIの認証を行う関数。
// scopes以外の値は、各自のアプリケーションによって変えてください。
var clientId = "各自のクライアントid";
var apiKey = "各自のapiKey";
var scopes = "https://www.googleapis.com/auth/analytics.readonly";
// ライブラリが読み込まれたあとで、最初に呼ばれる関数
// 以下、呼び出す関数は関数名を書いた次のセクション( ブレースで囲まれた部分 )に定義していく
function handleClientLoad() {
// 1. APIキーをセット
gapi.client.setApiKey(apiKey);
// 2. ユーザ認証の確認
window.setTimeout(checkAuth,1);
}
function checkAuth() {
// 今のユーザーの認証状態を確認するため、グーグルアカウントサービスを呼び出す
// handleAuthResult関数へ、以下の関数の結果を返却する
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
// ユーザーの認証が完了
// アナリティクスアカウントの情報を読み込む
loadAnalyticsClient();
} else {
// ユーザー認証が失敗
handleUnAuthorized();
}
}
// 認証されたユーザー
function handleAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var makeApiCallButton = document.getElementById('make-api-call-button');
// 'Get Sessions'ボタンを表示し、 'Authorize'ボタンを非表示
makeApiCallButton.style.visibility = '';
authorizeButton.style.visibility = 'hidden';
// 'Get Sessions'ボタンがクリックされた場合、makeAapiCall functionを実行
makeApiCallButton.onclick = makeApiCall;
}
// 認証されなかったユーザー
function handleUnAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var makeApiCallButton = document.getElementById('make-api-call-button');
// 'Authorize'ボタンを表示し、 'Get Sessions'ボタンを非表示
makeApiCallButton.style.visibility = 'hidden';
authorizeButton.style.visibility = '';
// 'Authorize'ボタンがクリックされた場合、handleAuthClick を実行
authorizeButton.onclick = handleAuthClick;
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function loadAnalyticsClient() {
// アナリティクスアカウントの情報を呼び出し、 その中でhandleAuthorized関数を実行する。
gapi.client.load('analytics', 'v3', handleAuthorized);
}
hello_analytics_api_v3.js
// 'Get Sessions' ボタンがクリックされたときに実行される関数
function makeApiCall() {
queryAccounts();
}
function queryAccounts() {
console.log('Querying Accounts.');
// 認証されたユーザーに紐付けられた全てのアナリティクスアカウントを取得
gapi.client.analytics.management.accounts.list().execute(handleAccounts);
}
function handleAccounts(results) {
if (!results.code) {
if (results && results.items && results.items.length) {
// 最初に登録されたアナリティクスアカウントidを取得
var firstAccountId = results.items[0].id;
// アカウントのウェブプロパティをリクエストする
queryWebproperties(firstAccountId);
} else {
console.log('No accounts found for this user.')
}
} else {
console.log('There was an error querying accounts: ' + results.message);
}
}
function queryWebproperties(accountId) {
console.log('Querying Webproperties.');
// アカウントの全てのウェブプロパティを取得する
gapi.client.analytics.management.webproperties.list({'accountId': accountId}).execute(handleWebproperties);
}
function handleWebproperties(results) {
if (!results.code) {
if (results && results.items && results.items.length) {
// 最初に登録されたアナリティクスアカウントidを取得
var firstAccountId = results.items[0].accountId;
// 最初のウェブプロパティを取得
var firstWebpropertyId = results.items[0].id;
// アカウントの最初のビューidを取得
queryProfiles(firstAccountId, firstWebpropertyId);
} else {
console.log('No webproperties found for this user.');
}
} else {
console.log('There was an error querying webproperties: ' + results.message);
}
}
function queryProfiles(accountId, webpropertyId) {
console.log('Querying Views (Profiles).');
// 最初のアナリティクスアカウントに紐付けられている全てのプロファイルidを取得
gapi.client.analytics.management.profiles.list({
'accountId': accountId,
'webPropertyId': webpropertyId
}).execute(handleProfiles);
}
function handleProfiles(results) {
if (!results.code) {
if (results && results.items && results.items.length) {
// 最初のプロファイルidを取得
var firstProfileId = results.items[0].id;
// Step 3. 実際のレポートを取得する
queryCoreReportingApi(firstProfileId);
} else {
console.log('No views (profiles) found for this user.');
}
} else {
console.log('There was an error querying views (profiles): ' + results.message);
}
}
function queryCoreReportingApi(profileId) {
console.log('Querying Core Reporting API.');
// アナリティクスのデータを取得
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '2012-03-03',
'end-date': '2012-03-03',
'metrics': 'ga:sessions'
}).execute(handleCoreReportingResults);
}
function handleCoreReportingResults(results) {
if (results.error) {
console.log('There was an error querying core reporting API: ' + results.message);
} else {
printResults(results);
}
}
function printResults(results) {
if (results.rows && results.rows.length) {
console.log('View (Profile) Name: ', results.profileInfo.profileName);
console.log('Total Sessions: ', results.rows[0][0]);
} else {
console.log('No results found');
}
}
流れとしては、
- Authorizeボタンをクリックして認証ダイアログへ遷移
- 情報入力してログイン
- Get Sessionsボタンをクリックしてプロファイル情報を取得、アナリティクスの解析データを取得する
といった感じです。
今回は、自サービス用に hello_analytics_api_v3.jsをカスタマイズしていきます。
解析データのリクエストプログラムは既にPerlで実装されているので、
1. ユーザープロファイル情報のリストを取得
2. html上にリストボックスとして表示
以上をできるようにします。