Google Analytics のデータをRubyで取得 (Google API Clientを利用)

Bookmark this on Google Bookmarks
LINEで送る
Pocket

Google API Client
https://github.com/google/google-api-ruby-client

参考
http://blog.twygmbh.ch/google-analytics-api-access-with-ruby/
http://www.karakaram.com/google-analytics-api-batch#create-new-project

以下3つを環境に合わせて書き換える
SERVICE_ACCOUNT_EMAIL_ADDRESS
PATH_TO_KEY_FILE
PROFILE

# encoding: utf-8
Encoding.default_external="utf-8"
Encoding.default_internal="utf-8"
require 'google/api_client'

# set up a client instance
  client  = ::Google::APIClient.new(
    :application_name => 'APP NAME',
    :application_version => '1.0')
  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_ADDRESS',
      :signing_key          => Google::APIClient::KeyUtils.load_from_pkcs12('PATH_TO_KEY_FILE', 'notasecret')
  ).tap { |auth| auth.fetch_access_token! }

  api_method = client.discovered_api('analytics','v3').data.ga.get

  # make queries
  result = client.execute(:api_method => api_method, :parameters => {
      'ids'        => 'ga:PROFILE',
      'start-date' => "7daysAgo",
      'end-date'   => "today",
      'dimensions' => 'ga:day',
      'metrics'    => 'ga:users'
  })

  result.data.rows.each_with_index do |(key, value), i|
    p key.to_s + "日:" + value.to_s + "人"
  end