Facebook - Get the access token

* You need to set "Site URL" under the tab "Website with Facebook Login" in the app setting page.

Why?

Because I need to get the access tokens of multiple Facebook accounts, so that I can write code to post from these accounts. These access tokens will be hard-coded.

Ruby Code

First, we redirect the end-user to the Facebook dialog url

            session[:state] = RANDOM_STR
            redirect "https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=URL&state=#{session[:state]}&scope=PERM1,PERM2"
        

After the user accepts your app, he/she is redirected back to our callback url with the parameters: state and code. We verify that the state is the same, and we request for the access token:

          require 'cgi'
          require 'uri'
          require 'net/http'

          if !session[:state] or session[:state] != params[:state]
            raise 'session[:state] is invalid'
          end

          uri = URI.parse("https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&redirect_uri=URL&client_secret=CLIENT_SECRET&code=#{params[:code]}")

          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = (uri.port == 443)
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE

          response = http.request(Net::HTTP::Get.new(uri.request_uri))

          if response.code.to_i != 200
            raise "Response from Facebook is not valid #{response.inspect}"
          end

          response_params = CGI::parse(response.body)
          session[:access_token] = response_params['access_token'][0]
        

Next time, with the access token, you can Facebook API:

          require 'uri'
          require 'net/http'

          uri = URI.parse("https://graph.facebook.com/me?access_token=ACCESS_TOKEN")
          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = (uri.port == 443)
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE

          response = http.request(Net::HTTP::Get.new(uri.request_uri))
          puts response.body
        

By Tanin Na Nakorn