Friday, February 25, 2011

How To Build A Facebook Application

Facebook, as you’ve probably noticed, is everywhere. And with that ubiquity comes a massive audience just waiting for your web app. Whether you’re looking to make things easier for your current users, or you have the perfect idea for a Facebook-only application, there are a few things you’ll need to know to get started.

Getting Started

FBML is basically the HTML you know and love, so we’ll include a heading and a stylesheet. The link element isn’t permitted and the @import rule isn’t supported either, so the simplest solution is to use a server-side include.
In order to install Facebook applications, or indeed to write your own, you need a Facebook account. You’ll also want to install the Developer application—this lets you create your own Facebook applications, as well as monitor their usage and configure various settings. You’ll also need your own web server; Facebook apps run direct from your own server—which means that you can write them in whatever language or framework you prefer. We’ll be using PHP in our examples, but the principles are the same for any language.

The Facebook Platform

Facebook have done a pretty good job of documenting the fundamental components of their platform over on their developer site. The platform consists of three core parts:
  • API – The API defines the various methods through which you can interact with Facebook. If you’re not familiar with the idea of an API, take a look at some recent Digital Web articles: APIs and Mashups for the Rest of Us and Hacking on Open APIs.
  • FBML – Facebook Markup Language is a custom markup language based on various bits of HTML. It’s similar to Coldfusion or ASP.NET’s tag-based syntax, and is used to define the pages in your application.
  • FQL – Facebook Query Language is SQL for Facebook. A powerful query language for situations where there are no existing helper methods in the API, or handy tags in FBML, to do exactly what you need.
We’ll be stepping through the development of a simple application which will demonstrate usage of FBML and the API.
As well as the core documentation, Facebook also makes available a set of useful tools and resources for developers. The tools are particularly useful for debugging raw API calls or tweaking FQL. The resources section contains official libraries for PHP and Java, with links to unofficial libraries for ActionScript, Cocoa, Coldfusion, .NET, Perl, Python and Ruby, and there is also a growing community wiki.
A typical page on Facebook is quite complicated, with lots of different elements on the page. Via FBML and the API you can influence most of these so it’s worth getting familiar with the terminology used before you get started. If you know your Profile from your News Feed then you’re good to go!

Example Application: Birthdays Book

We’re going to jump straight in to a full-blown application rather than start with a simple, but pretty useless, “Hello World” example. The application is called Birthdays Book, and it’s going to provide you with a list of your friends on Facebook, ordered by their upcoming birthdays.
The first thing you’ll want to do is set up your web server with the relevant Facebook client for your preferred language or framework. Our examples are in PHP so we want the official PHP library files.
Next you’ll want to create a new application from the Developer application you added to your Facebook profile earlier. Just click ‘Set Up New Application’ in the top right corner of the application page to get started. The next page has lots of hidden fields that you’ll need to fill in. Click ‘Optional Fields’ to get started. (Obviously you should replace the placeholders with the location and name of your own application.)
Field Value
Callback URL http://www.yoursite.com/yourapplication
Canvas Page URL My Example Application
Can your Applications be added on Facebook? Yes
Post-Add URL http://apps.facebook.com/yourapplication
Developer Mode Yes
Side Nav URL http://apps.facebook.com/yourapplication
Private Installation Yes
The Facebook New Application screen
Note that some of these only appear once you’ve answered certain questions. We’ll tick ‘Developer Mode’ and ‘Private Installation’ while we’re developing our app so as to avoid prying eyes—you can un-tick these once you’re ready for others to see and install your creation. There are lots of other settings you can tweak and information you can add, but this is a good starting point for our simple application.

Building The Application

On this occasion we’re only going to have one page in our application, but it’s still good form to move common behavior and configuration into a separate file. We start out by including the client library and setting our API key and application “secret” (password). You should be able to get these from the ‘My Applications’ page after you have set up your new application.
<?php
// Include the Facebook client library
require_once ('client/facebook.php');

// Set authentication variables
$appapikey = 'YOUR_API_KEY';
$appsecret = 'YOUR_APP_SECRET';

// Create the Facebook object
$facebook = new Facebook($appapikey, $appsecret);
We also set the url for where we are storing our code:
$appcallbackurl = 'YOUR_URL';
In order to use this application you’re going to have to be logged in to Facebook, so we’ll include a snippet from the Facebook code samples to make sure the current user is set up properly:
$user = $facebook->require_login();

//catch the exception that gets thrown if the cookie has an invalid session_key in it
try
{
  if (!$facebook->api_client->users_isAppAdded())
  {
    $facebook->redirect($facebook->get_add_url());
  }
}
catch (Exception $ex)
{
  //this will clear cookies for your application and redirect them to a login prompt
  $facebook->set_user(null, null);
  $facebook->redirect($appcallbackurl);
}
Save the above code as config.php. Now that we have our configuration file, we can start on our main application page—we’ll call this index.php. First we need to include the above configuration file:
<?php
require_once ('config.php');
Then we need to get a list of all the current user’s friends’ birthdays, which we will store in the $friends variable:
$friends = $facebook->api_client->users_getinfo($facebook->api_client->friends_get(), 'birthday');
?>
It’s worth breaking this line of code down, as it demonstrates how to make API calls using the library. We’re using two API methods in order to get the information we want: Users.getInfo and Friends.get.
(Note that the API docs do not provide details of the parameters or parameter order required by the library—you’ll need to delve into the source code of your chosen library to discover this information. The official libraries are well-documented with comments so you should be able to find your way around—just remember the API method Users.getInfo becomes the users_getinfo library method in the PHP library.)
<h1>Birthday Books</h1>
<style type="text/css">
  <?php include("style.css"); ?>
</style>
FBML is basically the HTML you know and love, so we’ll include a heading and a stylesheet. The link element isn’t permitted and the @import rule isn’t supported either, so the simplest solution is to use a server-side include. There are some more useful CSS tips on the developer wiki. Now we start with the bulk of our application.
First we’ll set-up a couple of empty arrays for storing information about our friends. We’ll also set a timestamp of the current day and month and store it in the variable $now. We do this so that later on we can work out whether a birthday has already occurred in this year. For a full list of formatting options for the date function see the PHP date page.
<table>
<?php

$now = strtotime(date("jS") . date("F"));

$with_birthday = array();
$without_birthday = array();
We already have a list of our friends in the $friends variable so let’s loop through that. What we’re aiming for at the other end is an array of our friends arranged into upcoming birthday order.
foreach ($friends as $friend) {
We’ll hold details of each person in a placeholder array called $person, then place each $person with birthday information into another array called $with_birthday. We’re going to want to get at their name, their profile picture, and details of their birthday. For ease of reference we store these against relevant keys in the array: name, image, month, day, year.
$person = array();
$person['name'] = '<fb:name uid="' . $friend[uid] . '"/>';
$person['image'] = '<fb:profile-pic uid="' . $friend[uid] . '" linked="true" size="square" />';
Here we have an example of the special FBML markup tags. Facebook users are referenced by a unique identifier which is returned by various API methods. We pass this uid value to the fb:name and fb:profile tags which return the name and profile picture of that user. A full list of FBML tags, along with lots of examples of usage, can be found on the wiki. Core documentation really is one of the strengths of the Facebook platform.
$person['day'] = date("jS", strtotime($friend[birthday]));
$person['month'] = date("F", strtotime($friend[birthday]));
$person['absolute_timestamp'] = strtotime($friend[birthday]);
$person['relative_timestamp'] = strtotime($person['month'] . $person['day']);

if ($person['relative_timestamp'] < $now)
{
  // birthday has already happened this year
  $person['year'] = date('Y', strtotime('+1 year'));
}
else
{
  // birthday still to come this year
  $person['year'] = date('Y');
}

$person['relative_timestamp_with_year'] = strtotime($person['month'] . $person['day'] . $person['year']);
Not everyone enters their birthday details into Facebook. We’ll store those people in the $without_birthday array for now. You could always do something with this information later.
if ($person['absolute_timestamp'])
  {
    $with_birthday[] = $person;
  }
  else
  {
    $without_birthday[] = $person;
  }
}
Now we have an array of people with birthdays we can loop through, but they’re in the wrong order. We’ll use the handy PHP array_multisort function to remedy the situation. array_multisort allows us to sort a given dataset ($with_birthdays) by one column (‘relative_timestamp_with_year’) using different order flags (in this case SORT_ASC, an ascending sort).
foreach ($with_birthday as $key => $row)
{
  $relative_timestamp_with_year[$key] = $row['relative_timestamp_with_year'];
}

array_multisort($relative_timestamp_with_year, SORT_ASC, $with_birthday);

?>
All we need to do now is loop through our final, sorted array and output a table of our friends together with their birthdays. We’ve thrown in some microformats to make it possible to export the data later:
<table>
<?php

$i = 0;
foreach ($with_birthday as $friend)
{
  echo '<tr class="vevent';
    if ($i == 0) {
      echo ' odd';
      $i = 1;
    } else {
      $i = 0;
    }
  echo '">';
  echo '<td>' . $friend['image'] . '</td>';
  echo '<th scope="row" class="summary vcard"><span class="fn">' . $friend['name'] . '</span></th>';
  echo '<td><abbr class="dtstart" title="' . $friend['year'] . '-' 
     . date('m', strtotime($friend['month'])) . '-' . substr($friend['day'],0,-2) . '">' 
     . $friend['day'] . ' ' . $friend['month'] . ' ' . $friend['year'] . '</td>';
  echo '</tr>';
}

?>
</table>
We now have version one of our Birthdays Book application. As a final touch, we’ll track how many people are using our application using Google Analytics. We can’t include Javascript in our pages, but there is a handy FBML tag, fb:google-analytics—just include your unique identifier from Google Analytics in the uacct parameter.
<fb:google-analytics uacct="YOUR_ANALYTICS_ID" page="Birthdays Book"/>
The finished application can be found at apps.facebook.com/birthdaysbook and you can download the source files at www.digital-web.com/extras/facebook_application.

Summary

Once you have a simple app up and running the next things you’ll want to look at are ways of interacting with the rest of Facebook. Take a look at Profile.setFBML, Feed.publishActionOfUser, and Notifications.send to get you started.
The Facebook platform isn’t standing still. Look out for the new mobile additions which allow for mobile optimised content, as well as sending SMS messages from your apps. Even more interesting are the new Data APIs, which let Facebook deal with the problem of scaling data storage while you get on with developing your applications.
If you can already build simple websites you can build Facebook applications. Being able to use your preferred language or framework really helps and the quality of the core documentation means the best way to learn is to jump in with your own ideas.
In the second part of this article we’ll be taking a closer look at getting information out of your Facebook applications and onto peoples profile pages.


No comments: