In a Rails app, we have implemented Facebook API. We have a Facebook page, where we need to automatically post statuses when a user will post something to the Rails app. The problem is, that we need automatically renew Facebook access token.
I am trying to do it this way, but as I am doing it the first time, I am a little bit lost here:
def fb_autopost
require 'net/http'
temp_token = 'my_short_time_token'
app_id = '145634995501123' # I didn't put here real token from obvious reason
app_secret = '0dd5fcf93b4280fb19bf6b80f487c123' # I didn't put here real token from obvious reason
puts "https://graph.facebook.com/oauth/access_token?client_id=#{app_id}&client_secret=#{app_secret}&grant_type=fb_exchange_token&fb_exchange_token=#{temp_token}"
puts '---'
url = "https://graph.facebook.com/oauth/access_token?client_id=#{app_id}&client_secret=#{app_secret}&grant_type=fb_exchange_token&fb_exchange_token=#{temp_token}"
response = open(url)
puts response.inspect
puts '---'
end
When I run this code, I get this error:
Processing by ListingsController#post_to_fb as HTML
Completed 500 Internal Server Error in 1015ms
OpenURI::HTTPError (400 Bad Request):
app/controllers/listings_controller.rb:194:in `fb_autopost'
I would like to ask you for help how to renew the token. Is in this case the best way to store the token in the database and like one day before expiring to run this action and renew the token?
Or is there any better way to do that?
Thank you so much
I personally use this gem : https://github.com/nov/fb_graph
You should find everything you need in the documentation (https://github.com/nov/fb_graph#normal-oauth2-flow)
Related
I've been trying to use my RoR app to connect to the Facebook API for a day without any luck. I'm using Ruby on Rails and Koala.
If I try to connect as follows:
graph = Koala::Facebook::API.new(User_Token)
Then there is no problem. (Where user token was obtained from https://developers.facebook.com/tools/access_token/)
The problem is that the user token expires. I am aware that there is a way to extend the app User Token, but I would rather not resort to this.
Rather, I am trying to authenticate my app to obtain an APP ACCESS TOKEN which I can use in lieu of the User Token (as per https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens. Please note this refers to the App Access Token, not the App Token which was referred to in the first link).
In order to obtain the App Access Token, I have followed a tutorial and provided this code in my controller:
id = <my app id>
secret = <my app secret>
callbackUrl = "http://localhost:3000/events/appcallback"
#ouath = Koala::Facebook::OAuth.new(id, secret, callbackUrl)
redirect_to #oauth.url_for_oauth_code()
in my routes.rb I have:
match "events/appcallback" => "events#appCalledBack", via: :get
This is purely to test that the callback worked.
My intention was then to do something like:
App_Access_Token = #oauth.get_access_token(params[:code])
But instead I get an error:
NoMethodError in EventsController#index
undefined method `url_for_oauth_code' for nil:NilClass
Please note that I am not interested in obtaining an access token for a user; I want one for my app, so that I can connect to the api a la:
graph = Koala::Facebook::API.new(App_Access_Token)
Any help would be greatly, greatly appreciated.
So it seems that your route is wrong, since it goes to EventsController#index. Can you post some logs and the relevant routes?
I'm trying to use the oauth-ruby gem (https://github.com/oauth-xx/oauth-ruby/) in my Rails application to let users authenticate with a 3rd party API, but I'm having problems getting the oauth_callback to work properly when using get_request_token. Here is the code that keeps failing:
#request_token = oauth_consumer.get_request_token(:oauth_callback => "http://myurl.com")
This results in a 400 Bad Request "OAuth::Unauthorized" error everytime. However when I remove that from my code it returns a request token fine:
#request_token = oauth_consumer.get_request_token()
The problem I'm facing is that when doing this I am not able to be redirected back to my application once the user has authenticated with the 3rd party. Is this an issue with my code or something to do with how the 3rd party handles oauth_callbacks?
Thanks,
Chris
That error probably become because the API you requested needs you to save at least one callback URL. Review the API and add your test/production callback url from your dashboard, then the API could validate it on every request you do.
I have a problem and found several resources to solve this one, but nothing seems to work (see below for the resource).
I want a possibility to auto-Post content I save in my Rails application to a connected Facebook fanpage.
Furthermore, I don't want the user to login to Facebook within the Rails application.
Nearly all available resources are a bit cumbersome.
http://blog.bignerdranch.com/1469-how-to-update-a-facebook-page-status-using-the-facebook-api/
http://talkweb.eu/posting-to-facebook-fan-page-wall-as-an-admin-using-facebook-api/
How to use fb_graph gem to post from app on my page wall?
I want to store some kind of token in the Rails-App which identifies the Fanpage.
Is there anything out there which does this kind of job easily?
Thanks in advance!
Ok,
after nearly one day of Googling and trial and error I've found a solution for this one.
I've built a function which only needs the Facebook page_id and the Facebook page_access_token (using the koala-Gem).
def self.post_on_facebook(body, facebook_page_id, facebook_page_access_token)
#user_graph = Koala::Facebook::API.new(facebook_page_access_token)
page_token = #user_graph.get_page_access_token(facebook_page_id)
#page_graph = Koala::Facebook::API.new(page_token)
#page_graph.get_connection('me', 'feed')
#page_graph.put_wall_post(body)
end
This guide will enable you a way to get a non-expiring access-Token for your page.
http://aseriesoftubes.com/articles/obtaining-facebook-page-access-tokens-the-4-step-program/
After doing so I can post on the pages-Wall.
Trying to write a facebook app and am attempting authentication. This is a rails 3.1 application
The First redirect where I give facebook my api and it returns a code seems to run well. But when I try to take that code and 'exchange it' from a access_token I run into problems.
The access token appears where the iframe aws.
Here is my code.
def index
#Load facebook.yml info
config = YAML::load(File.open("#{Rails.root}/config/facebook.yml"));
# setup client
redirect_to "https://graph.facebook.com/oauth/authorize?client_id=#{config['development']['app_id']}&redirect_uri=#{CALLBACK_URI}"
end
def callback
logger.debug("c")
config = YAML::load(File.open("#{Rails.root}/config/facebook.yml"));
if (!params.key?('access_token'))
logger.debug("A")
redirect_to "https://graph.facebook.com/oauth/access_token?client_id=# {config['development']['app_id']}&redirect_uri=#{CALLBACK_URI}&client_secret=#{config['development']['client_secret']}&code=#{params['code']}"
return
end
logger.debug("B")
access_token = params['access_token']
#me = FbGraph::User.me(ACCESS_TOKEN)
#name=#me.name
end
end
You are not supposed to redirect the user’s browser to the second endpoint (think for a moment, you are putting your app secret into that URL, so it would be easy for everyone to spot it there) – you are supposed to make a server-side call to that endpoint.
The docs clearly say so, https://developers.facebook.com/docs/authentication/server-side/:
“Once the user has authorized your app, you should make a server side request to exchange the code returned above for a user access token.”
I am using the ruby twitter gem and oauth to gain access to users twitter accounts. In my code, I have:
unless #user.twitter_authd?
oauth = Twitter::OAuth.new('token', 'secret')
session[:twitter_request_token] = oauth.request_token.token
session[:twitter_request_secret] = oauth.request_token.secret
#twitter_auth_url = oauth.request_token.authorize_url
end
where token and secret have my actual token and secret inserted. When I click on the link to the #twitter_auth_url, I am taken to twitter and asked to grant access. I click allow and then twitter redirects me to my callback URL http://www.mydomain.com/twitter_callback/?oauth_token=fmy2aMvnjVgaFrz37bJ4JuB8r5xN79gsgDQRG4BNY which then hits this code:
oauth = Twitter::OAuth.new('token', 'secret')
logger.info("session[:twitter_request_token] = #{session[:twitter_request_token]}")
logger.info("session[:twitter_request_secret] = #{session[:twitter_request_secret]}")
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
session[:twitter_request_token] = nil
session[:twitter_request_secret] = nil
#user.update_attributes({
:twitter_token => oauth.access_token.token,
:twitter_secret => oauth.access_token.secret,
})
redirect_to root_path
The twitter request token and secret are being set just fine. However I end up with an authorization error:
OAuth::Unauthorized in MainController#twitter_callback
401 Unauthorized
RAILS_ROOT: /Users/TAmoyal/Desktop/RoR_Projects/mls
Application Trace | Framework Trace | Full Trace
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/consumer.rb:167:in `token_request'
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/tokens/request_token.rb:14:in `get_access_token'
/Library/Ruby/Gems/1.8/gems/erwaller-twitter-0.6.13.1/lib/twitter/oauth.rb:29:in `authorize_from_request'
/Users/TAmoyal/Desktop/RoR_Projects/mls/app/controllers/main_controller.rb:70:in `twitter_callback'
The code is failing at this line:
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
when it tries to get an access token. You can see the source code of authorize_from_request here. I am not sure why this is happening. Anyone have ideas?
A bit late to the party but just ran into the same issue myself. I tracked the issue down to the setup of my OAuth app in Twitter. I had initially not specified a callback URL as I was unsure of it.
Once I had setup my rails app I went back to find Twitter had assumed I was a desktop application as I hadn't specified a callback URL. Once I changed this to website and entered a callback URL I stopped getting 400s.
If you're getting error 401 - OAuth::Unauthorized, make sure you edit the settings of your Twitter application as follows:
Application Type: Browser
Callback URL: http://127.0.0.1:3000/auth/twitter/callback
this is an issue about time synchronization of your system with twitter server.
Twitter doesn't allow localhost as part of a valid callback URL.
Instead use http://127.0.0.1:3000/auth/twitter/callback
Hope this helps
This was one of the most annoying things to debug that I have come across. I was outputting in a couple places by accident because the URL's are dynamic and they happened to not be defined in my test case (i use this to display chart data and there is not enough right now so the google chart api URL's are blank). This caused my browser to make multiple requests to my localhost when some pages were loaded. Somehow that made the oauth process crap out. Obviously there is no way for people on S.O. to know about my application specific issue so I had to answer my own question.
I had this same problem and none of the suggestions in this thread worked for me.
I found the problem for me was the TIMESTAMP on my request. The mobile device I was running my scripts on had a jacked up clock. When I updated the system time on my device to the correct time (i.e. now), all of my requests came back "200 OK" instead of "401 Unauthorized".
This problem seems to be caused by twitter not being able to handle connection keep-alive correctly. Make sure you set connection=close http header in the request to twitter. Wasted a weekend debugging this.
not enough info for me, but when was twitter gem last updated? twitter changed their oauth 'stuff' in mid may approx. perhaps you have an old one. I'd update your question to show the callback_url, and make sure you have the right token and secret, which it looks like you don't have.
also, did you put the right callback url in your twitter app page? alot of times that screws you up too.
if that fails use mbleighs twitter_auth instead. it worked for me and is pretty slick.