Canvas is an entire page that your application gets to use. On these pages you can choose to display content from another website through an iframe, so that is what we’re going to do. Ok, that it for the overview.
First you download Download the client library and copy the content of facebook-platform -> php to the Facebook application directory in your server – the same path of Canvas Callback URL.
On this occasion we are only going to have one page in our application, but it is 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.

Now, it is time to create the application itself:

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

FieldValue
Callback URLhttp://www.yoursite.com/yourapplication
Canvas Page URLMy Example Application
Can your Applications be added on Facebook?Yes
Post-Add URLhttp://apps.facebook.com/yourapplication
Developer ModeYes
Side Nav URLhttp://apps.facebook.com/yourapplication
Private InstallationYes

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 $friendsvariable:

$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:profiletags 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>’; echo ‘<td>’ . $friend[‘image’] . ‘</td>’; echo ‘<th scope=”row”><span>’ . $friend[‘name’] . ‘</span></th>’; echo ‘<td><abbr 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 uacctparameter.

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

Line 3: Including Facebook library

Lines 5-6: Declaring variables with API key and secret code

Line 8: Initializing a Facebook API

Line 10: Requiring the user to be logged into Facebook before using the application. If they are not logged in they will first be directed to a Facebook login page and then back to the application’s page. Then save the user unique id into $user_id variable

Line 12: Storing in the $friends array the unique id of all friends of yours

Line 14: This is the first FBML tag we see:Fb:name renders the name of the user specified by uid attribute. In this case, it will display your name. More information about Fb:name atthis page. You can see all available tags atthis page

Lines 16-20: Creating a string with all of your friends ids separated by comma, such as uid1,uid2,uid3,...,uidn

Line 22: users_getInfo returns a wide array of user-specific information for each user id passed. As you can see, I pass the whole list of friends and I only want to know their sex. More information aboutusers_getInfo atthis page

Line 24: Creating an array where I will store all genders

Line 26-31: Determining the % of each gender (male or female) in my friends list. You can see some additional math because sex value can be blank

Line 33: Displaying the results

Now that your application is completed, you can submit it to the Application directory.