2017-01-02 104 views
0

我想通過谷歌的API從我的谷歌分析帳戶中獲取數據,並在我的一個儀表板上顯示一些值。如果可能的話,我想用Ruby來做到這一點。如何使用Google API Ruby客戶端進行授權?

google-api-ruby-client似乎是一個很好的開始,我甚至找到了一些useful sample code幫助了很多,但我正在準備妥善授權我的請求。

在相同的示例代碼中,有一部分是shows how to do it但我不確定從哪裏獲得必要的密鑰。

的事情,我這樣做的遠:

  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獲取其他類型的密鑰?

回答

1

由於Google的API和企業安全要求的性質,這比一般的RESTful硅谷API要複雜一些。我需要在過去的項目上這樣做,我認爲這會有所幫助。

首先,爲了更方便地查詢我需要的數據,我使用了Legato,它自我描述爲「Google Analytics核心報告和管理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 

這裏假設你有對應於谷歌提供您的身份驗證數據三個環境變量:

  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) 

祝您好運!

相關問題