Renew Facebook access token with Koala

Mr_Nizzle picture Mr_Nizzle · Jan 24, 2012 · Viewed 9.5k times · Source

I'm using Koala gem on on Ruby on Rails application

And I have the following code on the model I'm using to the the data through Koala:

@graph = Koala::Facebook::GraphAPI.new(token_secret)
friends = @graph.get_connections("me", "friends")

where token_secret comes from a field of my users table, saved on the login.

It works fine but after a couple minutes I get:

Koala::Facebook::APIError (OAuthException: Error validating access token: Session has expired at unix time 1327438800. The current unix time is 1327442037.):

I found the way to renew this token in the front with the methods from the Facebook JS SDK but this method where I'm getting the list of friends is called on the controller.

How can I renew the token_secret using Koala? is this possible?

Answer

sevenseacat picture sevenseacat · May 28, 2013

I thought I'd answer this because it's something I just came across the need to do.

Koala added support for exchanging access tokens some time ago, here: https://github.com/arsduo/koala/pull/166

So my User model now has something like the following:

def refresh_facebook_token
  # Checks the saved expiry time against the current time
  if facebook_token_expired? 

    # Get the new token
    new_token = facebook_oauth.exchange_access_token_info(token_secret)

    # Save the new token and its expiry over the old one
    self.token_secret = new_token['access_token']
    self.token_expiry = new_token['expires']
    save
  end
end

# Connect to Facebook via Koala's oauth
def facebook_oauth
  # Insert your own Facebook client ID and secret here
  @facebook_oauth ||= Koala::Facebook::OAuth.new(client_id, client_secret)
end