ruby-on-rails - 在 Ruby 上访问 Google 通讯录 API

标签 ruby-on-rails ruby api google-api google-contacts-api

我无法访问 Google Contacts API。

首先我尝试了 google-api-ruby-client gem 但结果是 does not support the Contacts API .

下一个镜头是 google_contacts_api gem但我很难通过 oAuth2 gem 获得 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,我将不胜感激。

最佳答案

确保您的应用设置正确并且您已在 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 并登录到 Google。之后重定向到的 url 将在参数 code 中包含 token 。它看起来像这样(下一行不是您运行的代码):

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

解析重定向url中的代码,然后

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

编辑

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

token 在这个例子中是一个 OAuth2::AccessToken 对象。您所要做的就是将它传递给构造函数:

user = GoogleContactsApi::User.new(token)

要特别清楚,构造函数接受 token 对象,而不是字符串。

关于ruby-on-rails - 在 Ruby 上访问 Google 通讯录 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637485/

相关文章:

ios - 使用适用于 iOS 的 Google Analytics API v3 进行 session 控制?

ruby-on-rails - ruby /rails : Merge result of map

ruby-on-rails - 关于 RoR 更新数据库记录

ruby-on-rails - 无法在 Rails 3.2.3 中批量分配 protected 属性

ruby-on-rails - 使用 Rails 助手来呈现部分

ruby-on-rails - 捆绑安装:G​​em::RemoteFetcher::FetchError: SSL:...证书验证失败

php - 通过 token / key 进行用户和 API 身份验证

ruby-on-rails - 在 Mac 上安装 do_postgres

ruby - 包含一个模块来定义动态类方法

java - 什么是以及如何获取 Twitter 和 oauth-signpost 的 pinCode?