Ruby
GoogleAnalytics

Google Analyticsの情報をAPI経由で取得するスクリプト。

More than 5 years have passed since last update.

メモ

Google Analytics から情報を引っ張ってくるスクリプト。初回はブラウザで認証して、以降はファイルに保存した認証情報を使用する。

Google consoleなどの手順は

http://blog.naberon.jp/post/2013/08/25/google-analytics-api/

の通りにやってできました。


analytics.rb

#!/usr/bin/env ruby

# coding : utf-8

# 参考
# https://github.com/google/google-api-ruby-client
# https://github.com/google/google-api-ruby-client-samples/tree/master/adsense
# https://developers.google.com/api-client-library/ruby/guide/aaa_oauth
# http://blog.naberon.jp/post/2013/08/25/google-analytics-api/

# こっちのモジュールも良さそう
# http://tsuchikazu.net/googel_analytics_gar/

require 'pp'
require 'json'
require 'pry'

require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'

CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"

# Analytics profile ID.
# https://www.google.com/analytics/web/#home/a42353636w43552078pXXXXXXXX/
# なURLのpのあと数字がProfile ID
profileID = 'XXXXXXXX'

client = Google::APIClient.new(
:application_name => 'TestProject',
:application_version => '0.0.1'
)

analytics = client.discovered_api('analytics', 'v3')

authfile = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)

unless authfile.authorization.nil?
client.authorization = authfile.authorization
else
# ここでDLしたJSONを読み込んでいるので同じディレクトリにclient_secrets.jsonを置いておくこと
client_secrets = Google::APIClient::ClientSecrets.load

flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/analytics.readonly']
)

client.authorization = flow.authorize
authfile.write_credentials(client.authorization.dup) # 認証情報をファイルに保存
end

startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")

result = client.execute(
:api_method => analytics.data.ga.get,
:parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
'metrics' => 'ga:visitors,ga:visits,ga:pageviews',
'dimensions' => 'ga:pagePath,ga:pageTitle',
'sort' => '-ga:pageviews'
}
)

body = JSON.parse(result.response.body)
body['rows'].each do |row|
pp row
end