Access Google Contacts API on Ruby

筅森魡賤 提交于 2019-11-29 11:10:38

Make sure your app is set up properly and that you've enabled the Contacts API in the Google Developers Console. Then try this:

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)

Visit url in your browser and log in to Google. The url you are redirected to afterwards will contain the token in the parameter code. It will look like this (this next line is not code you run):

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

Parse the code from the redirect url, then

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

Edit

Someone asked in the comments how to pass the token to the google_contacts_api library. (I wrote the library, so I should know!)

token is an OAuth2::AccessToken object in this example. All you have to do is pass it to the constructor:

user = GoogleContactsApi::User.new(token)

To be extra clear, the constructor accepts the token object, not a string.

It looks like you're authenticating against localhost (should only be referring to localhost in the context of redirecting after authentication). You should be authenticating against Google's OAuth server somewhere in there.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!