Tôi cũng sử dụng đá quý google-api-ruby-client và thiết lập nó giống như cách được nêu trong liên kết bạn đã cung cấp (https://gist.github.com/joost/5344705).
Chỉ cần làm theo các bước được nêu trong liên kết để thiết lập một ứng dụng khách Google Analytics:
# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = '...' # looks like [email protected]
PATH_TO_KEY_FILE = '...' # the path to the downloaded .p12 key file
PROFILE = '...' # your GA profile id, looks like 'ga:12345'
require 'google/api_client'
# set up a client instance
client = Google::APIClient.new
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::PKCS12.load_key(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' => PROFILE,
'start-date' => Date.new(1970,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/url/to/user'
})
puts result.data.rows.inspect
Để hiển thị thống kê cho trang của người dùng trong ứng dụng, bạn phải điều chỉnh số liệu và lọc các tham số khi thực hiện truy vấn. Ví dụ: truy vấn ở trên sẽ trả lại đối tượng kết quả chứa tất cả số lần truy cập trang cho trang có url example.com/url/to/user.
Nên biết trước: câu trả lời này đã được viết trong một thời gian dài trước đây và Google phát hành một phiên bản tương thích mới của đá quý. Vui lòng tham khảo https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md
Legato đã không bao giờ bị bỏ rơi và là cách tốt hơn để tạo các truy vấn có thể duy trì đối với API GA. Tôi đã yêu cầu tác giả của Gist đó sửa lại những ghi chú sai lầm của anh ta. Legato đã _always_ hỗ trợ GA API phiên bản 3. https://github.com/tpitale/legato/commit/0def82f9bdb9cf259d4d91d5bd2f17759231bb29 –