へっぽこエンジニアの日誌

へっぽこエンジニアからのレベルアップをはかる

Rubyからgoogle Analyticsのデータを取得する

google apis consoleにアクセスし、プロジェクトを作成。 その後、serviceメニューからanalytics apiをonにする。 API Accessメニューから、アプリを作成し、Certificateでアカウントを作成する。 作成時にできたprivatekey.p12をダウンロードしておく。

アカウント作成時のアドレスyourapp@developer.gserviceaccount.comをanalyticsのユーザーとして登録。

これで準備は完了。

ライブラリをインストールする。

1
gem install google-api-client

サンプルを使う。

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
# Inspired by https://gist.github.com/3166610
require 'google/api_client'
require 'date'

# Update these to match your own apps credentials
service_account_email = 'yourapp@developer.gserviceaccount.com' # Email of service account
key_file = 'privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = '123456' # Analytics profile ID.


client = Google::APIClient.new()

# Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => 'https://www.googleapis.com/auth/analytics.readonly',
  :issuer => service_account_email,
  :signing_key => key)

# Request a token for our service account
client.authorization.fetch_access_token!

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

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

visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => { 
  'ids' => "ga:" + profileID, 
  'start-date' => startDate,
  'end-date' => endDate,
  'metrics' => "ga:visits",
})

プロファイルIDは日本語のanalytics画面だと、「ビュー ID 」となっているので、注意が必要。