Skip to content

Instantly share code, notes, and snippets.

@t-kashima
Last active October 27, 2015 03:01
Show Gist options
  • Save t-kashima/166fa5a69daa83d2696c to your computer and use it in GitHub Desktop.
Save t-kashima/166fa5a69daa83d2696c to your computer and use it in GitHub Desktop.
Google Analyticsから情報を取ってくるスクリプト
# coding: utf-8
require 'pp'
require 'json'
require 'yaml'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
CREDENTIAL_STORE_FILE = 'store-oauth2.json'
config = YAML.load_file('config.yml')
# Initialize the client.
client = Google::APIClient.new(
:application_name => 'Google Analytics',
:application_version => '0.0.1'
)
analytics = client.discovered_api('analytics', 'v3')
file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)
if file_storage.authorization.nil?
# read the 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(file_storage)
else
client.authorization = file_storage.authorization
end
# 新規訪問者数
result = client.execute(
:api_method => analytics.data.ga.get,
:parameters => {
'ids' => config['ga']['property_id'],
'start-date' => '2015-09-26',
'end-date' => '2015-10-26',
'metrics' => 'ga:newVisits',
}
)
# p result.response.body
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