I have been experimenting with the Foursquare API for a few months now, and I wanted to start fresh learning how to use OAuth. If you don’t know what OAuth is, think of it as a valet key. Instead of giving a third party (me) your username and password, you can click a simple link on my site, which takes you to Foursquare to authenticate, and then you come back to my site.
Note: The Foursquare API requires authentication to use most of its methods. You can choose basic HTTP authentication, but these days most developers prefer OAuth. So this tutorial will focus on OAuth, which is basically a trusted virtual handshake.
In this blog post, I want to give you guys a detailed tutorial on how I accomplished using the with Foursquare’s new API.
What you’ll need
- Your favorite text editor
- A web server with PHP
- MySQL with a way to edit tables
- A lot of patience – this took me a few weeks to figure out, but I hope you can do it in less than an hour.
Okay, so let’s get started shall we? By the way, here is what we are building:
The first thing I did was sign up for a consumer key and secret at Foursquare. To do that, point your browser to :
The callback URL is the location your users will be sent after they authenticate on Foursquare’s site.
Here is the OAuth workflow in five easy steps:
- Get request key and secret
- Provide link to foursquare authorization page
- User will approve or deny access and be redirected to your application
- Get access key and secret and store in your database
- Use access key and secret to make api method calls
Step one is done, but step two is a doozy.
I prefer using PHP, so let’s take a look at some code.
$key = '447ebcf0b99a149e06a9aa0cc91fe79904a54f798'; $secret = 'e6b7d0195c4481369ab87509d63591a7';
This is my key and secret. Yours will be different. This is how I start out my index.php file. Let’s move on…
require_once 'oauth/OAuthDiscovery.php'; require_once 'oauth/OAuthRequester.php'; require_once 'oauth/OAuthRequestVerifier.php'; require_once 'oauth/OAuthServer.php';
Here is where I am including the OAuth library files. You only need these four to get started. Next:
$options = array( 'server' => 'mysql.foursqwhere.com', 'username' => 'foursqwhere', 'password' => 'f0ursqu4re', 'database' => 'foursqwhere' );
This is a data object that stores the MySQL login information. oauth-php uses a database to store your OAuth tokens and secrets and all the goodness. It also requires that you set a $user_id
variable to keep track of multiple sites authentications. In this case, I am hardcoding that value as 1:
$user_id = 1;
We are ready to connect to the database now. Here is how it’s done with oauth-php:
$store = OAuthStore::instance('MySQL', $options);
This next bit of code will check to see if there is anything in the database already relating to our consumer. If not, it will create a new entry in the database with everything we need to request a “token” from Foursquare.
// See if we have already an access token, if so we don't need to do the "dance" try { $secrets = $store->getSecretsForSignature("playfoursquare.com", $user_id); // var_dump($secrets); } catch(OAuthException $e) { $secrets = false; // Make sure the server is registered try { $store->getServer($key, $user_id, true); } catch(OAuthException $e) { // The server description $server = array( 'consumer_key' => $key, 'consumer_secret' => $secret, 'server_uri' => 'playfoursquare.com', 'ocr_server_uri' => 'http://api.playfoursquare.com/', 'ocr_server_uri_host' => 'api.playfoursquare.com', 'ocr_server_path' => '/', 'signature_methods' => array('HMAC-SHA1', 'PLAINTEXT'), 'request_token_uri' => 'http://playfoursquare.com/oauth/request_token', 'authorize_uri' => 'http://playfoursquare.com/oauth/authorize', 'access_token_uri' => 'http://playfoursquare.com/oauth/access_token' ); // Save the server in the the OAuthStore $consumer_key = $store->updateServer($server, $user_id); } // Obtain a request token from the server $token = OAuthRequester::requestRequestToken($key, $user_id); }
Once we have that, we can finally direct the user over to Foursquare. Do a var_dump()
on $token
and you can see that you finally have a token that Foursquare will accept.
Array ( [authorize_uri] => http://playfoursquare.com/oauth/authorize [token] => 89910ced8d6f4dc3706d6208cc50789404a64046a )
Time to build the URL to connect to Foursquare:
$authLink = 'http://playfoursquare.com/oauth/authorize?oauth_token=' . $token['token'];
Here is how I built out the link on my site:
Once the user goes to Foursquare to authenticate, they will be sent to your callback URL. Some people like to use the same location, but I directed the user over to a new directory. The callback URL contains some query parameters that are required to make signed posts to Foursquare. Here is what my callback URL looks like:
http://www.foursqwhere.com/home/index.php?consumer_key=447ebcf0b99a149e06a9aa0cc91fe79904a54f798&user_id=1
&oauth_token=d434603dbfef173efeb930494ca713e904a64a832
It contains the consumer key, a user ID (hardcoded as 1), and an OAuth token.
Okay, here is where it might get a little hacky. Sometimes you get an error when you reach your callback page. Something about the getSignatures()
function failing. Make sure your database has the following fields are correct in your database:
Okay, moving on to the callback page code. I usually declare my $consumer_key
variable again just for good practice:
$consumer_key = '447ebcf0b99a149e06a9aa0cc91fe79904a54f798';
Then I create a cookie in case my users come back and don’t want to re-authenticate again:
if (empty($_COOKIE["Foursqwhere"])) { $oauth_token = $_GET['oauth_token']; setcookie("Foursqwhere", $oauth_token); } else { $oauth_token = $_COOKIE["Foursqwhere"]; }
Include a few more oauth-php library files:
require_once '../oauth/OAuthDiscovery.php'; require_once '../oauth/OAuthServer.php'; require_once '../oauth/OAuthRequest.php'; require_once '../oauth/OAuthRequestLogger.php'; require_once '../oauth/OAuthStore.php'; require_once '../oauth/OAuthRequestSigner.php'; require_once '../oauth/OAuthRequestVerifier.php'; require_once '../oauth/OAuthRequester.php';
oauth-php requires that you connect to the database again before you can use your token:
$options = array( 'server' => 'mysql.foursqwhere.com', 'username' => 'foursqwhere', 'password' => 'f0ursqu4re', 'database' => 'foursqwhere' ); $store = OAuthStore::instance('MySQL', $options);
Almost there. Now let’s request the access token:
try { OAuthRequester::requestAccessToken($consumer_key, $oauth_token, $user_id); } catch (OAuthException $e) { // Something wrong with the oauth_token. // Could be: // 1. Was already ok // 2. We were not authorized }
Believe it not, now we are officially approved to make signed requests to Foursquare. Here is a and .
I will show you some examples of my code now. Let’s use the checkins
method provided by the API:
$api_checkins = 'http://api.playfoursquare.com/v1/checkins.json'; $params_checkins = array(); $checkins = new OAuthRequester($api_checkins, 'GET', $params_checkins); $checkins_result = array_filter($checkins->doRequest($user_id)); $checkins_body = $checkins_result['body'];
You can do a var_dump()
on $checkins_body
to see what data is returned. Note that the $api_checkins
variable string has .json as a file extension. If you leave this blank, you get an XML tree of data back.
This is how I get the current user data, using XML instead. Towards the bottom, you will see how I target certain nodes:
$api_user = 'http://api.playfoursquare.com/v1/user'; $params_user = array(); $user = new OAuthRequester($api_user, 'GET', $params_user); $user_result = $user->doRequest($user_id); $user_body = $user_result['body']; $user_rss = simplexml_load_string($user_body); $user_city = $user_rss->city->name; $user_lat = $user_rss->checkin->venue->geolat; $user_lon = $user_rss->checkin->venue->geolong; $you = $user_rss->checkin->venue->name;