2017-01-02 122 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) 

祝您好运!

相关问题