CSS

Foursquare API with oauth2 gem

The oauth things is pretty complex, here is some notes that may avoid you fall into the same pitfall as me.

You can read the whole spec here.

But basically, it provide a interface let website can access the user's data in other website.
User will first be redirect to that website, click confirm, and redirected back to the callback page.

In the back end, the process of server is:
1.Send request to target website for token, with the server's client_id & secret_id
2.Redirect user to authorize page with token (and callback url)
3.After user confirm, user will be redirect to the callback page with a access_token
4.Save the access_token, and free to call target server for user data.

However, using gem to manage those things seen like a smart way, but still, it may not work correctly because of some error:

#pitfall 1

Check the api is using oauth or oauth2,
which is different when choosing the oauth gem.

#pitfall 2

check the oauth_path, access_token_path is correct
the default setting of gem may not work with the api you choose.

#pitfall 3

check the api address,
in foursquare, the authorize url is : https://foursquare.com/oauth2/authorize
however, the api is not under the same subdomain, is under https://api.foursquare.com/

make sure those setting is correct, and you will feel the sweet of oauth!

here's the code with sinatra:

require 'sinatra'
require 'oauth2'

get '/auth' do
  redirect to(client.web_server.authorize_url(:redirect_uri =>
                                              "http://myhost/callback"))
end

get '/callback' do
  #make sure the access token is named "code"
  access_token = client.web_server.get_access_token(params[:code],
                                      :redirect_uri => "http://myhost/callback")
  access_token.get('https://api.foursquare.com/v2/users/self')
  # save your access token in session or db...
end

def client
  client ||= OAuth2::Client.new(
  YOUR_CLIENT_ID,YOUR_SECRET_ID,
  :site => 'https://foursquare.com',
  :authorize_path => '/oauth2/authorize',
  :access_token_path => '/oauth2/access_token')
end

No comments:

Post a Comment