•August 29, 2011. 12:32 pm •
Recently, I’ve been looking at the Foursquare API and noticed that there isn’t enough documentation on how to authenticate with Foursquare in order to start making calls to the API. During my research I stumbled into joesiewert’s blog, who has this great article called “How To Use The Foursquare API With OAuth And PHP”. It is a great article that goes through every step in order to authenticate with Foursquare using OAuth authentication and PHP. However, his article was written in Apr 2010, which means it refers to the now deprecated version 1 of the Foursquare API. I can’t probably explain how useful was his article to help me understand how to start using the Foursquare API v2 at it’s full potential in such a short time.
After reading the comments on his blog, from people who have been having trouble understanding how to migrate from Foursquare API v1 to API v2, using the foursquare-async library provided by jmathai @ github, I decided to make this small tutorial of my own. This article is based off joe’s article, I consider it only a revised version to refer to the Foursquare API v2.
Before diving into the code, you should know that for this article we use:
In order to use this article’s intel, you should be familiar with basic PHP usage. Small piece of advice, if you have problems copying and pasting this codes into your own php files, READ THEM. The code used in this articles is pretty easy to understand, and most of the errors you may catch are easy to detect if you just try to read the code. Use your common sense, please.
Lets get started.
First, you need to setup your environment (AKA what you need).
- A text/php editor. Depending on your OS, I recommend BlueFish, but you can use any text editor, really.
- A web server with PHP or a computer with LAMP/WAMP/MAMP (You get the idea).
- The foursquare-async library. FOR HEAVEN’S SAKE: Make sure you are downloading the v2 version of this library. At the time Im writting this, there is no v3. But, you know, things change.
- A Foursquare account.
- Quoting Joe: A bunch of patience.
We will be creating two files to manage the authentication process:
And we will need to upload the files from foursquare-async library:
- EpiCurl.php
- EpiFoursquare.php
- EpiSequence.php
So far so good? Great! Now please make sure you make the calls to the right place in your server AKA:
require_once(‘EpiCurl.php’);
Is not the same than:
require_once(‘Scripts/EpiCurl.php’);
Direct quote from Joe’s:
Note: Depending on your server configuration you may need to manually enable cURL support. I did this example using XAMPP and needed to turn it on. In the php.ini file (C:\xampp\php\php.ini) uncomment the line “extension=php_curl.dll” and then restart Apache. If you get an error like this later in the tutorial it might indicate you need to enable cURL.
Possible cURL error:
Fatal error: Call to undefined function curl_multi_init() in C:\xampp\htdocs\test\EpiCurl.php on line 24
Let’s take a quick look at OAuth…
There are really two ways to connect to Foursquare’s API. However, one of them (the simple one) is not really secure and requires the user to give you their credentials. Since we live in a beautiful time where scammers live in every site and each time less users are willing to give up such information… Then we will not see this method in this article, but if you want to take a closer look, click here to read about basic access authentication.
The more recommendable and secure option is through OAuth authentication, and it is the option we’ll see in this article. quoting from Joe…
OAuth does a better job of protecting the user’s credentials and also gives the user greater control over what applications have access to their account. For example, instead of giving a random application your Foursquare credentials, you instead click on a link within the application that sends you to Foursquare to provide your credentials. Then Foursquare sends you back to the application with appropriate access keys for the application to use. Authenticating this way means that your credentials stay between you and Foursquare. The application you are giving access to only gets the OAuth access keys and doesn’t see or store your actual Foursquare credentials. It sounds complicated, but hopefully this tutorial will clear it up a little. OAuth is becoming more of a standard and as an end user you are probably already authenticating with different applications and web services this way.
So basically, we go through five steps to work with OAuth
- Get request key and secret.
- Provide link to the Foursquare authorization page.
- The user will approve or deny the access and we will be redirected to our callback URL.
- Get access key and secret code (and store it for future use).
- Use access key and secret code to make API calls.
Now, register with Foursquare and get your key and secret.
Go to http://foursquare.com/oauth/register, login and fill the required information.
- Application Name: OAuth Test
- Give your application a name (My Foursquare App)
- Application Web Site: http://localhost/
- Provide the site where you will host your application (www.mysite.com/my-foursquare-app)
- Callback URL: http://localhost/test/callback.php
- This is the URL that Foursquare will send the user to after authenticating (www.mysite.com/my-foursquare-app/callback.php)

Click Register Application and you’ll get a new key and secret key, save them!
Note: If later on you are having a php error calling a “‘grant_type’ => ‘authorization_code’ not valid” or ANYTHING along those lines. Don’t break your head against a brick wall, it’s an OAuth problem and all you need to do is RESET to get a new key and secret (Don’t forget to change them in your files too!).
So far so good?
Let’s start with the fun…
Create a index.php and open it in your text/php editor of choice. And lets go through the code you need…
<?php
//Declare your key, secret key and callback URL variables (Without these, the api wont work at all)
$clientId = “DROLX3YP0MWNTVYD2CQPAKZWEGPE3NQHAB0FWJQPKTTNW5XC”;
$clientSecret = “OZSAFCGO0VVQJHYHEOS35QPR1W2NFJTZHAPJ0C5MZCCBHIYW”;
$redirectUrl=”http://www.yoursite.com/oAuth_test/callback.php”;
//Include the foursquare-async library: (Remember, check your paths!)
require_once(‘EpiCurl.php’);
require_once(‘EpiSequence.php’);
require_once(‘EpiFoursquare.php’);
//And some code!
session_start();
try{
$foursquareObj = new EpiFoursquare($clientId, $clientSecret);
$results = $foursquareObj->getAuthorizeUrl($redirectUrl);
echo “<a href=\”$results\”>Click here to make foursquare login</a>”;
} catch (Execption $e) {
//If there is a problem throw an exception
}
?>
So what we did here, after starting the session, is basically creating a new object for the EpiFoursquare class (That’s how we use this library in particular, to read more head to the github project) And send it our clientId and clientSecret vars.
Then we make a call to getAuthorizeUrl; in that class, which requires us to send the path of callback.php, hence the $RedirectUrl.
And finally, we make a quick link that will generate an URL that will lead our user to the Foursquare authorization page.
Foursquare will recognize our link GET variables and ask the user to authorize our application. When the user clicks on the link, he will be redirected to their site and see something like this:

Once your user allows the application, he/she won’t need to do it ever again. But they can also revoke your access at any time through their profile, so be careful not to piss them off.
And lets add some code to the callback.php file…
Otherwise, the user won’t have anywhere to come back to and we won’t know if this worked or not. So make sure to add this callback.php BEFORE you go on and try to click on the link of your index.php.
<?php
//Put in the key and secret for YOUR Foursquare app, callback URL and receive the _GET code.
$clientId = “DROLX3YP0MWNTVYD2CQPAKZWEGPE3NQHAB0FWJQPKTTNW5XC”;
$clientSecret = “OZSAFCGO0VVQJHYHEOS35QPR1W2NFJTZHAPJ0C5MZCCBHIYW”;
$redirectUrl=”http://www.yoursite.com/callback.php”;
$settoken=$_GET['code'];
//Includes the foursquare-async library files
require_once(‘EpiCurl.php’);
require_once(‘EpiSequence.php’);
require_once(‘EpiFoursquare.php’);
//Start session and make some magic…
session_start();
$foursquareObj = new EpiFoursquare($clientId, $clientSecret);
$token = $foursquareObj->getAccessToken($settoken, $redirectUrl);
$foursquareObj->setAccessToken($token["access_token"]);
//You should save the $token in your $_SESSION and in your database for further use, but we don’t need it right now. You will need to setAccessToken($token["access_token"]); the first time you want to make a call in a certain page.
That works enough to make sure we’re connected to the Foursquare API. Congrats! You are now able to make calls to the API!
So lets try that out… add this below the last piece of code in callback.php
try {
//Lets test it making a check in at Mt Rushmore…
$params["venueId"]=”3000225″; //We get this number from foursquare, its the id for each registered place.
$params["shout"]=”Im really at Mt Rushmore!”; //And we make a shout, just for fun
$params["broadcast"]=”public”; //Who can see the post?
$myvar=$foursquareObj->post(‘/checkins/add’,$params); //We make the call to the foursquareObj and send our params.
} catch (Exception $e) {
echo “Error: “.$e;
}
Upload your files, once again make sure the 5 needed files are uploaded. And open index.php You should see a link that directs you to the authorization site and as soon as you allow it you will be redirected and check in at Mr Rushmore.
Now, you should try a few more API calls to get used to this. For this, you should go through the API documentation and put special attention on how I chose the ‘/checkins/add’ parameter from the API documentation and applied it into our example.
Now, I’ll quote Joe in his nice description of the API’s methods:
As you look through the API documentation you will notice the different methods described like this:
URL: http://api.foursquare.com/v1/venue
Formats: XML, JSON
HTTP Method(s): GET
Requires Authentication: No, but recommended
Parameters:
- vid – the ID for the venue for which you want information
To call the venue details method above in our example we just need to change a couple things. We know this method takes in the single parameter vid and we can grab a venue’s ID from its Foursquare URL. 22242 in my example corresponds to the venue Town Talk Diner. On the next line, combine the HTTP method (GET) with the method name from the URL (venue) to form get_venue.
|
1
2
3
4
|
//Making a call to the API
$params = array("vid"=>22242);
$foursquareTest = $foursquareObj->get_venue($params);
print_r($foursquareTest->response)
|
You should think about saving the OAuth information of your users in a database so that they don’t have to authenticate each time, this is done easily if you already use users in your site with a simple call to your database. But extending in that field is not the point of this article.
For now, I hope that you are able to make successful calls to the Foursquare API. To see what else the foursquare-async library has to offer, you should check their wikipage. It’s awesome.
So finally, thanks to joesiwert for his article, which is largely the base of this one. And I hope many of you find this article useful. If you have any comments or questions, or anything remains unclear, please post it below and I’ll be happy to reply as I can.
Happy coding.
~Ryoku W. (w45p)
Posted in Ryoku Weil
Recent Comments