我使用Garb(0.9.8)直接使用 OAuth1 从我们的服务器从 Google Analytics 获取数据。由于 Google 现在只支持 OAuth2,所以我切换到Signet gem并使用服务帐户直接从服务器获取 access_token,因为我们只需要服务器到服务器的交互。
key = Google::APIClient::KeyUtils.load_from_pkcs12(p12_key_path, 'notasecret')
client = Google::APIClient.new(application_name: 'Service account demo', application_version: '0.0.1')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => ['https://www.googleapis.com/auth/analytics', 'https://www.googleapis.com/auth/analytics.readonly'],
:issuer => <service account email>,
:signing_key => key
)
access_token = client.authorization.fetch_access_token!["access_token"]
令牌有效,我从 Google API 游乐场仔细检查了它。该服务帐户已添加为对我的 Google Analytics 帐户具有所有权限的用户。如果可行,我想使用 Garb 而不是完全切换到 google-api-client gem,以避免重写大量现有代码。然后为了让 Garb 使用获得的 access_token 并获取所有配置文件,我做了以下操作
garbsession = Garb::Session.new
garbsession.access_token = access_token
Garb::Management::Profile.all(garbsession)
但我收到一个错误:
NoMethodError: undefined method `get' for #<String:0xd877aa0>
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/request/data.rb:94:in `oauth_user_request'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/request/data.rb:41:in `send_request'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/management/feed.rb:21:in `response'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/management/feed.rb:13:in `parsed_response'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/management/feed.rb:17:in `entries'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/garb-0.9.8/lib/garb/management/profile.rb:14:in `all'
from (irb):47
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.19/lib/rails/commands/console.rb:47:in `start'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.19/lib/rails/commands/console.rb:8:in `start'
from /home/alok/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.19/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
难道我做错了什么?我可以在 Garb 中使用通过其他方法获得的访问令牌,然后访问 Google Analytics API 吗?