Monday, July 11, 2011

Facebook for Websites

Facebook for Websites

Facebook Platform enables you to make your website more social. You can use our Social Plugins, such as the Like Button to drive user engagement with a single line of HTML. Our Login Button and Registration Plugin let you simplify or eliminate your own user registration and sign-in. Lastly, the Graph API lets you access the full social graph of a given user, allowing you to create a truly deep personal experience.
This guide will walk you through the basics of creating a web app that leverages these features. The examples in this guide use PHP for server-side programming and HTML/JavaScript for client-side code. These examples are very straightforward and easily translatable to other languages.
In this document:


Social Plugins

Social Plugins are the easiest way to get started with Facebook Platform. The plugins are embeddable social features that can be integrated in your site with a line of HTML. Because they are hosted by Facebook, the plugins are personalized for all users who are currently logged into Facebook, even if they are visiting your site for the first time.
The most important Social Plugin is the Like Button, which enables users to share your page with their friends with one click. You can add a Like button to any page with an iframe tag:
<html>
    <head>
      <title>My Great Web page</title>
    </head>
    <body>
       <iframe src="http://www.facebook.com/plugins/like.php?href=YOUR_URL"
        scrolling="no" frameborder="0"
        style="border:none; width:450px; height:80px"></iframe>
    </body>
 </html>
There are a number of options for the Like Button, including the option to include the names and profile pictures of the user's friends who have also liked the page. Here is a Like Button for the Facebook Developers site:
Once you have included the Like Button into your site, you can use other Social Plugins to turn those user interactions into more engaging experiences throughout your site. You can use the Activity Feed Plugin to show users a stream of the recent likes and comments from their friends on your site. You can use the Recommendations Plugin to show personalized page recommendations to your users based on the likes and comments across your entire site. Here are the activity and recommendations plugins for the Facebook Developers site:
Most Social Plugins can be integrated with your site by simply including the iframe tag for the plugin within your page. There are several Social Plugins, such as Comments and Live Stream, that require the use of XFBML (eXtended Facebook Markup Language). XFBML is a set of XML elements that can be included in your HTML pages to display Social Plugins. When your page is loaded, any XFBML elements found in the document are processed by the JavaScript SDK, resulting in the appropriate plugin being rendered on your page.
We provide XFBML elements for all of our Social Plugins. For example, the Like Button can also be placed on your page by using the XFBML equivalent:
 <html>
    <head>
      <title>My Great Web page</title>
    </head>
    <body>
      <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
      <fb:like></fb:like>
    </body>
 </html>
The iframe versions of our plugins are the most widely, used as they require a minimal understanding of Facebook Platform. The XFBML versions are typically used by more sophisticated developers looking for more control and consistency in their codebase.
Getting started could not be simpler. Just select the plugin from our Social Plugin page and follow the steps in the provided configurator. These configurators, like the below, help you setup your plugin and generate all the code you need to add it to your site.
Like Config


Authentication

Facebook helps you simplify and enhance user registration and sign-in by using Facebook as your login system. Users no longer need to fill in yet another registration form or remember another username and password to use your site. As long as the user is signed into Facebook, they are automatically signed into your site as well. Using Facebook for login provides you with all the information you need to create a social, personalized experience from the moment the user visits your site in their browser.
Facebook Platform uses OAuth 2.0 for authentication and authorization. While you can add login to your site using OAuth 2.0 directly (see our Authentication Overview), the open source JavaScript SDK is the simplest way to use Facebook for login.
The JavaScript SDK requires that you register your website with Facebook to get an App ID (or appId). The appId is a unique identifier for your site that ensures that we have the right level of security in place between the user and your website. The following example shows how to load the JavaScript SDK once you have your appId:
 <html>
    <head>
      <title>My Facebook Login Page</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js"></script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });
      </script>
    </body>
 </html>
Once you have loaded the JavaScript SDK into your page and initialized it with your appId, you simply add the Login Button to your page using the <fb:login-button> XFBML element as shown below:
 <html>
    <head>
      <title>My Facebook Login Page</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js"></script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });
      </script>
      <fb:login-button>Login with Facebook</fb:login-button>
    </body>
 </html>
When the user loads the page in their browser, the JavaScript SDK renders the Login Button on your page:
Login Button
In order to log the user into your site, three things need to happen. First, Facebook needs to authenticate the user. This ensures that the user is who they say they are. Second, Facebook needs to authenticate your website. This ensures that the user is giving their information to your site and not someone else. Lastly, the user must explicitly authorize your website to access their information. This ensures that the user knows exactly what data they are disclosing to your site.
These steps may seem complex, but fortunately all you need to do is use the fb:login-button and all the user needs to do is click it. When the user does so, the JavaScript SDK will ensure that the user is signed into Facebook and that the request is coming from your website. We then present an authorization dialog in their browser that provides information about your site and the user data you are requesting. By default, this dialog looks like the below:
Authorization Dialog
If the user clicks Allow, we will give your site access to the requested information. If the user clicks, Don't Allow the dialog will close and no information will be available to your website. By default, we give you access to the user's name, picture and any other data they have shared with everyone on Facebook (see the User Graph object for more details).
If you need access to more information, such as the user's email address, etc. you must request permissions for this information. If you can do this by adding the permissions you need to the perms attribute of the fb:login-button like below:
 <html>
    <head>
      <title>My Facebook Login Page</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js">
      </script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });
      </script>
      <fb:login-button perms="email,user_checkins">
         Login with Facebook
      </fb:login-button>
    </body>
 </html>
When the user clicks the login button from this page, they will see the below authorization dialog. Note that there are now two new sections that outline the additional information that your site is requesting permission to access.
Authorization Permissions
A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your site requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your site.
In addition to Login Button, we offer the Registration Plugin. The Registration Plugin offers two key features not available with the Login Button: support for users without Facebook accounts and the ability to request additional user information that Facebook may not have or make available.
Using the Registration Plugin is just as simple as using the Login Button. You merely need to use the fb:registration XFBML element in your page, rather than the Login Button:
 <html>
    <head>
      <title>My Facebook Registration Page</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js">
      </script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });
      </script>
         <fb:registration
            fields="[{'name':'name'}, {'name':'email'},
            {'name':'favorite_car','description':'What is your favorite car?',
            'type':'text'}]" redirect-uri="URL_TO_LOAD_AFTER_REGISTRATION">
    </fb:registration>
    </body>
 </html>
If the user is not already logged into Facebook, they will see the below form. Notice that the form is not prefilled with any user information, but there is a link to login to Facebook to do so.
Registration No Login
If the user is already logged into Facebook or decides to login from the registration form, they will see the below. Notice that the form is now prefilled with their Facebook information.
Registration Login
Once the user reviews the information and/or enters any custom fields (in the above example, favorite_car is a custom field that the user must populate directly, as it is not data that is currently part of the user's Facebook profile), the user clicks Register. This will start the authentication and authorization process which is denoted by the below dialog:
Registration Sign in
With authentication/authorization complete, we redirect the user to whatever URL you placed into the redirect-uri attribute of the fb:registration element which completes the registration process.
The Login Button and the Registration Plugin allow you to easily bring the more than 500 million Facebook users to your site. In doing so, you can also eliminate or reduce whole parts of your codebase. You can learn more about how to add Login with Facebook to your site by reading the documentation for the Login Button, the Registration Plugin and the JavaScript SDK.


Personalization

While Social Plugins offer a easy way to personalized your site, once you have added login to your site, you can access the full power of the Graph API to create an even deeper personalized experience for your users. You can use the Graph API to access the user's Facebook profile, using this data in your own custom experience. You can use the Graph API to publish to the user's Facebook Wall and their News Feed. You can use the Graph API to access the user's social graph, bring their friends directly to your site all in your own custom experience.
The Javascript SDK provides a straightforward way to access the Graph API: FB.api. This function takes a string argument which specifies the part of the Graph to target and a callback function that is invoked when the call completes. The following demonstrates how to use FB.api() to retrieve the user's picture and name from the Graph API and display it on a page within your site:
<html>
    <head>
      <title>My Great Website</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js">
      </script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });
         FB.api('/me', function(user) {
           if(user != null) {
              var image = document.getElementById('image');
              image.src = 'http://graph.facebook.com/' + user.id + '/picture';
              var name = document.getElementById('name');
              name.innerHTML = user.name
           }
         });
       </script>
           <div align="center">
           <img id="image"/>
           <div id="name"></div>
           </div>
    </body>
 </html>
Another way to personalize your site with the JavaScript SDK is the FB.ui function. This function invokes our Platform Dialogs within the context of your site. You can use the FB.ui function to post to the user's Feed or allow them to invite new friends. The following demonstrates how to use the Feed Dialog from your site:
<html>
    <head>
      <title>My Great Website</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js">
      </script>
      <script>
         FB.init({ 
            appId:'YOUR_APP_ID', cookie:true, 
            status:true, xfbml:true 
         });

         FB.ui({ method: 'feed', 
            message: 'Facebook for Websites is super-cool'});
      </script>
     </body>
 </html> 
When this page is loaded in the user's browser, the JavaScript SDK will render the below dialog that the user can use to post to their feed. You can set a number of defaults for the dialog, which the user can then modify or override prior to posting.
Web Dialog
One of the best ways to learn what is possible with the JavaScript SDK is our JavaScript Console. The tool offers a host of examples that you can execute directly in the console itself before you make any changes to your site.
The Javascript SDK lets you access the Graph API and Platform Dialogs from client-side code but some of the most interesting integrations involve accessing the Graph API from server-side code running on your web server. The JavaScript SDK saves the details for the logged in user in a cookie named fbs_YOUR_APP_ID. The following PHP example shows you how to use access this cookie and then customize the generated page based on this information:
<?php

define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');

function get_facebook_cookie($app_id, $app_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 . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}

$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);

$user = json_decode(file_get_contents(
    'https://graph.facebook.com/me?access_token=' .
    $cookie['access_token']));

?>
<html>
  <body>
    <?php if ($cookie) { ?>
      Welcome <?= $user->name ?>
    <?php } else { ?>
      <fb:login-button></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 ?>', status: true,
               cookie: true, xfbml: true});
      FB.Event.subscribe('auth.login', function(response) {
        window.location.reload();
      });
    </script>
  </body>
</html>
Using the JavaScript SDK cookie is only one of several ways to access user credentials and information from server-side code. Our Security Guide highlights how to perform authentication and authorization directly from your web server allowing you to access the Graph API without using any client-side code.