代码之家  ›  专栏  ›  技术社区  ›  migu

在Ruby上访问Google联系人API

  •  4
  • migu  · 技术社区  · 11 年前

    我很难访问Google联系人API。

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

    下一个镜头是 google_contacts_api gem 但我很难得到 oauth_access_token_for_user 使用 oAuth2 gem 。当遵循 oAuth2 instructions 我不知道该放什么 authorization_code_value Basic 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,我将不胜感激。

    2 回复  |  直到 11 年前
        1
  •  6
  •   alvin    11 年前

    确保您的应用程序设置正确,并且已在 Google Developers Console 。然后尝试此操作:

    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}"
    

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

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

    编辑

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

    token 是一个 OAuth2::AccessToken 对象。您所要做的就是将其传递给构造函数:

    user = GoogleContactsApi::User.new(token)
    

    更明确的是,构造函数接受令牌对象,而不是字符串。

        2
  •  1
  •   Blake O'Hare    11 年前

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

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