简体   繁体   中英

How to authorize with the Google API Ruby client?

I want to fetch data from my google analytics account via google's API, and to display some values on one of my dashboards. I want to use Ruby for this, if possible.

The google-api-ruby-client seems like a good place to start, and I have even found some useful sample code that helps out a lot, but I am faling to properly authorize my requests.

In the same sample code, there is a part that shows how to do it but I am not sure where to get the necessary keys.

Things that I've done so far:

  1. Created a project on https://console.developers.google.com
  2. Enabled the Analytics API
  3. Based on a wizard, I have created and downloaded a service account key that looks like:

     { "type": "service_account", "project_id": "xxx" "provate_key_id": "xxx", "private_key": "xxx", "client_email": "xxx", "client_id": "xxx", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "xxx" } 

But, I can't figure out how to use it. Maybe I've made a mistake, and I need to fetch some other kind of key from Google?

Due to the nature of Google's API and the enterprise security requirements, this is a little more complicated than your average RESTful, Silicon Valley API. I needed to do this on a past project, and I think this will help.

First, to make querying for the data I needed easier, I used Legato , which self-describes as a “Ruby Client for the Google Analytics Core Reporting and Management API”.

In order to get Legato working, you need to obtain an OAuth token from Google, which expires after a while.

class AuthToken
  def self.retrieve
    new.retrieve
  end

  def retrieve(expires_in = 1.hour)
    client = Google::APIClient.new(application_name: 'YOUR APP NAME', application_version: '0.1')
    client.authorization = service_account('https://www.googleapis.com/auth/analytics.readonly', private_key).authorize
    OAuth2::AccessToken.new(oauth_client, client.authorization.access_token, expires_in: expires_in )
  end

private

  def oauth_client
    OAuth2::Client.new('', '', {
      authorize_url: authorize_url,
      token_url: token_url
    })
  end

  def service_account(scope, key)
    Google::APIClient::JWTAsserter.new(ENV['GOOGLE_SERVICE_EMAIL'], scope, key)
  end

  def private_key
    @private_key ||= Google::APIClient::PKCS12.load_key(
      ENV['GOOGLE_PRIVATE_KEY_PATH'],
      ENV['GOOGLE_PRIVATE_KEY_PASSPHRASE']
    )
  end

  def authorize_url
    'https://accounts.google.com/o/oauth2/auth'
  end

  def token_url
    'https://accounts.google.com/o/oauth2/token'
  end
end

This assumes you have three environment variables corresponding to the authentication data that Google provided you:

  1. GOOGLE_SERVICE_EMAIL, which is the same as the client email you have in your JSON object.
  2. GOOGLE_PRIVATE_KEY_PATH, which points to the .p12 file you should have been able to download at the same time.
  3. GOOGLE_PRIVATE_KEY_PASSPHRASE, which should literally be “notasecret”.

You can utilize the service with legato like so:

class ArticlePageviews
  extend Legato::Model
  metrics :pageviews
  dimensions :page_path
  filter(:only_articles) { contains :page_path, '/articles/' }
end

ga_user = Legato::User.new(AuthToken.retrieve)
ga_profile = ga_user.profiles.first

ArticlePageviews.only_articles.results(ga_profile)

Best of luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM