Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kazuph
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuph/9246411 to your computer and use it in GitHub Desktop.
Save kazuph/9246411 to your computer and use it in GitHub Desktop.
Google Analytics から情報を引っ張ってくるスクリプト。初回はブラウザで認証して、以降はファイルに保存した認証情報を使用する。
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment