本文介绍了如何提取 Google Analytics 统计信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google API Ruby 客户端是最佳选择吗?

我有一个网站 example.com 有用户,我希望他们在 example.com 上查看他们的谷歌分析统计数据,我该怎么做?

I have a site example.com with users and I want them to see their google analytics stats on example.com, how can I do it ?

我可以看到示例,但我不知道如何开始.

I can see the example but I'm not able to figure out how to begin.

推荐答案

我也使用 google-api-ruby-client gem 并按照链接中概述的相同方式进行设置您提供(https://gist.github.com/joost/5344705).

I also use the google-api-ruby-client gem and set it up about the same way that is outlined in the link you provided (https://gist.github.com/joost/5344705).

只需按照链接中列出的步骤设置 Google Analytics 客户端:

Just follow the steps outlined in the link to set up a Google Analytics client:

# 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

要在您的应用中显示用户页面的统计信息,您必须在进行查询时调整 metricsfilters 参数.例如,上面的查询将返回一个结果对象,其中包含带有 url example.com/url/to/user 的页面的所有综合浏览量.

To display statistics for a user's page in your app, you have to adjust the metrics and filters parameters when making the query. The query above for example will return a result object containing all pageviews for the page with url example.com/url/to/user.

警告:这个答案是很久以前写的,Google 发布了一个新的、不兼容的 gem 版本.请参考 https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md

Caveat: this answer was written a long time ago and Google released a new, incompatible version of the gem. Please consult https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md

这篇关于如何提取 Google Analytics 统计信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:54