如何获取Google Analytics统计数据?

16

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

我有一个名为 example.com 的网站,它有用户。我想让他们在 example.com 上看到他们的 Google Analytics 统计信息,我该怎么做?

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


1
Legato从未被放弃,并且是构建可维护的针对GA API查询的更好方式。我已要求该Gist的作者纠正他错误的注释。Legato一直支持GA API版本3。https://github.com/tpitale/legato/commit/0def82f9bdb9cf259d4d91d5bd2f17759231bb29 - Tony Pitale
1个回答

30

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

只需按照链接中概述的步骤设置Google Analytics客户端即可:

# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = '...' # looks like 12345@developer.gserviceaccount.com
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

要在您的应用程序中显示用户页面的统计信息,您需要在查询时调整指标筛选器参数。例如上面的查询将返回一个结果对象,其中包含页面example.com/url/to/user的所有页面查看次数。


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


@severin 当我运行“api_method = client.discovered_api('analytics','v3').data.ga.get”时,它会导致未知关键字:interval,来自/home/brahmos/.rvm/gems/ruby-2.0.0-p576/gems/google-api-client-0.7.1/lib/google/api_client.rb:595:in `execute!'。 - Aparichith
在 @h.APP.y 中,您可以通过导航到“管理”然后转到您的视图的“查看设置”来查找配置文件 ID;在那里,您应该会看到一个“查看 ID”:这是配置文件 ID(Google 将其从配置文件 ID 重命名为查看 ID),例如“12345”。然后,您必须将 PROFILE 设置为“ga:12345”。 - severin
@severin明白了,谢谢。我已经搜索得很累了。 - Aparichith
它返回一个空数组。你能帮我吗? - Gowtham
我解决了。在视图设置中,我使用了账户ID而不是ID。 - Gowtham
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接