Sponsored by

  • Intel
  • HP

JavaScriptTutorial

Discover Facebook’s developer tools

Techlightenment's systems architect Chas Coppard gives us a rundown of the APIs and plug-ins available to connect your site to Facebook

The Facebook Developer Platform is a collection of APIs and plug-ins that enable Facebook users to log in to your site using their Facebook identity. Techlightenment uses these tools to create engaging social user experiences on many of the apps and websites that we build for the world’s leading brands.

Once logged in, users can connect with their friends and interact with their Facebook profile through your site, and you will be able to connect with your users and access their social graph. The Developer Platform is comprised of the following components:

    •    Authentication (Login, Registration)
    •    Social Plugins (Like Button, Send Button, Activity Feed, Recommendations, Comments, Live Stream, Facepile)
    •    Facebook Dialogs (Feed, Friends, OAuth, Pay, Requests)
    •    Graph API
    •    Real-time Updates

In this tutorial we’ll build a web page containing many of these components. The focus will mostly be on client-side code using eXtensible Facebook Markup Language (XFBML), although some server-side code will also be covered.

Create the app

To start, register a new Facebook app here and note down the App ID and Secret Key. Be aware that certain Facebook plug-ins such as the Like button require that your site be reachable by Facebook, so you’ll need to host your test page on a publicly accessible server.

Next, create a page including the code to load the JavaScript SDK as shown below. Replace [APP_ID] with your App ID:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">  <head>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>    <title>Facebook Developer Plaform Example</title>  </head>  <body>    <div id="fb-root"></div>    <script>      window.fbAsyncInit = function() {        FB.init({appId: '[APP_ID]', status: true, cookie: true, xfbml: true});      };      (function() {        var e = document.createElement('script');        e.type = 'text/javascript';        e.src = document.location.protocol + '//connect.facebook.net/en_GB/all.js';        e.async = true;        document.getElementById('fb-root').appendChild(e);      }());    </script>    <script>      function trace(message) {          var div = document.getElementById('trace');          div.innerHTML = div.innerHTML + message + '<br/>';      }    </script>    <p><div id="trace" style="font-size:8pt; height:200px; width:500px; overflow:scroll;"></div></p>  </body></html>

Note the fbml schema attribute in the html tag and the script block, which asynchronously loads and initialises the Facebook JavaScript SDK. The fb-root element will contain the script include after this code has executed. Once the script has loaded it will parse any XFBML tags on your page and render them into HTML.

We’ve also added a trace function and a div so we can monitor events.

Login plug-in

The Facebook log-in plug-in allows users to connect to your site using their Facebook credentials. Techlightenment has seen the Login button being much more popular with users than standard registration forms and increases the rate of registration on a site or app. The simplest way to do this is to use the fb:login-button tag:

<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>

You can use the perms attribute to request extended permissions from your users, giving you greater access to their social graph, but be aware that the more permissions you request, the less likely your users are to grant them. A full list of permissions is available here.

You can customise the look and feel of the login button through its various attributes, but if you want complete control then you’ll need to create your own custom button and call the API’s FB.login (and FB.logout) functions when it is clicked:

<input type="button" id="login_button" onclick=&rdquo;login&rdquo; value="Login"/><script>  function login() {    FB.login(function(response) {}, {perms:'read_stream,publish_stream'});  }  function logout() {    FB.logout(function(response) {});  }</script>

Notice the perms are passed to the FB.login method as a JSON dict. We’ve left the response handlers for the FB.login and FB.logout methods empty because we’re going to handle these by subscribing to the auth-login and auth-logout events. This will ensure we receive these notifications from our custom login button as well as any other XFBML components that may invoke a login, such as the Registration plug-in.

<script>  FB.Event.subscribe('auth.login', function(response) {    loggedIn(response.session);  });          FB.Event.subscribe('auth.logout', function(response) {    loggedOut();  });    function loggedIn(session) {    var btn = document.getElementById('login_button');    btn.disabled = false;    btn.value = 'Logout';    btn.onclick = logout;  }  function loggedOut() {    var btn = document.getElementById('login_button');    btn.disabled = false;    btn.value = 'Login';    btn.onclick = login;  }</script>

In the handler methods I have added code to change our custom login button to a logout button and vice-versa. Later we will add more code to these handlers to perform various actions after login and logout.

Registration plug-in

The Facebook Registration plug-in enables users to sign up for your site with their Facebook account. If a user is logged into Facebook when they visit your site then the registration form will be pre-filled with their details. The form can be customised to allow extra fields to be included for data that is not present on Facebook. The form can even be used by non-Facebook users, thus providing a consistent experience for all users.

Let’s add a customised registration form to our page:

<fb:registration redirect-uri="[YOUR_SITE_URL]/submit.php"     fields='[{"name":"name"},             {"name":"birthday"},             {"name":"gender"},             {"name":"location"},             {"name":"email"},             {"name":"password", "view":"not_prefilled"},             {"name":"quote","description":"Favourite quote","type":"text"},             {"name":"colour","description":"Favourite colour","type":"select","options":               {"blue":"Blue","green":"Green","puce":"Puce"}},             {"name":"agree_tcs","description":"Agree to T&Cs","type":"checkbox"},             {"name":"anniversary","description":"Anniversary","type":"date"},             {"name":"favourite_city","description":"Favourite city","type":"typeahead","categories": ["city"]},       {"name":"captcha"}]'     onvalidate="validate"></fb:registration> <script>   function validate(form) {    errors = {};    if (form.quote == "") {      errors.quote = "You didn't enter a favourite quote";   }   if (form.colour == "") {      errors.colour = "Pick choose your favourite colour";   }   if (!form.agree_tcs) {      errors.agree_tcs = "You have not agreed to the T&Cs";   }   return errors;}</script>

The registration plug-in has following attributes:

The fields attribute is either a comma-separated list of Facebook fields (called named fields) or a JSON-formatted string of both named fields and custom fields. The available named fields are listed here. As well as standard Facebook fields they include a captcha field for bot detection and a password field. Note the "view":"not_prefilled", attribute we have added to the password field. This will prevent the password field being displayed if we are logged into Facebook. Adding “view”:”prefilled” to a field will do the opposite.

The custom fields each consist of a dictionary with name, description and type fields. Supported custom types are:

In our example the onvalidate attribute calls a custom validation function, allowing us to perform client-side validation.

When the user submits the form, Facebook will post a signed request to the URL specified in the redirect_uri attribute. We'll need to decrypt this in our server-side code. Save the following code as submit.php, replacing [APP_ID] and [APP_SECRET] with the values for your app:

<?phpdefine('FACEBOOK_APP_ID', '[APP_ID]');define('FACEBOOK_SECRET', '[APP_SECRET]');function parse_signed_request(&#36;signed_request, &#36;secret) {  list(&#36;encoded_sig, &#36;payload) = explode('.', &#36;signed_request, 2);   // decode the data  &#36;sig = base64_url_decode(&#36;encoded_sig);  &#36;data = json_decode(base64_url_decode(&#36;payload), true);  if (strtoupper(&#36;data['algorithm']) !== 'HMAC-SHA256') {    error_log('Unknown algorithm. Expected HMAC-SHA256');    return null;  }  // check sig  &#36;expected_sig = hash_hmac('sha256', &#36;payload, &#36;secret, &#36;raw = true);  if (&#36;sig !== &#36;expected_sig) {    error_log('Bad Signed JSON signature!');    return null;  }  return &#36;data;}function base64_url_decode(&#36;input) {    return base64_decode(strtr(&#36;input, '-_', '+/'));}if (&#36;_REQUEST) {  echo '<p>signed_request contents:</p>';  &#36;response = parse_signed_request(&#36;_REQUEST['signed_request'],                                    FACEBOOK_SECRET);  echo '<pre>';  print_r(&#36;response);  echo '</pre>';} else {  echo '&#36;_REQUEST is empty';}?>

When you submit the registration form, the submit page should decode the signed request and display its contents. In a real app you would create your user here.

I don't have space here to cover much of the Registration plug-in functionality, so for more details check out Facebook's documentation.

Like button

Now let’s add a Like button for the page:

<fb-like></fb-like>

When clicked, this will post a message to the user’s friends’ newsfeeds, linking back to your page. The user can optionally add a comment, which will also appear in the newsfeed. Note that our example page must be reachable by Facebook for the like to work, so you’ll need to host it publicly.

We can also target the like for a specific URL rather than the current page:

<fb:like href="[YOUR_SITE_URL]/product.html" show_faces="true"></fb:like>

In our example we’ve also added the show_faces attribute to display thumbnails of other users who have liked the object. Various other customisation attributes are described here.

Open Graph

If the target URL of a Like button represents a real-world entity (eg a movie or a product on a shopping website) then you can add Open Graph markup to the target page, which semantically describes the entity. Facebook will read these tags and treat your page as if it were a Facebook page. This means it will appear in the Likes and Interests section of the user’s profile and allow Facebook ads to be targeted at these users. You will also be able to publish updates to the users.

Open Graph markup consists of meta-tags that must be included in the <head> section of your page. The following six tags are required:

It is important to note that the link that appears in the newsfeed will be the value of og:url rather than the url attribute of the Like button. Also, if the value of og:url is changed, Facebook will treat the page as a new, different Like.

Now let’s create a new target page for our Like button with Open Graph markup. Add the code below to a file called product.html, replacing the values of the og:image, og:url and fb:admins meta-tags with appropriate values for your site:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#">  <head>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>    <title>Awesome Product</title>    <meta property="og:title" content="Awesome Product"/>    <meta property="og:type" content="product"/>    <meta property="og:image" content="[YOUR_SITE_URL]/product.png"/>    <meta property="og:url" content="[YOUR_SITE_URL]/product.html"/>    <meta property="og:site-name" content="Facebook Developer Platform Demo"/>    <meta property="fb:admins" content="581504668"/>  </head>  <body>    <img src="product.png"/>    <div>This is an awesome product. You love it!</div>  </body></html>

Now when you click the Like button you should see the Open Graph values in the newsfeed.

Like events

It is sometimes useful to know when a user has liked or unliked an entity. The Like button supports two events - edge.create and edge.remove - for this purpose. Techlightenment’s apps check for these events and use the actions to build the user’s social graph within the app; this helps you understand which users are engaging with the site. The href of the Like is passed as the first parameter in the handler. Let’s handle these events on our test page, simply logging them to our trace panel:

FB.Event.subscribe('edge.create', function(href, response) {  trace('edge.create: ' + href);});FB.Event.subscribe('edge.remove', function(href, response) {  trace('edge.remove: ' + href);});Send button

The Send button is a new addition from Facebook. It’s similar to a Like button but sends messages towards a specific set of friends rather than the user’s newsfeed. We’ll add one for our product page:

<fb:send href="[YOUR_SITE_URL]/product.html"></fb:send>

Rather than edge.create, the Send button generates a message.send event, which we'll also add to our page:

FB.Event.subscribe('message.send', function(href, response) {  trace('message.send: ' + href);});

As you can see, the handler only gets passed the href of the like so it is not possible to get the selected list of friends.

Note that the Like button also supports a new attribute send="true", which will render it as a combined Like and Send button.

Other plug-ins

There are a bunch of other Facebook plugins that are simple to add to your site and can significantly increase user engagement.

The Activity Feed plugin displays Facebook activity related to your site:

<fb:activity site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:activity>

The Recommendations plug-in shows recommendations for your site:

<fb:recommendations site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:recommendations>

The Comments plug-in provides a comments box, which also optionally publishes comments to the user's friends' News Feed:

<fb:comments href="[YOUR_SITE_URL]" num_posts="2" width="500"></fb:comments>

The Live Stream plugin allows users on your site to share activity and comments in real time:

<fb:live-stream event_app_id="[APP_ID]" width="600" height="400" xid="" always_post_to_friends="false"></fb:live-stream>
Facebook dialogs

Facebook Dialogs are standard dialogs you can include on your site to enable the user to interact with Facebook in various ways. The available dialogs are:

All dialogs are invoked through the FB.ui call. For our demo site we'll add a Feed Dialog. Add the following function:

function postToWall() {    FB.ui(    {        method: 'feed',        name: 'Facebook Dialogs Example',        description: 'This is a demo of the Feed Dialog.',        message: 'Enter your message'    },    function(response) {        if (response && response.post_id) {            trace('Post was published.');        } else {            trace('Post was not published.');        }     }   );}

Now add a button to invoke it:

<input type="button" id="post_button" disabled="true" value="Post to wall" onclick="postToWall();"/>Graph API

Once a user has granted permissions to your application, you may use the Facebook Graph API to pull information from their Social Graph. Which information you can access depends on the permissions that were requested during login and the privacy settings of the user's profile.

You can see a list of all available graph objects here. For this tutorial we are going to fetch a list of the user's likes and display them in our trace window.

Graph access is through the FB.api method, passing the path to the graph object. The path element “me” is used to represent the current user. All data is returned as JSON. Add the following code at the end of our loggedIn function to pull the likes and display them in our trace window.

FB.api('/me/likes', function(response) {    data = response['data'];    for (var key in data) {        trace(data[key]['name']);    }});Conclusion

Hopefully this whirlwind tour of the Facebook Developer Platform has shown you how quick and easy it is to add social content to your site. Although we've touched on most of the available features, there's a whole lot more you can do. You can download the tutorial files from https://github.com/chascoppard/chascoppard.github.com/tree/master/connectdemo. Check our Facebook's developer documentation and get coding!

Subscription offer

Log in to Creative Bloq with your preferred social network to comment

OR

Log in with your Creative Bloq account

site stat collection