A client asked us to show Google Analytics data on one of our sites, so that they would not have to leave our site to get that data. I decided that the best way to do this is to import the requested Google Analytics metrics daily at 3:00 a.m. This way, we query Google Analytics only once per day (rather than on every page request). There is a quota policy on querying Google Analytics data, and this ensures that we don’t come close to filling that quota.
The example below borrows from the Google Analytics curl tester.
There are a few Ruby libraries for accomplishing this task, but my needs were so simple that I preferred to retrieve the XML from Google Analytics and get the metrics from XPath queries.
Google Analytics metrics, request and response, and XML are well-documented.
require 'net/http'
require 'uri'
require 'rexml/document'
http = Net::HTTP.new('www.google.com',443)
http.use_ssl = true
# in order to query Google Analytics, you have to log into Google and acquire an authorization token
path = '/accounts/ClientLogin'
data = {'Email' => 'YOUR_EMAIL',
'Passwd' => 'YOUR_PASSWORD',
'accountType' => 'GOOGLE',
'source' => 'GA-curl-tester',
'service' => 'analytics'}
resp,data = http.post(path,data.to_query)
auth_token = resp.body.split("\n").detect{|x|x=~/^Auth=/}.sub(/^Auth=/,'')
# now use the authorization token get the GA data
data = {'ids' => 'ga:YOUR_ACCOUNT_ID',
'metrics' => 'ga:visitors,ga:pageviews',
'start-date' => '2011-01-01',
'end-date' => Date.yesterday.strftime('%Y-%m-%d')}
path = "/analytics/feeds/data/?#{data.to_query}"
h = {'Authorization' => "GoogleLogin auth=#{auth_token}"}
resp,data = http.get(path,h)
ga_xml_string = resp.body
doc = REXML::Document.new(ga_xml_string)
# you can store these variables in a database or handle them in whatever manner you see fit
ga_visitors=REXML::XPath.first(doc,"//dxp:aggregates/dxp:metric[@name='ga:visitors']").attributes['value']
ga_pageviews=REXML::XPath.first(doc,"//dxp:aggregates/dxp:metric[@name='ga:pageviews']").attributes['value']
