Monday 29 July 2013

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

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:
  • View source
  • Copy code
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
  3.   <head>
  4.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5.     <title>Facebook Developer Plaform Example</title>
  6.   </head>
  7.   <body>
  8.     <div id="fb-root"></div>
  9.     <script>
  10.       window.fbAsyncInit = function() {
  11.         FB.init({appId: '[APP_ID]', status: true, cookie: true, xfbml: true});
  12.       };
  13.       (function() {
  14.         var e = document.createElement('script');
  15.         e.type = 'text/javascript';
  16.         e.src = document.location.protocol + '//connect.facebook.net/en_GB/all.js';
  17.         e.async = true;
  18.         document.getElementById('fb-root').appendChild(e);
  19.       }());
  20.     </script>
  21.     <script>
  22.       function trace(message) {
  23.           var div = document.getElementById('trace');
  24.           div.innerHTML = div.innerHTML + message + '<br/>';
  25.       }
  26.     </script>
  27.  
  28.     <p><div id="trace" style="font-size:8pt; height:200px; width:500px; overflow:scroll;"></div></p>
  29.   </body>
  30. </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:
  • View source
  • Copy code
  1. <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:
  • View source
  • Copy code
  1. <input type="button" id="login_button" onclick=&rdquo;login&rdquo; value="Login"/>
  2. <script>
  3.   function login() {
  4.     FB.login(function(response) {}, {perms:'read_stream,publish_stream'});
  5.   }
  6.  
  7.   function logout() {
  8.     FB.logout(function(response) {});
  9.   }
  10. </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.
  • View source
  • Copy code
  1. <script>
  2.   FB.Event.subscribe('auth.login', function(response) {
  3.     loggedIn(response.session);
  4.   });
  5.        
  6.   FB.Event.subscribe('auth.logout', function(response) {
  7.     loggedOut();
  8.   });
  9.  
  10.   function loggedIn(session) {
  11.     var btn = document.getElementById('login_button');
  12.     btn.disabled = false;
  13.     btn.value = 'Logout';
  14.     btn.onclick = logout;
  15.   }
  16.  
  17.   function loggedOut() {
  18.     var btn = document.getElementById('login_button');
  19.     btn.disabled = false;
  20.     btn.value = 'Login';
  21.     btn.onclick = login;
  22.   }
  23. </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:
  • View source
  • Copy code
  1. <fb:registration redirect-uri="[YOUR_SITE_URL]/submit.php"
  2.     fields='[{"name":"name"},
  3.             {"name":"birthday"},
  4.             {"name":"gender"},
  5.             {"name":"location"},
  6.             {"name":"email"},
  7.             {"name":"password", "view":"not_prefilled"},
  8.             {"name":"quote","description":"Favourite quote","type":"text"},
  9.             {"name":"colour","description":"Favourite colour","type":"select","options":
  10.               {"blue":"Blue","green":"Green","puce":"Puce"}},
  11.             {"name":"agree_tcs","description":"Agree to T&Cs","type":"checkbox"},
  12.             {"name":"anniversary","description":"Anniversary","type":"date"},
  13.             {"name":"favourite_city","description":"Favourite city","type":"typeahead","categories": ["city"]},
  14.               {"name":"captcha"}]'
  15.     onvalidate="validate">
  16. </fb:registration>
  17.  
  18. <script>
  19.   function validate(form) {
  20.     errors = {};
  21.     if (form.quote == "") {
  22.       errors.quote = "You didn't enter a favourite quote";
  23.    }
  24.    if (form.colour == "") {
  25.       errors.colour = "Pick choose your favourite colour";
  26.    }
  27.    if (!form.agree_tcs) {
  28.       errors.agree_tcs = "You have not agreed to the T&Cs";
  29.    }
  30.    return errors;
  31. }
  32. </script>
The registration plug-in has following attributes:
http://media.netmagazine.futurecdn.net/files/images/2011/05/table1.jpg
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:
http://media.netmagazine.futurecdn.net/files/images/2011/05/table2.jpg
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:
  • View source
  • Copy code
  1. <?php
  2. define('FACEBOOK_APP_ID', '[APP_ID]');
  3. define('FACEBOOK_SECRET', '[APP_SECRET]');
  4.  
  5. function parse_signed_request($signed_request, $secret) {
  6.   list($encoded_sig, $payload) = explode('.', $signed_request, 2);
  7.  
  8.   // decode the data
  9.   $sig = base64_url_decode($encoded_sig);
  10.   $data = json_decode(base64_url_decode($payload), true);
  11.  
  12.   if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  13.     error_log('Unknown algorithm. Expected HMAC-SHA256');
  14.     return null;
  15.   }
  16.  
  17.   // check sig
  18.   $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  19.   if ($sig !== $expected_sig) {
  20.     error_log('Bad Signed JSON signature!');
  21.     return null;
  22.   }
  23.  
  24.   return $data;
  25. }
  26.  
  27. function base64_url_decode($input) {
  28.     return base64_decode(strtr($input, '-_', '+/'));
  29. }
  30.  
  31. if ($_REQUEST) {
  32.   echo '<p>signed_request contents:</p>';
  33.   $response = parse_signed_request($_REQUEST['signed_request'],
  34.                                    FACEBOOK_SECRET);
  35.   echo '<pre>';
  36.   print_r($response);
  37.   echo '</pre>';
  38. } else {
  39.   echo '$_REQUEST is empty';
  40. }
  41. ?>
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.
http://media.netmagazine.futurecdn.net/files/images/2011/05/CustomRegForm.jpg
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:
  • View source
  • Copy code
  1. <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:
  • View source
  • Copy code
  1. <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:
http://media.netmagazine.futurecdn.net/files/images/2011/05/table3.jpg
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:
  • View source
  • Copy code
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#">
  3.   <head>
  4.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5.     <title>Awesome Product</title>
  6.     <meta property="og:title" content="Awesome Product"/>
  7.     <meta property="og:type" content="product"/>
  8.     <meta property="og:image" content="[YOUR_SITE_URL]/product.png"/>
  9.     <meta property="og:url" content="[YOUR_SITE_URL]/product.html"/>
  10.     <meta property="og:site-name" content="Facebook Developer Platform Demo"/>
  11.     <meta property="fb:admins" content="581504668"/>
  12.   </head>
  13.   <body>
  14.     <img src="product.png"/>
  15.     <div>This is an awesome product. You love it!</div>
  16.   </body>
  17. </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:
  • View source
  • Copy code
  1. FB.Event.subscribe('edge.create', function(href, response) {
  2.   trace('edge.create: ' + href);
  3. });
  4.  
  5. FB.Event.subscribe('edge.remove', function(href, response) {
  6.   trace('edge.remove: ' + href);
  7. });

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:
  • View source
  • Copy code
  1. <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:
  • View source
  • Copy code
  1. FB.Event.subscribe('message.send', function(href, response) {
  2.   trace('message.send: ' + href);
  3. });
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:
  • View source
  • Copy code
  1. <fb:activity site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:activity>
http://media.netmagazine.futurecdn.net/files/images/2011/05/activity.png
The Recommendations plug-in shows recommendations for your site:
  • View source
  • Copy code
  1. <fb:recommendations site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:recommendations>
http://media.netmagazine.futurecdn.net/files/images/2011/05/recommendations.png
The Comments plug-in provides a comments box, which also optionally publishes comments to the user's friends' News Feed:
  • View source
  • Copy code
  1. <fb:comments href="[YOUR_SITE_URL]" num_posts="2" width="500"></fb:comments>
http://media.netmagazine.futurecdn.net/files/images/2011/05/comments.png
The Live Stream plugin allows users on your site to share activity and comments in real time:
  • View source
  • Copy code
  1. <fb:live-stream event_app_id="[APP_ID]" width="600" height="400" xid="" always_post_to_friends="false"></fb:live-stream>
http://media.netmagazine.futurecdn.net/files/images/2011/05/livefeed.png

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:
http://media.netmagazine.futurecdn.net/files/images/2011/05/table4.jpg
All dialogs are invoked through the FB.ui call. For our demo site we'll add a Feed Dialog. Add the following function:
  • View source
  • Copy code
  1. function postToWall() {
  2.     FB.ui(
  3.     {
  4.         method: 'feed',
  5.         name: 'Facebook Dialogs Example',
  6.         description: 'This is a demo of the Feed Dialog.',
  7.         message: 'Enter your message'
  8.     },
  9.     function(response) {
  10.         if (response && response.post_id) {
  11.             trace('Post was published.');
  12.         } else {
  13.             trace('Post was not published.');
  14.         }
  15.      }
  16.    );
  17. }
Now add a button to invoke it:
  • View source
  • Copy code
  1. <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.
  • View source
  • Copy code
  1. FB.api('/me/likes', function(response) {
  2.     data = response['data'];
  3.     for (var key in data) {
  4.         trace(data[key]['name']);
  5.     }
  6. });

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!

No comments:

Post a Comment

Featured post

Life Infotech now a leading brand in the field of technology training

  Life Infotech now a leading brand in the field of technology training & its invites students around the nation to be a part of the Tra...