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
- <!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>
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
- <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
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
- <input type="button" id="login_button" onclick=”login” value="Login"/>
- <script>
- function login() {
- FB.login(function(response) {}, {perms:'read_stream,publish_stream'});
- }
- function logout() {
- FB.logout(function(response) {});
- }
- </script>
- View source
- Copy code
- <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>
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
- <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 custom fields each consist of a dictionary with name, description and type fields. Supported custom types are:
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
- <?php
- define('FACEBOOK_APP_ID', '[APP_ID]');
- define('FACEBOOK_SECRET', '[APP_SECRET]');
- function parse_signed_request($signed_request, $secret) {
- list($encoded_sig, $payload) = explode('.', $signed_request, 2);
- // decode the data
- $sig = base64_url_decode($encoded_sig);
- $data = json_decode(base64_url_decode($payload), true);
- if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
- error_log('Unknown algorithm. Expected HMAC-SHA256');
- return null;
- }
- // check sig
- $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
- if ($sig !== $expected_sig) {
- error_log('Bad Signed JSON signature!');
- return null;
- }
- return $data;
- }
- function base64_url_decode($input) {
- return base64_decode(strtr($input, '-_', '+/'));
- }
- if ($_REQUEST) {
- echo '<p>signed_request contents:</p>';
- $response = parse_signed_request($_REQUEST['signed_request'],
- FACEBOOK_SECRET);
- echo '<pre>';
- print_r($response);
- echo '</pre>';
- } else {
- echo '$_REQUEST is empty';
- }
- ?>
Like button
Now let’s add a Like button for the page:- View source
- Copy code
- <fb-like></fb-like>
We can also target the like for a specific URL rather than the current page:
- View source
- Copy code
- <fb:like href="[YOUR_SITE_URL]/product.html" show_faces="true"></fb:like>
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:
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
- <!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>
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
- 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:- View source
- Copy code
- <fb:send href="[YOUR_SITE_URL]/product.html"></fb:send>
- View source
- Copy code
- FB.Event.subscribe('message.send', function(href, response) {
- trace('message.send: ' + href);
- });
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
- <fb:activity site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:activity>
- View source
- Copy code
- <fb:recommendations site="[YOUR_SITE_URL]" width="300" height="300" header="true"></fb:recommendations>
- View source
- Copy code
- <fb:comments href="[YOUR_SITE_URL]" num_posts="2" width="500"></fb:comments>
- View source
- Copy code
- <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:- View source
- Copy code
- 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.');
- }
- }
- );
- }
- View source
- Copy code
- <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
- FB.api('/me/likes', function(response) {
- data = response['data'];
- for (var key in data) {
- trace(data[key]['name']);
- }
- });
No comments:
Post a Comment