2014-09-03 66 views
4

我很努力地访问Google Contacts API。在Ruby上访问Google Contacts API

首先我试了google-api-ruby-client宝石,但事实证明,它does not support the Contacts API

下一个镜头是google_contacts_apigem但我很难获得与oAuth2gem一个oauth_access_token_for_user。当按照oAuth2 instructions我不知道该写什么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。

回答

6

确保您的应用设置正确,并且您已经启用的Google Developers Console联系人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在您的浏览器,登录到谷歌。之后重定向到的URL将包含参数code中的标记。它看起来像这样(这下一行是不是代码,你跑):

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

解析从重定向URL代码,然后

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

编辑

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

token是本例中的一个OAuth2::AccessToken对象。所有你需要做的就是将它传递给构造函数:

user = GoogleContactsApi::User.new(token) 

要格外清晰,构造函数接受令牌对象,而不是字符串。

+0

非常感谢alvin,但我陷入困境。我能够以这种格式获取访问令牌:#。但是现在我怎么继续使用google_contacts_api gem。我应该如何将令牌传递给它。如果你能给出一些细节,我将不胜感激。 – ben 2014-09-25 22:55:58

+0

您只需将令牌传递给构造函数:'GoogleContactsApi :: User.new(token)' – alvin 2014-09-26 08:34:22

+0

您的回答帮助我授权并获取令牌。当我将令牌传递给构造函数时,就像你所说的那样,它给出了一个错误。我发布了一个关于这个http://stackoverflow.com/questions/26052480/how-to-access-google-contacts-api-in-ruby的问题。 Plz查看问题 – ben 2014-09-26 08:56:07