How to pull Google Analytics stats?

后端 未结 1 875
甜味超标
甜味超标 2020-12-23 00:04

Is Google API Ruby client the best option?

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 ?

相关标签:
1条回答
  • 2020-12-23 00:50

    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).

    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 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
    

    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.


    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

    0 讨论(0)
提交回复
热议问题