2011-09-21 115 views

回答

11

如果您要创建服务帐户应用程序来访问Google Analytics。

  1. 通过https://code.google.com/apis/console向Google注册。 在API访问选项卡上,单击创建客户端ID,选择服务帐户。存储Google将生成的密钥文件,并记住该密钥的密码。
  2. 下面是一些代码,让你开始

    require 'rubygems' 
    require 'google/api_client' 
    
    api_client = Google::APIClient.new 
    path_to_key_file ="/path/to/key/file-privatekey.p12" 
    passphrase = "google_generated_password" 
    key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase) 
    

一旦一个键,那么请与您的客户端ID(电子邮件中的API控制台) 和授权范围初始化声明者。

asserter = Google::APIClient::JWTAsserter.new(
    '[email protected]com', 
    'https://www.googleapis.com/auth/analytics.readonly', 
    key) 

# To request an access token, call authorize: 
api_client.authorization = asserter.authorize() 
puts api_client.authorization.access_token 

http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts

+0

我得到这个:'授权失败。服务器消息:{“error”:“invalid_grant”}'。 我听说有人说要将授予模式更改为脱机,但有没有办法从ruby gem那样做? – NullVoxPopuli

0

我已经回答了在几个其他职位,我发现了这样一个类似的东西...所以柜面其相关的,红宝石,使用谷歌的API客户端(对于任何谷歌apis),有几个与身份验证使用api密钥,而不是OAuth身份验证...

我已经列出了这个过程(使用api密钥服务器端)在the code abode

在构建客户端时,您必须明确设置authorzation参数为nil,否则gem会尝试使用OAuth进行身份验证,所以如果仅使用api键从服务器调用,您将始终获得401 Unauthorized。

the code abode - google-api-client for ruby