Googleアナリティクスのデータを必要個所だけ取得したかったので、JavaScriptでのアナリティクスAPIの使い方を少し調べてみました。
Google Developers Consoleの設定
以下のページを参考にしました。
Hello Analytics API: JavaScript quickstart for web applications | Analytics Core Reporting API | Google Developers
Googleアカウントでログインした状態で、こちらのページにアクセスします。
Google Developers ConsoleでアナリティクスAPIを使えるように設定します。
続行をクリック。
「My project」という名前のプロジェクトが作成され、Analytics API が有効化されます。
認証情報に進むをクリック。
認証情報画面が開かれるので、新しいクライアントIDを作成をクリック。
アプリケーションの種類は作るものによって選択してください。
今回はウェブアプリケーションを選択して同意画面を設定をクリック。
必須項目のサービス名を入力して保存をクリック。
このサービス名はユーザーに認証を求めるときに表示されます。
サービスを使用するドメインを指定します。
初期はプロトコルがhttps:になっているので注意して下さい。
例えば「cly7796.net」内で使用する場合は以下のように入力します。
入力が完了したらクライアントIDを作成をクリック。
クライアントIDが作成されました。
クライアントIDはのちほど使用するので、どこかにメモしておいてください。
ファイルの作成
表示するページのHTMLとJavaScriptを記述します。
基本的には参考ページと同じ形です。
HTML
<button id="auth-button" hidden>認証ボタン</button><br /> <textarea cols="80" rows="20" id="query-output"></textarea> <script src="./sample.js"></script> <script src="https://apis.google.com/js/client.js?onload=authorize"></script>
JavaScript
// Replace with your client ID from the developer console.
var CLIENT_ID = 'クライアントIDをここに入れる';
// Set authorized scope.
var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
function authorize(event) {
// Handles the authorization flow.
// `immediate` should be false when invoked from the button click.
var useImmdiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: useImmdiate
};
gapi.auth.authorize(authData, function(response) {
var authButton = document.getElementById('auth-button');
if (response.error) {
authButton.hidden = false;
}
else {
authButton.hidden = true;
queryAccounts();
}
});
}
function queryAccounts() {
// Load the Google Analytics client library.
gapi.client.load('analytics', 'v3').then(function() {
// Get a list of all Google Analytics accounts for this user
gapi.client.analytics.management.accounts.list().then(handleAccounts);
});
}
function handleAccounts(response) {
// Handles the response from the accounts list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account.
var firstAccountId = response.result.items[0].id;
// Query for properties.
queryProperties(firstAccountId);
} else {
console.log('No accounts found for this user.');
}
}
function queryProperties(accountId) {
// Get a list of all the properties for the account.
gapi.client.analytics.management.webproperties.list({
'accountId': accountId
})
.then(handleProperties)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProperties(response) {
// Handles the response from the webproperties list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account
var firstAccountId = response.result.items[0].accountId;
// Get the first property ID
var firstPropertyId = response.result.items[0].id;
// Query for Views (Profiles).
queryProfiles(firstAccountId, firstPropertyId);
} else {
console.log('No properties found for this user.');
}
}
function queryProfiles(accountId, propertyId) {
// Get a list of all Views (Profiles) for the first property
// of the first Account.
gapi.client.analytics.management.profiles.list({
'accountId': accountId,
'webPropertyId': propertyId
})
.then(handleProfiles)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProfiles(response) {
// Handles the response from the profiles list method.
if (response.result.items && response.result.items.length) {
// Get the first View (Profile) ID.
var firstProfileId = response.result.items[0].id;
// Query the Core Reporting API.
queryCoreReportingApi(firstProfileId);
} else {
console.log('No views (profiles) found for this user.');
}
}
function queryCoreReportingApi(profileId) {
// Query the Core Reporting API for the number sessions for
// the past seven days.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '7daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions'
})
.then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
// Add an event listener to the 'auth-button'.
document.getElementById('auth-button').addEventListener('click', authorize);
アナリティクスAPIのデモページ(クライアントIDを外しているので動作しません。)
作成したページをサーバへアップしてアクセスすると、以下のように表示されます。
認証ボタンをクリックすると認証画面が表示されます。
テスト の部分は登録したサービス名が表示されます。
取得したいGoogleアナリティクスのアカウントにログインして、承認するをクリックします。
データを取得して表示できました。
取得データ・期間を変更する
指定した年月から過去1年間のデータを取得して、データを成型して表示させてみます。
取得するデータ(metrics)は
bounces、
pageviews、
sessionDuration、
visitors、
visitsを、
dimensionsには各月ごとにデータを取得したいので、
year、
month
を指定します。
HTML
<button id="auth-button" hidden>認証ボタン</button><br /> <div id="output"></div> <script src="./sample2.js"></script> <script src="https://apis.google.com/js/client.js?onload=authorize"></script>
JavaScript
// 取得するメトリクスとディメンションとソートの指定
// メトリクスの指定
var metricsArr = ['ga:bounces', 'ga:pageviews', 'ga:sessionDuration', 'ga:visitors', 'ga:visits'];
var metricsData = '';
for (var i = 0; i < metricsArr.length; i++) {
metricsData += metricsArr[i] + ', ';
};
metricsData = metricsData.substr(0, metricsData.length - 2);
// ディメンションの指定
var dimensionsArr = ['ga:year', 'ga:month'];
var dimensionsData = '';
for (var i = 0; i < dimensionsArr.length; i++) {
dimensionsData += dimensionsArr[i] + ', ';
};
dimensionsData = dimensionsData.substr(0, dimensionsData.length - 2);
// ソートの指定
var sortData = 'ga:year';
// パラメータの取得
var param = location.search.replace('?', '').split('&');
var params = [];
for (var i = 0; i < param.length; i++) {
params[i] = param[i].split('=');
};
// 調査対象の年月を取得
var tgtdate;
for (var i = 0; i < params.length; i++) {
if(params[i][0] = 'date') {
tgtdate = params[i][1];
break;
}
};
// パラメータが無いときは前月を対象にする
if(tgtdate == undefined) {
var today = new Date();
var lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
var tgtyear = lastMonth.getFullYear();
var tgtmonth = lastMonth.getMonth() + 1;
var tgtday = lastMonth.getDate();
} else {
var tgtyear = parseFloat(tgtdate.slice(0, 4));
var tgtmonth = parseFloat(tgtdate.slice(4));
var tgtday = parseFloat(getNumOfDays(tgtyear, tgtmonth));
}
// 年月の期間取得
var start_date = (tgtyear - 1) + '-' + addZero(tgtmonth + 1, 2) + '-' + '01';
var end_date = tgtyear + '-' + addZero(tgtmonth, 2) + '-' + tgtday;
// その月が何日まであるか調べる関数
function getNumOfDays(year, month) {
return new Date(year,month,0).getDate();
};
// 数値の桁数揃えの関数
function addZero(num, digit) {
var no = String(num);
while(no.length < digit) {
no = '0' + no;
}
return no;
};
// Replace with your client ID from the developer console.
var CLIENT_ID = 'クライアントIDをここに入れる';
// Set authorized scope.
var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
function authorize(event) {
// Handles the authorization flow.
// `immediate` should be false when invoked from the button click.
var useImmdiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: useImmdiate
};
gapi.auth.authorize(authData, function(response) {
var authButton = document.getElementById('auth-button');
if (response.error) {
authButton.hidden = false;
}
else {
authButton.hidden = true;
queryAccounts();
}
});
}
function queryAccounts() {
// Load the Google Analytics client library.
gapi.client.load('analytics', 'v3').then(function() {
// Get a list of all Google Analytics accounts for this user
gapi.client.analytics.management.accounts.list().then(handleAccounts);
});
}
function handleAccounts(response) {
// Handles the response from the accounts list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account.
var firstAccountId = response.result.items[0].id;
// Query for properties.
queryProperties(firstAccountId);
} else {
console.log('No accounts found for this user.');
}
}
function queryProperties(accountId) {
// Get a list of all the properties for the account.
gapi.client.analytics.management.webproperties.list({
'accountId': accountId
})
.then(handleProperties)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProperties(response) {
// Handles the response from the webproperties list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account
var firstAccountId = response.result.items[0].accountId;
// Get the first property ID
var firstPropertyId = response.result.items[0].id;
// Query for Views (Profiles).
queryProfiles(firstAccountId, firstPropertyId);
} else {
console.log('No properties found for this user.');
}
}
function queryProfiles(accountId, propertyId) {
// Get a list of all Views (Profiles) for the first property
// of the first Account.
gapi.client.analytics.management.profiles.list({
'accountId': accountId,
'webPropertyId': propertyId
})
.then(handleProfiles)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProfiles(response) {
// Handles the response from the profiles list method.
if (response.result.items && response.result.items.length) {
// Get the first View (Profile) ID.
var firstProfileId = response.result.items[0].id;
// Query the Core Reporting API.
queryCoreReportingApi(firstProfileId, start_date, end_date, metricsData, dimensionsData, sortData);
} else {
console.log('No views (profiles) found for this user.');
}
}
function queryCoreReportingApi(profileId, start, end, metrics, dimensions, sort) {
// Query the Core Reporting API for the number sessions for
// the past seven days.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': start,
'end-date': end,
'metrics': metrics,
'dimensions': dimensions,
'sort': sort
})
.then(function(response) {
var getData = JSON.stringify(response.result, null, 2);
output(getData);
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
// Add an event listener to the 'auth-button'.
document.getElementById('auth-button').addEventListener('click', authorize);
function output(data) {
// データの変換
var data = JSON.parse(data);
var insert = '<table>';
// 各データの見出し追加
insert += '<tr>';
for (var i = 0; i < dimensionsArr.length; i++) {
insert += '<th>' + dimensionsArr[i] + '</th>';
};
for (var i = 0; i < metricsArr.length; i++) {
insert += '<th>' + metricsArr[i] + '</th>';
};
insert += '</tr>';
// 各データの追加
for (var i = 0; i < data['rows'].length; i++) {
// 各データを変数に格納
var year = data['rows'][i][0];
var month = data['rows'][i][1];
var bounces = data['rows'][i][2];
var pageviews = data['rows'][i][3];
var sessionDuration = data['rows'][i][4];
var visitors = data['rows'][i][5];
var visits = data['rows'][i][6];
insert += '<tr>';
insert += '<td>' + year + '</td>';
insert += '<td>' + month + '</td>';
insert += '<td>' + bounces + '</td>';
insert += '<td>' + pageviews + '</td>';
insert += '<td>' + sessionDuration + '</td>';
insert += '<td>' + visitors + '</td>';
insert += '<td>' + visits + '</td>';
insert += '</tr>';
};
insert += '</table>';
// ページに出力
document.getElementById('output').innerHTML = insert;
}
指定月から過去1年間のデータを取得するデモページ(クライアントIDを外しているので動作しません。)
基準にする年月はパラメータで?date=201501のように指定するようにしています。
パラメータが無い場合は前月を基準とします。
認証すると以下のように表示できました。
上記JavaScriptの164~169行目の各項目で、取得するデータの種類や期間を指定しています。
| ids | Googleアナリティクスのどのビューのデータを取得するか指定。必須。 |
|---|---|
| start-date | データ取得の開始日を指定。必須。 |
| end-date | データ取得の終了日を指定。必須。 |
| metrics | 取得したいデータの指定。必須。 |
| dimensions | 取得するデータの分類方法を指定。 例えばmonthを指定してデータを月毎で取得したり、userTypeを指定してデータを新規とリピーターで分けて取得したりできます。 |
| sort | 取得するデータの並び順の変更。 |
これら以外にも設定できますので、詳しくは以下をご確認ください。
Core Reporting API – Reference Guide | Analytics Core Reporting API | Google Developers
metricsとdimensionsの指定できる内容についてはこちら。
Dimensions & Metrics Explorer | Analytics Core Reporting API | Google Developers
注意点
サービスを使用するドメインを指定する形なので問題なさそう?かもですが、JavaScriptで実装した場合、クライアントIDがソース上で丸見えになります。
実際にサイト上で公開したりする場合、可能であればPHPなどクライアントIDが外から見られない形で実装するようにした方がよいかもしれません。
2015.08.15追記
上でも書いていますが、GoogleのAPIの場合、使用するドメインを指定してAPIを取得する形なので問題なさそうです。
指定するmetricsとdimensionsによっては、取得したデータとWeb版で見たデータに誤差が出ることがあるようです。
metricsとdimensionsの組み合わせによって起こるようなので、指定内容によっては注意が必要です。
【参考サイト】
- Hello Analytics API: JavaScript quickstart for web applications | Analytics Core Reporting API | Google Developers
- Core Reporting API – Reference Guide | Analytics Core Reporting API | Google Developers
- Dimensions & Metrics Explorer | Analytics Core Reporting API | Google Developers
- APIとWeb版でPV数や訪問数の違いについて – Google プロダクト フォーラム
- Google+ APIのOAuth認証によるログイン方法のまとめ: 小粋空間












コメントが承認されるまで時間がかかります。