繁体   English   中英

在Ruby上访问Google Contacts API

[英]Access Google Contacts API on Ruby

我很难访问Google Contacts API。

首先我尝试了google-api-ruby-client gem,但事实证明它不支持Contacts API

下一个镜头是google_contacts_api gem,但我很难获得oauth_access_token_for_useroAuth2 gem 当遵循oAuth2指令时,我不知道在authorization_code_valueBasic some_password放入什么。

我尝试了以下方法:

require 'oauth2'
client = OAuth2::Client.new(ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], :site => 'http://localhost:9292')
=> #<OAuth2::Client:0x007fcf88938758 @id="blabla.apps.googleusercontent.com", @secret="blabla", @site="http://localhost:9292", @options={:authorize_url=>"/oauth/authorize", :token_url=>"/oauth/token", :token_method=>:post, :connection_opts=>{}, :connection_build=>nil, :max_redirects=>5, :raise_errors=>true}>

client.auth_code.authorize_url(:redirect_uri => 'http://localhost:9292')
=> "http://localhost:9292/oauth/authorize?client_id=blabla.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A9292&response_type=code"

token = client.auth_code.get_token('authorization_code_value', :redirect_uri => 'http://localhost:9292', :headers => {'Authorization' => 'Basic some_password'})
=> Faraday::ConnectionFailed: Connection refused - connect(2) for "localhost" port 9292

如果有人能给我详细的逐步说明如何访问API,我将不胜感激。

确保您的应用已正确设置,并且您已在Google Developers Console中启用了Contacts API。 然后尝试这个:

CLIENT_ID = '?????.apps.googleusercontent.com'
CLIENT_SECRET = 'your_secret'
REDIRECT_URI = 'your_redirect_uri'
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, 
           site: 'https://accounts.google.com',
           token_url: '/o/oauth2/token',
           authorize_url: '/o/oauth2/auth')
url = client.auth_code.authorize_url(scope: "https://www.google.com/m8/feeds",
           redirect_uri: REDIRECT_URI)

在浏览器中访问url并登录Google。 之后重定向到的URL将在参数code包含令牌。 它看起来像这样(下一行不是你运行的代码):

actual_redirect_url = "#{REDIRECT_URI}?code=#{code}"

然后解析重定向网址中的代码

token = client.auth_code.get_token(code, :redirect_uri => REDIRECT_URI)

编辑

有人在评论中询问如何将令牌传递给google_contacts_api库。 (我写了图书馆,所以我应该知道!)

在此示例中, tokenOAuth2::AccessToken对象。 您所要做的就是将它传递给构造函数:

user = GoogleContactsApi::User.new(token)

为了更清楚,构造函数接受令牌对象,而不是字符串。

看起来您正在对localhost进行身份验证(在身份验证后重定向的上下文中应该只引用localhost)。 您应该在那里的某个地方对Google的OAuth服务器进行身份验证。

请参阅: https//github.com/google/google-api-ruby-client/blob/master/lib/google/api_client.rb#L165

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM