How To Use The Foursquare API v2 With OAuth And PHP [REVISED]

I’m sorry, this post (and the whole blog) has moved to a new permanent location.
<a href=””>Click here to see this post at</a>



~ by Ryoku Weil on August 29, 2011. 12:32 pm.

47 Responses to “How To Use The Foursquare API v2 With OAuth And PHP [REVISED]”

  1. This is awesome! Thanks so much for taking the time to do version 2 of this. I know many will benefit. Cheers!

  2. 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.

  3. 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 ;)

  4. thank You, this post saved my (professional) life! :D

  5. http://localhost/hmm/callback.php?code=FMYQRC1NQUOB1QCDH32JJ5GJGZ3X5QNPYXVKSFJDQ2DPYRCN

    Nooooo :(
    Do you know what’s wrong ?

    Great tutorial by the way, really easy to understand ! :D

  6. 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

  7. 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.

  8. Thanks!

  9. 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!
      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.

  10. 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!

  11. works like a charm. thank you so much for spending time to share this info with us.

  12. This is great. Thanks a lot mate.

  13. I am new to the API, thank you for the tutorial. It is great :)
    I have a question, do you know how I can use herenow, I want to see a list of users that check in a specific place (perhaps their names and check-in time)
    I think I should use herenow but I don’t know how to extract the data.

    I appreciate so much if you can help me.

    • Absolutely, that was actually the first part of the response I had to use. First you need to make a call to like this:

      //Declare the venue you want to fetch, in this case "The geographical center of New York State".
      //Declare your oauth_token (Which you got earlier).
      //Build the URL you're going to use.
      $url = "".$venue."/herenow?oauth_token=".$oauth_token;
      //And now we make the call.

      What we get in $response is a json object. To read it, we can decode it with json_decode(); and treat it like an object, like this:


      Finally, you can find any element of the response like an object. For example like this:

      echo $responseOBJ->response->hereNow->count; //returns the number of persons currently checked in at the venue.

      If you want to know all the structure of the response, you could try running a test var_dump(); on the response object and see what elements are inside.


      And that’s basically it. Note that you don’t need to authenticate as user to make a call to hereNow. All you need is an oauth token.
      I hope this helps you!

      • Thank you so much for the quick response. I managed to get the data I needed :)
        By the way, I was thinking the same about authenticating user for using the herenow, however in the documents it’s written that it’s needed or maybe I misunderstood. Anyway, thanks a million again :)

      • Don’t worry, if you want to find more information check the site
        That’s the list of all the endpoints and if you click on them it will tell you which need an authenticated user and which don’t.

      • Thanks,
        cheers :)

      • Sorry to bother again but I have one more question, do you think it’s possible to get the location of users when they check-in at a venue? The reason I’m asking is that I’m making a location-based game and I know that the API won’t return off-the-grid check-ins but still it would be more accurate If I can get the locations of users when they check in and perhaps sort the them by the ones who check in closer to the check-points. Thanks

      • Well, out of the foursquare API you can’t. BUT if you only allow users with HTML5 capable browsers, there is a geolocation tag. It is not VERY accurate, but it can work nicely. An example can be seen here

      • Alright, thanks so much again :)

  14. I’m just getting into the foursquare api and this tutorial is a great help, thanks alot. I still got an error in callback tho’.

    The index.php login-link works fine,
    Connect your foursquare account … click allow,
    callback.php gives me an redirect_uri_mismatch error (see below)

    the redirectUrl in index.php and callback.php are:
    $redirectUrl= “”;

    Got the ?code=XXX in callback.php.

    Could you please help me out? I think it is a redirectUrl mistake somewhere but can’t find it myself.


    Fatal error: Uncaught exception ‘EpiFoursquareBadRequestException’ with message ‘{“error”:”redirect_uri_mismatch”}’ in /mounted-storage/home11/sub001/sc16503-XOOX/ Stack trace: #0 /mounted-storage/home11/sub001/sc16503-XOOX/ EpiFoursquareException::raise(Object(EpiCurlManager), false) #1 /mounted-storage/home11/sub001/sc16503-XOOX/ EpiFoursquareJson->__get(‘response’) #2 /mounted-storage/home11/sub001/sc16503-XOOX/ EpiFoursquareJson->offsetGet(‘access_token’) #3 {main} thrown in /mounted-storage/home11/sub001/sc16503-XOOX/ on line 244

    • Im not completely sure about it out just looking at the error, I’d need to look at the code and may be run some tests. But if I had to take an educated guess, I would think it is your callback mismatches in the foursquare perms. Try checking your application settings in foursquare may be?
      I don’t think I ever got that error.

  15. Hi, I am getting this error.

    ( ! ) Fatal error: Call to undefined function curl_init() in C:\wamp\www\EpiFoursquare.php on line 119
    Call Stack
    # Time Memory Function Location
    1 0.0007 372592 {main}( ) ..\callback.php:0
    2 0.0039 571896 EpiFoursquare->getAccessToken( ) ..\callback.php:17
    3 0.0040 572928 EpiFoursquare->request( ) ..\EpiFoursquare.php:31

    Anyone please help me out :(

    • That’s most likely because cUrl is not available in your php configuration… Try running phpinfo(); in a blank page to see your configuration.
      To change it you have to edit the .ini file if you don’t know how you should ask your webmaster.

  16. Hi,
    By any chance, do you know how to use the push notification API or real-time API. I need to get the push notification when the users of my app check in a place or somebody checks-in in one of my venues. I appreciate if you help me. Thanks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: