代码之家  ›  专栏  ›  技术社区  ›  iCyborg

如何获取谷歌分析统计数据?

  •  16
  • iCyborg  · 技术社区  · 12 年前

    Google API Ruby client 最佳选择?

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

    我能看到 the example 但我不知道该怎么开始。

    1 回复  |  直到 9 年前
        1
  •  30
  •   severin    9 年前

    我还使用 谷歌api ruby客户端 gem,并按照您提供的链接中概述的方式进行设置( https://gist.github.com/joost/5344705 ).

    只需按照链接中列出的步骤设置谷歌分析客户端:

    # 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
    

    要在应用程序中显示用户页面的统计信息,您必须调整 韵律学 过滤器 参数。例如,上面的查询将返回一个结果对象,该对象包含带有url的页面的所有页面视图 example.com/url/to/user示例 .


    注意事项: 这个答案是很久以前写的,谷歌发布了一个新的、不兼容的gem版本。请咨询 https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md