簡體   English   中英

如何使用Google API Ruby客戶端進行授權?

[英]How to authorize with the Google API Ruby client?

我想通過Google API從我的Google Analytics(分析)帳戶中獲取數據,並在我的一個儀表板上顯示一些值。 如果可能,我想為此使用Ruby。

google-api-ruby-client似乎是一個不錯的起點,我什至找到了一些有用的示例代碼 ,這些代碼對您有很大幫助,但是我無法正確授權我的請求。

在相同的示例代碼中,有一部分顯示了如何執行此操作,但是我不確定從哪里獲取必要的密鑰。

到目前為止,我已經做過的事情:

  1. https://console.developers.google.com上創建了一個項目
  2. 啟用Analytics API
  3. 基於向導,我創建並下載了一個服務帳戶密鑰,如下所示:

     { "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" } 

但是,我不知道如何使用它。 也許我犯了一個錯誤,我需要從Google那里獲取其他類型的密鑰嗎?

由於Google API的性質和企業安全性要求,這比普通的RESTful硅谷API稍微復雜一些。 我需要在過去的項目中執行此操作,我認為這會有所幫助。

首先,為了簡化查詢所需數據的過程,我使用了Legato ,它自稱為“ Google Analytics Core Reporting and Management API的Ruby客戶端”。

為了使Legato正常工作,您需要從Google獲取OAuth令牌,該令牌會在一段時間后失效。

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

假設您具有三個與Google提供的身份驗證數據相對應的環境變量:

  1. GOOGLE_SERVICE_EMAIL,與JSON對象中的客戶電子郵件相同。
  2. GOOGLE_PRIVATE_KEY_PATH,它指向您應該可以同時下載的.p12文件。
  3. GOOGLE_PRIVATE_KEY_PASSPHRASE,字面上應為“ notasecret”。

您可以像以下這樣用連奏來使用該服務:

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)

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM