How To Use The Foursquare API v2 With OAuth And PHP [REVISED]
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:
- Foursquare API v2 (Click for Documentation)
- Foursquare OAuth (Click for Documentation)
- Jmathai’s foursquare-async library (Which is absolutely awesome)
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:
- index.php
- callback.php
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.
1234//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)



This is awesome! Thanks so much for taking the time to do version 2 of this. I know many will benefit. Cheers!
I am getting the following error when the callback url loads. Any idea what could be causing this?
Thank you!
Fatal error: Uncaught exception ‘EpiFoursquareBadRequestException’ with message ‘{“error”:”invalid_grant”}’ in /home/marineboudeau/marineboudeau/lab/test/EpiFoursquare.php:247 Stack trace: #0 /home/marineboudeau/marineboudeau/lab/test/EpiFoursquare.php(211): EpiFoursquareException::raise(Object(EpiCurlManager), false) #1 /home/marineboudeau/marineboudeau/lab/test/EpiFoursquare.php(199): EpiFoursquareJson->__get(‘response’) #2 /home/marineboudeau/marineboudeau/lab/test/callback.php(18): EpiFoursquareJson->offsetGet(‘access_token’) #3 {main} thrown in /home/marineboudeau/marineboudeau/lab/test/EpiFoursquare.php on line 247
Yes, I was getting this response for quite a while and was a pain to fix it. I tried many things, including checking all the variables that are actually sent to the foursquare API. I would recommend you take a look at them, just to understand what the class is really doing.
However, I was able to fix this error by resetting my API keys with foursquare.
hi,
sorrie my terrible English, and very thanks for this amazing tutorial
there is an error in your callback.php code, at the beginning you declare $settoken variable but than whe you set token ($token = $foursquareObj->getAccessToken($tokentoken, $redirectUrl);) you call $tokentoken variable.
Just change $tokentoken in $settoken and everything works fine ;)
Thank you very much for pointing this out! Must have slipped through me when I was preparing the post. It has been fixed!
thank You, this post saved my (professional) life! :D
You’re welcome! I’m glad you found it useful!
http://localhost/hmm/callback.php?code=FMYQRC1NQUOB1QCDH32JJ5GJGZ3X5QNPYXVKSFJDQ2DPYRCN
Nooooo :(
Do you know what’s wrong ?
Great tutorial by the way, really easy to understand ! :D
Well, please copy and paste the error, I can’t see your own localhost directory.
And I’ll be glad to try to help.
Hi, nice tutorial but I got an issue. When calling this link => http://localhost/testApp/callback.php?code=FMYQRC1NQUOB1QCDH32JJ5GJGZ3X5QNPYXVKSFJDQ2DPYRCN
It keeps on loading, even 20 seconds long. I can’t retrieve the accessToken.
Fatal error: Maximum execution time of 20 seconds exceeded in C:\wamp\www\testAxxesFinder\EpiCurl.php on line 71
Call Stack
# Time Memory Function Location
1 0.0005 678560 {main}( ) ..\callback.php:0
2 0.0022 943008 EpiFoursquare->getAccessToken( ) ..\callback.php:19
3 0.0023 944448 EpiFoursquare->request( ) ..\EpiFoursquare.php:31
4 0.0028 951776 EpiFoursquareJson->__get( ) ..\EpiFoursquare.php:136
5 0.0028 952760 EpiCurlManager->__get( ) ..\EpiFoursquare.php:202
6 0.0028 952760 EpiCurl->getResult( ) ..\EpiCurl.php:177
Hmm, it sounds like the problem is in the way you’re receiving the json object. You could try debugging with a few echo’s or var_dumps to see where the information is lost.
I am getting the same error with wamp, windows 7. Max execution time long
Which same error? Do you have an output you can C&P here?
That kind of error means there’s an error in the configuration that’s causing the script to loop.
Hi… Great link…. But I am getting following error:
Need your help:
Fatal error: Uncaught exception ‘EpiFoursquareException’ in C:\xampp\htdocs\FB_LinkedIn\foursquare\EpiFoursquare.php:252 Stack trace: #0 C:\xampp\htdocs\FB_LinkedIn\foursquare\EpiFoursquare.php(208): EpiFoursquareException::raise(Object(EpiCurlManager), false) #1 C:\xampp\htdocs\FB_LinkedIn\foursquare\EpiFoursquare.php(196): EpiFoursquareJson->__get(‘response’) #2 C:\xampp\htdocs\FB_LinkedIn\callback.php(18): EpiFoursquareJson->offsetGet(‘access_token’) #3 {main} thrown in C:\xampp\htdocs\FB_LinkedIn\foursquare\EpiFoursquare.php on line 252
Sure, this problem was actually asked in a comment above yours. I got this same error for quite a while and it was a real pain. You should check the API we’re using to see how it is working, it will help you find bugs much easily.
However, for a quick fix, which I can’t tell will work for you but is certainly worth a try. I was able to get rid of this error by resetting my Foursquare API keys.
Thanks!
Thanks for the detailed explanation. It was very helpful. Index.php is working correctly but after I allow the application on the Foursqaure side I get redirected to a blank white page. If i refresh the page I get the same error as Arun and Marine (in the above comments). I have tried resetting the API and that didn’t work. Any other thoughts?
Thanks,
Thanks!
That error is most likely because your callback.php doesn’t do anything with the authorization/information it is getting.
So I would ask, what are the contents of the site you’re redirecting to?
I figured out my problem. The page was doing something (checking in at a location) but it wasn’t echoing anything. Hence the blank white page. Silly.
While I’m asking questions, I’d like to save the user’s tokens in a database so they don’t have to . What data exactly should be saved? Just $token["access_token"]?
Awesome! I hate when it’s something silly like that, sometimes it takes me ages to realize it!
Yeah, the user ID and the access token should be the only thing you need to make further requests once your user has been authenticated on your side.
Of course, it has the downside that if your site’s user access is compromised, a malicious user would be able to take advantage of those users’ FQ, and it would quickly be related to your site. However, if you authenticate with them each time you will sometimes force the user to make an extra step (FQ login), but in exchange their FQ activity won’t be compromised if something happens on your side.
I guess it’s just about weighting the risks and benefits.
Once I save the user ID and access token how do I know which to use with which user? In other words if I have 10 users of my app how do I know which of the ten users is currently using it so I can use the proper user ID and access token?
For that you would need to use sessions with PHP (Or the server-side language of your choice) and a Database table that has at least 4 rows: id, user_id, auth-token. Where you know which row corresponds to the user that is currently logged in your application.
Right. But how do I know who’s logged in if all they’re logged into is Foursquare? (I don’t have any other login to my app.)
Ah! Well for saving the auth token you would need to have a login in your app. But don’t worry, you don’t have to save it to do what you want. Once they have authorized your application all they need is to be logged in to foursquare.
I’m still not getting it (sorry for my thick headedness).
Scenario: User comes to my index page for the first time and clicks the foursquare login link. User is then prompted to authorize my app. Once they have done so they are forwarded to callback.php. What do I have to do to allow this user to go directly to callback.php to use the app without having to go back to index.php first?
Aah! Ok, I get it. So here are the steps that happen. -> You never send a user “directly” to callback.php, but if the foursquare user is logged in and has already authorized your application, it will look like that.
Step 1: User clicks on the foursquare link on your app for the first time.
Step 2: The user is asked to authenticate with his/her Foursquare credentials. If he is already logged in, this step will be skipped.
Step 3: The user is now prompted to allow your application to whatever you want to do. Once this happens, Foursquare knows (just like in facebook) that the user has allowed your application once, hence not needing him to give permissions again).
Step 4: The user is redirected to callback.php with authorization to do whatever.
After that, any other time the user tries to use the link will look like this.
Step 1: User clicks on your link.
Step 2: User authenticates with FQ credentials. Again, this step is skipped if he is already logged in.
Step 3: Foursquare knows your application has permissions, automatically redirects to callback.php without the user never knowing the difference.
In this scenario, if the user has given permissions to your application previously, and is logged in on Foursquare, it will look like he clicked the link and went directly to callback.php.
I hope this helps clear it up. =)
I’ve built out my app a bit. Once the user clicks the link on index.php they are sent to callback.php which presents a form that lists a set of venues. The user clicks the radio button to select a venue and submits the form. What I’d like to happen is that upon submitting the form the user checks into this venue but I keep getting an error as follows:
Fatal error: Uncaught exception ‘EpiFoursquareBadRequestException’ with message ‘{“error”:”invalid_grant”}’ in /home/golddave/public_html/foursquare/EpiFoursquare.php:244 Stack trace: #0 /home/golddave/public_html/foursquare/EpiFoursquare.php(208): EpiFoursquareException::raise(Object(EpiCurlManager), false) #1 /home/golddave/public_html/foursquare/EpiFoursquare.php(196): EpiFoursquareJson->__get(‘response’) #2 /home/golddave/public_html/foursquare/callback.php(23): EpiFoursquareJson->offsetGet(‘access_token’) #3 {main} thrown in /home/golddave/public_html/foursquare/EpiFoursquare.php on line 244
The form action = callback.php and the method is POST. I included an if statement that should execute the checkin if !empty($_POST) and uses $_POST["venue"] for the venue ID (which it gets from the form.
BTW this app is meant for me to use myself and not for public use.
Nevermind my last comment. I figured it out. Since I’m the only one using the app I just hard coded my acess token. That worked. I should have thought of it sooner.
Thanks again for the great post!
That works too!
works like a charm. thank you so much for spending time to share this info with us.
This is great. Thanks a lot mate.