You are on page 1of 6

Developing with the Facebook Platform and PHP

By David Mytton

First Steps
You must register for an API key before you can access the Facebook Platform. To do this,
you'll need to sign up for a Facebook account, then add the "Developer" application to your
Facebook account. You can do so by following the very simple instructions at
www.facebook.com/developers. Once it's added, you'll find that the Developer application
is very much like a normal Facebook group, but it has an additional link near the top of the
page called "My Applications" which, when clicked, will display a list of all the Facebook
applications that you have registered.
Once you've registered, you need to generate a key. Click the Apply for another key link and
you'll be walked through the process of creating a Facebook application. There are a
number of fields that you can provide optional information to, all of which are explained in
the quick start guide on the Facebook Developers site.
Your application is actually now ready to be used, although it won't do anything! Depending
on what you want your application to do, your users may need to perform a number of
steps to install your app into their Facebook accounts. The process usually consists of them
clicking an Install link, then confirming the request, as shown here.

Adding an application to a Facebook account (click to view image)

Once the application is added, it will appear in the user's news feed and on their mini-feed,
both of which are viewable by all their friends -- your first bit of free publicity!
Authentication
Your application is ready to be used, but of course you'll want to provide some content for
your user. The two most important features for web site owners are:
• the ability to publish items to the news feed
• the ability to add a profile box
Before you can use either of these pieces of functionality, you need to authenticate the
current user with the Facebook platform.
Each call to the Facebook Platform API requires a session key that identifies the user who's
logged in and is using the system. To obtain this key, you must make a call to the Facebook
API that redirects the user to log in to the Facebook web site and authorize the request.
One hurdle here is that this authorization provides a session key that only lasts for a certain
period of time -- around 24 hours. A key that didn't expire would be much more useful.
Fortunately, we can obtain such a key by following these two steps, which I'll explain in
more detail in a moment:
1. First, ask the user to authorize your application so that it can access the user's
account on Facebook. This returns auth token 1, which generates a session key that
expires after 24 hours.
2. Then, ask the user to generate auth token 2, which they should then paste into a
form on your web site. With this token in place, you'll be able to generate a session
key that never expires.
Once you have the final token, you can request a permanent session key by calling the
facebook.auth.getSession function.
But first, allow me to elaborate on those two steps.

Step 1 - Obtaining Auth Token 1


From your web site, direct your user to Facebook using a URL appended with your API key,
like this: www.facebook.com/login.php?api_key=APIKEY (where APIKEY should be replaced
with your own API key). If the user is not currently logged in, they'll be asked to do so.
The user will then be asked to accept any terms of service you set, and will be redirected
to the callback URL that you specified when creating the application. This can be changed
by editing your application through the Developer link in Facebook's sidebar.
With the redirect in place, Facebook will append ?auth_token=TOKEN to the URL, using an
actual authentication token. You can use this token with the facebook.auth.getSession
function; it's available as a GET variable in PHP.
However, because we want to get an infinite session, that auth token is actually irrelevant
-- we need to get another token that we can use to get a permanent session key. If we were
not interested in an infinite session, this is where we would stop. We could use the auth
token with the facebook.auth.getSession function below.

Step 2 - Obtaining Auth Token 2


Once your user has returned to your site after logging into Facebook, you'll need to send
them to www.facebook.com/code_gen.php?api_key=APIKEY. Back on the Facebook site, the
user will be asked to generate a token that will be displayed to them. They must then copy
and paste it into a form on your web site -- it's not passed through via GET/POST. It's up to
you to create a form that accepts this token from your user.
Once the user has submitted this second token to your site, you'll need to call the
facebook.auth.getSession function, passing the token as a parameter. This will finally
return a session key that you can use continuously to authenticate that user; this key could,
for example, be stored in the database alongside the user's account for easy retrieval in the
future.
It's important to note that, should the user delete your application from their Facebook
account, they'll need to repeat this authentication process in order to use your Facebook
application. You should therefore provide the option for the user to reset their Facebook
integration and set it up again. If you're storing the user's session key in the database, this
task would simply involve deleting that session key and taking the user through the two-
step authentication process above.

Calling facebook.auth.getSession

Now that you have an authentication token, you'll need to get yourself a session key for the
current user. This key is passed to every other Facebook API call, to identify the user upon
which your application is conducting an action.
Because we're not using a library provided by Facebook, we'll need to manually construct
the HTTP query that we'll send to Facebook, and write some code to process the response.
With every call, you must provide three required values, as described on the Facebook web
site:
• method - The first parameter is the method name. The method must be one of those
exposed by the API documentation, or the API will return error code 3 (with message
Unknown method).
• api_key - The vendor-specific API key corresponding to the site making the API call.
This is the same key that we used in the login request, as provided to you when you
registered your application.
• sig - The signature for the method call.
The signature is generated as described by this pseudocode:
args = array of args to the request, formatted in arg=val pairs
sorted_array = alphabetically_sort_array_by_keys(args);
request_str = concatenate_in_order(sorted_array);
signature = md5(concatenate(request_str, secret))
Rather than having to do this manually every time you need to perform an HTTP query, I've
written a short do_facebook_request() function that is available for download. This takes
the optional parameters that are to be sent for a specific API function, as well as the name
of that function. It constructs and sends the request, then returns the result:
do_facebook_request.php
<?php
/**
* Sends an API request to Facebook
*
* @param array $parameters Array of parameters to send
* @param string $method The API function to call
* @return array Returns array of data returned
*/
function do_facebook_request($parameters, $method)
{
if (empty($parameters) || empty($method))
{
return false;
}

// Build Facebook args


// http://developers.f8.facebook.com/documentation.php?v=1.0&doc=auth
$data['api_key'] = 'API KEY';
$data['method'] = $method;
$data['v'] = '1.0';

// Loop through and set as array


foreach ($parameters as $key => $value)
{
$data[$key] = $value;
}

// Sort
ksort($data);

$args = '';

foreach ($data as $key => $value)


{
$args .= $key.'='.$value;
}

$data['sig'] = md5($args.'secret');

// Get a Facebook session


$response = do_post_request('http://api.facebook.com/restserver.php', $data);

// Handle XML
$xml = simplexml_load_string($response);

return $xml;
}

/**
* Sends a POST request with necessary parameters
* Code based on http://netevil.org/node.php?nid=937
* We use HTTP here. See http://uk2.php.net/manual/en/wrappers.http.php
*
* @param string $url The URL to perform the POST on. Include http://
* @param array $data The data to POST in array format
* @param array $optional_headers Any HTTP headers. See http://www.php.net/manual/sv/
function.header.php or http://www.faqs.org/rfcs/rfc2616
* @param string $method The method for the request. Defaults to POST
* @return string The response
*/
function do_post_request($url, $data, $optional_headers = NULL, $method = 'POST')
{
// Just defining some parameters for the request here
// See http://uk2.php.net/manual/en/wrappers.http.php#AEN268663 for additional
context options
$params = array('http' => array('method' => $method, 'content' =>
http_build_query($data)));

if ($optional_headers !== NULL) // Add in any additional headers


{
$params['http']['header'] = $optional_headers;
}

// Makes it easier to add additional parameters such


// as any optional HTTP headers as set above
$context = stream_context_create($params);

$fp = @fopen($url, 'rb', false, $context);

if (!$fp)
{
return false;
}

$response = @stream_get_contents($fp);

if ($response === false)


{
fclose($fp);
return false;
}

fclose($fp);

return $response;
}
?>
The code is part of a class I wrote for the welovelocal application, and is based on the code
provided in Wez Furlong's blog. You'll need to replace the API_KEY on line 20 with your own
key, as well as the secret on line 40 to generate the signature. The secret is a string
generated by Facebook, and is displayed underneath your API key on the My Applications
section of the Developer application within Facebook.
Here's an example in which we're calling the do_facebook_request function:
$xml = do_facebook_request(array('auth_token' => $token), 'facebook.auth.getSession');
After the request has been processed, the $xml variable will contain something that looks
like this:
<?xml version="1.0" encoding="UTF-8"?>
<auth_getSession_response xmlns="http://api.facebook.com/1.0/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://api.facebook.com/1.0/
http://api.facebook.com/1.0/facebook.xsd">
<session_key>5f34e11bfb97c762e439e6a5-8055</session_key>
<uid>8055</uid>
<expires></expires>
</auth_getSession_response>
This is the session_key that you can store and use for all subsequent requests. See the
auth.getSession documentation for detailed information.

Get more related articles at: http://facebook-friends.com/

Cheers!

You might also like