2014-09-03 65 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