![](/img/trans.png)
[英]Can't get birthday from Google Contacts Data API in Ruby on Rails
[英]Access Google Contacts API on Ruby
我很難訪問Google Contacts API。
首先我嘗試了google-api-ruby-client
gem,但事實證明它不支持Contacts API 。
下一個鏡頭是google_contacts_api
gem,但我很難獲得oauth_access_token_for_user
和oAuth2
gem 。 當遵循oAuth2指令時,我不知道在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,我將不勝感激。
確保您的應用已正確設置,並且您已在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庫。 (我寫了圖書館,所以我應該知道!)
在此示例中, token
是OAuth2::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.