Friends

Rabu, 26 Januari 2011

How To Use The Foursquare API With OAuth And PHP

I started playing with the Foursquare API and one of the first things you need to do is figure out how to authenticate with Foursquare to make calls to the API. It took me awhile to figure this out and start making successful calls, so I thought others could benefit from a detailed tutorial. The goal of this tutorial is to demonstrate how to make calls to the Foursquare API using OAuth authentication and PHP. Foursquare has a helpful API discussion group I recommend checking out. Here are a few starting points that are helpful for this tutorial:

Setup your environment

Here is what you’ll need to complete this tutorial:
To begin, setup a project folder on your web server with the necessary files for this example.
Create a folder called “test” and create files inside that folder called index.php and callback.php. Then download the foursquare-async library (click “Download Source” in the upper right corner). Extract the files EpiCurl.php, EpiFoursquare.php and EpiOAuth.php to the test folder.
You now should have a folder called test that is accessible via a browser that contains these files:
  • index.php
  • callback.php
  • EpiCurl.php
  • EpiFoursquare.php
  • EpiOAuth.php
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

OAuth overview

You can authenticate with Foursquare’s API in one of two ways. The simpler, but less secure way is through basic access authentication. This method requires the user to provide their credentials (username/password) to your application and those credentials get passed right in the web request to the API. It gets the job done, but makes the user’s data more vulnerable. The user is also trusting that the application is storing their credentials securely.
The more secure option we will use in this example is OAuth authentication. 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.
Here are the steps for the OAuth workflow that this example will accomplish:
  1. Get request key and secret
  2. Provide a link to the Foursquare authorization page
  3. The user will approve or deny access and be redirected back to your application
  4. Get access key and secret (and store in your application database, but we don’t need to for this example)
  5. Use access key and secret to make API calls

Register with Foursquare to get your key and secret

The first thing we need to do is register our application with Foursquare to get a request key and secret for our application.  Go to http://foursquare.com/oauth/register, login and fill in 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” and Foursquare should generate a new key and secret for your application.  Your key and secret will be different than mine.

You can always return to http://foursquare.com/oauth/ to change these details or reset your key and secret.  At this point your application is registered and you have a key and secret to use.

Add code to the index.php file

The second task is filling in the index.php file with some code.  Open up index.php and add the following code.
Also if you are curious I am using the SyntaxHighlighter Evolved plug-in for displaying code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
 
//Put in the key and secret for your Foursquare app
//Your values will be different than mine
$consumer_key = "XB1NE31CJ4U22EF2GA53C4ULR3SL2BG21G1M5VTRCZ3K1XW5";
$consumer_secret = "3RHRD1KJLGFFHKDMD4SCE11NHNDCFUPOIPOQW4VGKLADFKC1";
$loginurl = "";
 
//Includes the foursquare-asyc library files
require_once('EpiCurl.php');
require_once('EpiOAuth.php');
require_once('EpiFoursquare.php');
 
session_start();
try{
  $foursquareObj = new EpiFoursquare($consumer_key, $consumer_secret);
  $results = $foursquareObj->getAuthorizeUrl();
  $loginurl = $results['url'] . "?oauth_token=" . $results['oauth_token'];
  $_SESSION['secret'] = $results['oauth_token_secret'];
} catch (Execption $e) {
  //If there is a problem throw an exception
}
 
echo "<a href='" . $loginurl . "'>Login Via Foursquare</a>"//Display the Foursquare login link
echo "<br>";
//This is your OAuth token and secret generated above
//The OAuth token is part of the Foursquare link above
//They are dynamic and will change each time you refresh the page
//If everything is working correctly both of these will show up when you open index.php
var_dump($results['oauth_token']);
echo "<br>";
var_dump($_SESSION['secret']);
 
?>
Now open index.php in your browser and you should see the following, only your two values will be different.

Add code to the callback.php file

Before you go to the login link you created, we need to add code to the callback.php file.  Now open that one and add this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
//Put in the key and secret for your Foursquare app
//Your values will be different than mine
$consumer_key = "XB1NE31CJ4U22EF2GA53C4ULR3SL2BG21G1M5VTRCZ3K1XW5";
$consumer_secret = "3RHRD1KJLGFFHKDMD4SCE11NHNDCFUPOIPOQW4VGKLADFKC1";
 
//Includes the foursquare-asyc library files
require_once('EpiCurl.php');
require_once('EpiOAuth.php');
require_once('EpiFoursquare.php');
 
session_start();
$foursquareObj = new EpiFoursquare($consumer_key, $consumer_secret);
$foursquareObj->setToken($_REQUEST['oauth_token'],$_SESSION['secret']);
$token = $foursquareObj->getAccessToken();
$foursquareObj->setToken($token->oauth_token, $token->oauth_token_secret);
 
try {
   //Making a call to the API
   $foursquareTest = $foursquareObj->get_user();
   print_r($foursquareTest->response);
 } catch (Exception $e) {
   echo "Error: " . $e;
 }
 
?>

Test it out

Now we are ready to try it all out and make a call to the Foursquare API.  This first call is going to bring back your user information.
Open up index.php in your browser again and click the login link.  This is the part where the user leaves your application and goes to authenticate with Foursquare directly.

Notice that your OAuth token is along for the ride in the URL:

Click on “Allow” and Foursquare will send the user to the callback page you created.

If everything worked correctly you will see your user information in the browser.
Try a few more API calls.  This will call back your check-in history:
1
2
3
//Making a call to the API
$foursquareTest = $foursquareObj->get_history();
print_r($foursquareTest->response);
If you want to make a call with parameters it looks like this.  This will get your user information along with your badges and mayorships:
1
2
3
4
//Making a call to the API
$params = array("badges"=>1, "mayor"=>1);
$foursquareTest = $foursquareObj->get_user($params);
print_r($foursquareTest->response);
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);
Note that every time you go through this process and click “Allow” Foursquare adds another entry for your application.  You can go to your Foursquare settings page to clean these up.  If you were building out an application you would want to save the user’s OAuth information in a database so they don’t have to re-authenticate each time.  For this example the OAuth information is just getting placed in a temporary browser session and thus we have to re-authenticate each time.

Hopefully at this point you are making calls to the API and getting data back.  To go beyond these basic calls refer to the Foursquare API documentation to see everything that is available.  Also refer to the wiki page for the foursquare-asyc library to learn more about how it works.

0 komentar:

Posting Komentar

300Ribu Dapat Website
### ###