Get gmail contacts usign token in ruby on rails
Hello Everyone,
I've
find a nice way to fetch the gmail contacts of the person whose token
is already present in our database. No gem is required for this, just
follow the below steps :
Step 1 : https://console.developers.google.com/ create
a new application or select one which is existing, then go to "APIs
& auth" on the right tab, there in the sub-options choose "API".
Now, you'll find list of API, enable "Contacts API".
Step 2 : In your devise.rb where it is written the keys, write the scope to access the contacts of user.
=> config.omniauth :google_oauth2, CLIENT ID , CLIENT SECRET, { scope: 'https://www.googleapis.com/auth/userinfo.emailhttps://www.googleapis.com/auth/userinfo.profile https://www.google.com/m8/feeds/&response_type=code'}
Step 3 : Write code in the controller or where you want to fetch the contacts list :
=>
token = current_user.authorization.token
uri = URI.parse("https://www.google.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = "/m8/feeds/contacts/default/full?max-results=10000"
headers = {'Authorization' => "AuthSub token=#{token}",
'GData-Version' => "3.0"}
resp = http.get(path, headers)
# extract the name and email address from the response data
# HERE USING REXML TO PARSE GOOGLE GIVEN XML DATA
xml = REXML::Document.new(resp.body)
contacts = []
xml.elements.each('//entry') do |entry|
person = {}
person['name'] = entry.elements['title'].text
gd_email = entry.elements['gd:email']
person['email'] = gd_email.attributes['address'] if gd_email
contacts << {label: person['email'], value: person['email'] }
end
----------------------------------------------------------------------------------------------------------------------
That's It !!! You have all contacts now.
Happy Coding.
----------------------------------------------------------------------------------------------------------------------
[Note] : For Login process, I'd used gem 'omniauth-google-oauth2'
Comments
Post a Comment