Saturday 8 October 2016

Twitter authentication and Posting url and message on Twitter through RoR

In this blog, we will implement authentication with twitter and posting on twitter.

First, we will implement twitter authentication with omniauth-twitter.

So, in Gemfile -



gem 'omniauth-twitter'

After that in config/intializer/omniauth.b -


Rails.application.config.middleware.use OmniAuth::Builder do
# get consumer_key and consumer_secret from creating a developer account in twitter
    provider :twitter, ['consumer_key'], ['consumer_secret'], {:display => "popup",:x_auth_access_type => 'Read, Write & Direct Messages'}

end



In routes.rb -




# Here we are using oauths controller. Set callback url in twitter developer account as https://localhost:3000/auth/twitter/callback
get '/auth/twitter/callback' => 'oauths#twitter_callback', as: 'twitter-callback'


Now in controller -


  def twitter_callback
    token = request.env['omniauth.auth']['extra']['access_token'].params[:oauth_token]
    token_secret = request.env['omniauth.auth']['extra']['access_token'].params[:oauth_token_secret]
    twitter_id = request.env['omniauth.auth']['extra']['access_token'].params[:user_id]
  end


Above method return token, token_secret and twitter_id of twitter user.

Now, we have all done with twitter authentication.

Now for posting we will use twitter gem.

In Gemfile -

gem 'twitter', '~> 5.16'

We have to initialize the twitter cleint. Below method intialize
In model - # you can put anywhere initializer method as per your convenience.


def initialize_twitter_client
    data = YAML::load_file(File.join(Rails.root, 'config', 'api_keys.yml'))[Rails.env]
    client = Twitter::REST::Client.new do |config|
      config.consumer_key = ['consumer_key'] # put here consumer_key of twitter app.
      config.consumer_secret = ['consumer_secret'] # put here consumer_secret of twitter app.
      config.access_token = ['token'] # We have alraedy got token from twitter authentication for perticular twitter user.
      config.access_token_secret = ['token_secret'] # It is also provided by twitter authentication for perticular twitter user.
    end
end


Now, we can post on twitter from below method



def post_to_twitter(product)
    client = initialize_twitter_client
    message = "Put your message here. Be sure it will not more than 140 character"[0..139]
    client.update("#{message} #{url}")
end

No comments:

Post a Comment