X Forward

Labs.

Facebook Development PHP Utility Class

Project Description

I’ve built a few Facebook applications and integrated Facebook Connect into some sites in the past and I found myself running into the same thing every time: sub-par documentation by Facebook.

Now, don’t get me wrong, they have a fairly good reference for the API and FBML and all that stuff. But when it comes to actually using the PHP client libraries they provide, there is little to no documentation. There are code snippets, and some 3rd party examples/tutorials, but none of them really *document* the libraries. So, after many hours of asking uncle Google, and sifting through the actual Facebook code to find undocumented methods to perform the tasks I needed, I decided to make my own PHP utility class to make my life easier.

This utility class is very simple and straightforward, but it is also very powerful because it is so easy to use. You can download it here: PHP Facebook Utility Just copy and paste the code into a file named FBUtil.php.

Here’s a quick rundown of the methods:

The most important method is do_fb_method(), it is really the only one you need. All of the other methods are used by do_fb_method() to perform its task. Although each method could be of some use on its own. do_fb_method() performs arbitrary Facebook API methods, it takes care of generating the request signature, signing the request, and posting it to the API. Here is a simple usage example:


// This example publishes some text to a user’s wall
// Refer to the Facebook API reference for what action links are.
// An action link is basically a short text link you can have attached to the wall post. It must be an array that contains associative arrays that describe the link text and target URL.
$action_links = array( array(‘text’ => ‘Get GridPong3D’, ‘href’ => ‘http://‘.$_SERVER[‘HTTP_HOST’].‘/thegames/gridpong’));
$params[‘api_key’] = $fb_api_key; // your Facebook API key
$params[‘call_id’] = microtime(true);
$params[‘method’] = ‘facebook.stream.publish’; // the method you want to perform
$params[‘uid’] = $fb_userid; // the Facebook userid of the user whose wall you are posting to
$params[‘message’] = “thinks Brett Duncavage is totally awesome!“; // the message you wish to post
$params[‘action_links’] = json_encode($action_links); // you must json encode the action links array
$params[‘v’] = ‘1.0’; // I believe this is always 1.0 at the moment
FBUtil::do_fb_method($fb_secret, $params); // call the do_fb_method() with your Facebook secret key and the parameter associative array. The XML response will be returned.

That’s it! Pretty easy right?

PS: Sorry about the almost-impossible-to-read formatting of the sample code.