Apps on Facebook.com

Introduction

Building an application on Facebook gives you the opportunity to deeply integrate into the core Facebook experience. By leveraging Facebook's integration points you can make your application feel native to the site, and create a seamless experience as users browse Facebook. Your application can integrate with all aspects of the Facebook user experience, from the profile page to bookmarks and the stream.

Applications that run within Facebook use all the same fundamental technologies as websites which integrate Facebook. Other than some differences in user authentication, all of the technologies discussed in the Facebook for Websites guide are available to applications on Facebook. You should start with that guide if you are new to developing with Facebook's APIs.

This guide walks you through the basics of getting your application set up and provides an overview of the key Facebook integration points.

Canvas
Bookmarks
Requests


Getting Started

When you build an application on Facebook, your application's primary page views come via the canvas page, an iframe hosted by Facebook at http://apps.facebook.com/your_app/ that points to your application. When you register your application, you choose a Canvas Page URL (your_app in the example above) and a Canvas Callback URL (e.g., http://www.example.com/canvas/). When a user visits http://apps.facebook.com/your_app/, Facebook loads your specified Canvas Callback URL within an iframe on that page. Likewise, when a user visits http://apps.facebook.com/your_app/foo/bar, Facebook loads the URL http://www.example.com/canvas/foo/bar in the canvas page iframe.

To get started, register your Facebook application. Once you have entered your basic application information, click the "Canvas" tab on the left hand side of the configuration screen, and specify a Canvas Page URL and Canvas Callback URL for your application:

Canvas configuration

To test that things are working properly, put up a simple page at your Canvas Callback URL and visit http://apps.facebook.com/your_app/. You should see your page load in the Canvas Page iframe:

A simple canvas app

In general, you should use only one Application ID for your base domain; a single Application ID allows you to create a full-featured application.


Authentication

Canvas applications use cookies to get user authentication information. The cookie includes a signature for all the values as the argument sig. The signature scheme is described in detail in the Canvas authentication guide. This PHP snippet returns all the official Facebook arguments and verifies the signature with your app's Application Secret:

<?php

define('FACEBOOK_APP_ID', 'your application id');
define('FACEBOOK_SECRET', 'your application secret');

function get_facebook_cookie($app_id, $application_secret) {
    $args = array();
    parse_str(trim($_COOKIE['fbs_' . $app_id], '\"'), $args);
    ksort($args);
    $payload = '';
    foreach ($args as $key => $value) {
        if ($key != 'sig') {
            $payload .= $key . '=' . $value;
        }
    }
    if (md5($payload . $application_secret) != $args['sig']) {
      return null;
    }
    return $args;
}

$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
echo 'The ID of the current user is ' . $cookie['uid'];

?>

When a user first visits your application, he or she will not be logged in to it. In this state, the cookie won't include uid. The recommended way to handle this case is to render a logged out version of your application with a Facebook login button, just like you would on a Facebook Connect site:

<html>
  <body>
    <?php if ($cookie) { ?>
      Your user ID is <?= $cookie['uid'] ?>
    <?php } else { ?>
      <fb:login-button>Install Example App</fb:login-button>
    <?php } ?>

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      FB.init({appId: 'your app id', xfbml: true, cookie: true});
      FB.Event.subscribe('auth.login', function(response) {
        // Reload the application in the logged-in state
        window.top.location = 'http://apps.facebook.com/your_app/';
      });
    </script>
  </body>
</html>

Check out the full PHP example application on GitHub for working "Getting Started" examples to copy to get started more quickly.


Making API Calls

We are currently in the process upgrading our core server API from the old REST API to the more modern Graph API. However, most of the methods required for canvas applications to integrate with Facebook have not yet been upgraded to the new API. For the time being, we recommend you continue using the old REST API in canvas apps instead of the new APIs for the sake of completeness.

Included in the arguments passed to your canvas callback URL is oauth_access_token. That argument can be used to make OAuth 2.0-authenticated calls to the REST API on behalf of the active user. For example, you can call the friends.get method by fetching the URL:

https://api.facebook.com/method/friends.get?
    format=json&
    access_token=...

In PHP, using the $args data structure above, you could fetch the current user's list of friends with:

$friends = json_decode(file_get_contents(
    'https://api.facebook.com/method/friends.get?' .
    'format=json&access_token=' .
    $cookie['oauth_access_token']));

Integration Points

Once you have developed your application using the REST API, you can integrate your applications with the communication channels and integration points Facebook provides to help grow your user base and re-engage existing users. The most important integration points are:


Stream Publishing

The stream is shown immediately to users upon logging into Facebook, making it core to the Facebook experience. You can prompt a user to publish stories about what she is doing in your application to her wall. If she publishes the story, it will appear on her wall and in all her friends' streams. Stories published from your application will include a link to your canvas page, and can optionally include an rich attachment. Effective use of stream publishing enables new users to discover your application, and existing users to re-engage with it.

A basic example of how to prompt a user to publish a story using the Facebook JavaScript SDK:

<script>
  FB.ui(
   {
     method: 'stream.publish',
     message: 'Check out this great app! http://apps.facebook.com/{your_app}'
   }
  );
</script>

The code above prompts the user with this dialog:

A Feed Form

Read the complete documentation on stream publishing and attachments.


Requests

Requests are a great way to enable users to invite their friends to your application, and for users to confirm connections from your application. As an example if user A wants to invite user B to join a group inside your application, user A could send user B a request, asking if user B would like to join. User B will receive the request and have the opportunity to respond. Users can easily send requests by simply clicking on friend's faces and hitting send.

Using FBML tags you can render request forms and friend selectors. There are many ways to customize your requests including the display of the friend selector, and what options are available to the recipient of the request. Complete documentation is available here. Iframe applications simply need to wrap the FBML tags in a <fb:serverFbml> tag for them to render.

An example request form:

<fb:serverFbml>
<script type="text/fbml">
<fb:fbml>
    <fb:request-form
        method='POST'
        type='join my Smiley group'
        content='Would you like to join my Smiley group? 
            <fb:req-choice url="http://apps.facebook.com/smiley/yes.php" 
                label="Yes" />'
            <fb:req-choice url="http://apps.facebook.com/smiley/no.php" 
                label="No" />'
        <fb:multi-friend-selector 
            actiontext="Invite your friends to join your Smiley group.">
    </fb:request-form>
</fb:fbml>
</script>
</fb:serverFbml>

The above code renders this on your canvas page:

Request form

After the user chooses a friend and clicks Send, the request will look like this to the recipient:

Request receive


Bookmarks and Counters

Bookmarks enable users to easily navigate back to your application. Bookmarks are automatically added for your application if a user starts using it. The bookmark will appear on left column of the homepage as well as on the top right of canvas pages. Once a user has your bookmark, you can set a counter which will appear next to it. You should set the counter to remind users of actions they need to take within your application.

When a user needs to return to your application, you should increment the counter:

$result = json_decode(file_get_contents(
    'https://api.facebook.com/method/dashboard.incrementCount?' .
    'format=json&access_token=' . 
    $cookie['oauth_access_token']));

This will increment the counter for this user:

Counter

Complete documentation on the counter can be found here.


Profile Tabs

Profile tab dev app

All profiles on Facebook have tabs. For example, users have a 'Photos' tab and a 'Links' tab by default. A user can add a tab for your application to her profile. When one of the user's friends visits her profile, the friend can check out the profile tab to get a sense of what your application is about, what the user has been doing in your application, and the friend can click back to your canvas page.

To enable users to add a profile tab, set a tab name and a tab URL in the Facebook Developer app:

Profile tab dev app

When a user navigates to the profile tab, Facebook makes a request to the tab URL you specified. A number of POST parameters are included with the request. You can verify the parameters using the same technique described here, but using $_POST parameters instead of the parameters from the cookie.

Facebook does not pass back who the viewing user is when she first visits your tab. Facebook does send the profile owner's ID in the fb_sig_profile_user parameter, so you know whose profile to display content for. See Authentication for more information.

Please Note: We've announced that tabs on user profile pages will no longer be supported after the end of the year. Tabs on other Facebook pages will continue to exist. See the roadmap for more information.


Like button

The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your application, a story appears in the user's friends' News Feed with a link back to your application.

To implement this feature, add Open Graph protocol <meta> tags in the <head> of the IFramed page or the canvas endpoint. Your canvas application’s ID will be automatically added as the fb:app_id. The og:url automatically points to your apps.facebook.com URL, and the og:site_name will be filled in as your application name.

If you’re interested in gaining distribution for content or giving users the ability to like a virtual good, you should not include the og:type tag. In this case, a stream story will still be published when your users like your content, but your URL will not be equivalent to a Facebook page. This means you will not have the ability to publish to users, and your pages will not show up on users' profiles.

If your canvas URL represents a real-world object (e.g. a cause, movie, product), add the appropriate og:type tag. In this case your canvas URL will be equivalent to a Facebook page. In addition to stream distribution, when a user likes your page you will have the ability to publish updates to them, and your URL will show up on users' profiles.

Additional details on the Like button can be found here.


Performance

To improve the speed and reliability of your application, check out the Performance Guide.