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.

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

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Reading Excel Sheets using "Roo" gem in ruby on rails

Bootstrap Select Picker append add new item if search not exist

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails