Created
February 18, 2016 06:28
-
-
Save rakuishi/54a9ce68cbee81b1fc4b to your computer and use it in GitHub Desktop.
Google Analytics API Client with ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 参考 | |
# * https://developers.google.com/google-apps/calendar/quickstart/ruby | |
# * https://github.com/google/google-api-ruby-client/blob/master/samples/cli/lib/samples/analytics.rb | |
# * https://gist.github.com/rakuishi/5010ee819260cdd32a15 | |
# $ gem install google-api-client | |
require 'googleauth' | |
require 'googleauth/stores/file_token_store' | |
require 'google/apis/analytics_v3' | |
require 'fileutils' | |
require 'Date' | |
# Google Developers Console => 認証情報 => Create credentials => OAuth クライアント ID から作成する | |
CLIENT_SECRETS_PATH = 'client_secret.json' | |
CREDENTIALS_PATH = "#{ENV['HOME']}/.config/google/credentials.yaml" | |
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob' | |
SCOPE = Google::Apis::AnalyticsV3::AUTH_ANALYTICS | |
VIEW_ID = 'VIEW_ID' | |
def authorize | |
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH)) | |
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH) | |
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH) | |
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) | |
user_id = 'default' | |
credentials = authorizer.get_credentials(user_id) | |
if credentials.nil? | |
url = authorizer.get_authorization_url(base_url: OOB_URI) | |
puts "Open the following URL in the browser and enter the resulting code after authorization" | |
puts url | |
code = gets | |
credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI) | |
end | |
credentials | |
end | |
service = Google::Apis::AnalyticsV3::AnalyticsService.new | |
service.authorization = authorize | |
result = service.get_ga_data( | |
"ga:#{VIEW_ID}", | |
Date.today.prev_day(7).to_s, | |
Date.today.to_s, | |
'ga:screenviews', | |
dimensions: 'ga:screenName', | |
sort: '-ga:screenviews', | |
max_results: 10, | |
filters: 'ga:screenName=~^Screen/Name/.+?$' | |
) | |
result.rows.each do |row| | |
if matched = /^Screen\/Name\/(.+?)$/.match(row[0]) | |
puts "name: #{matched[1]}, count: #{row[1]}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment