Introduction
Hello all, in this post I will show you how you can add the Connect with Facebook button to your web page. Adding this button to your web page could allow the users to login to your web page using their Facebook login rather than having to remember another login. Or, you could use the information retrieved from their Facebook profile to fill your web page’s registration form.
In this post I will show you how you can use the information of the user’s Facebook profile to fill in the subscription form on your web page. I will use the mighty jQuery framework to interact with the elements on the web page so I suppose you’re already familiar with this framework.
Setting up a Facebook Application
The first thing you need to do is to create a Facebook application. If you are one of those thousands of players of Farmville you probably already know what a Facebook application is
Creating a Facebook application is a way to register your website in order to get a Facebook AppID. The AppID is a unique identifier allowing Facebook to ensure the right level of control of security offered to its users. Once a Facebook Application has been created take not of the Application ID appearing on the Application Details page. A very important step in configuring the Facebook application is setting up the URL and the domain of the website you are going to link with the Facebook app. In my example, supposing that I was going to integrate the Facebook login on this page, I’ve put http://nicobalestra.wordpress.com/ as web page and nicobalestra.wordpress.com as site domain. This tells Facebook where is going to redirect the user after the login and ensures that your application is linked only by the web page you specify. The website must be in the same domain specified in the Facebook application settings. Facebook Application ID and website settings are highlighted in the picture below:
The Facebook Javascript SDK
First of all you need to add a reference to the Facebook Javascript SDK in your web page. Facebook use the OAuth 2.0 for authentication and authorization but thanks to the Javascript SDK the whole process is completely hidden to the developer. Add the following source link in your webpage
<script src="http://connect.facebook.net/en_US/all.js "></script> Is worth nothing that Facebook supports Internationalization. Therefore if you need your login to support a specific language (for example to show the Login button caption and the Login dialog in a specific language) you can replace en_US in the previous link, with any other locale following the ISO Language and Country code standards. For example, if you’d like to use the Italian locale, the following Javascript library must be linked:
<script src="http://connect.facebook.net/it_IT/all.js "></script>
Adding the Login button
I’m going to show you two solutions on how to implement the login button:
- Using the extended Facebook Markup Language (XFBML)
- Using Javascript and the Facebook Javascript SDK
Regardless of the approach you chose, you have to load the Facebook Javascript SDK when the page is loaded. You will do this by calling the FB.init function:
<script>
FB.init({
appId : '186329391405522', //This is our application ID
status : true, // This is if you want to get login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // In this way the fb:login-button will be parsed by the Javascript SDK
});
</script>
However, the above code is blocking. This means that if for any reasons the initialization process takes too long, the loading of your page will be blocked until the Facebook initialization block is completed. Facebook lets you initialize its Javascript SDK in an asynchronous manner. Below is the code you will find on the official Facebook Developers page:
<script>
window.fbAsyncInit = function() {
FB.init({appId: '186329391405522',
status: true,
cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Option 1 – Using the extended Facebook Markup Language (XFBML)
This is the easiest option because it renders the button for you. Plus it will render the standard Facebook Login button, giving the user a well known user experience. Wherever you want to have your Facebook login button to appear, just put the following code:
<div id="fb-root"></div> <fb:login-button>Login with Facebook</fb:login-button>
There is a very nice tool provided by Facebook which will help you set up this button. You can find the tool at http://developers.facebook.com/docs/reference/plugins/login/ . Here you will be able to set up your button and get the HTML code to render the button itself:
In order to read user’s details to fill in our subscription form, we explicitely ask the users to give our page the permission to read those details. We’ll do this by adding the following attribute to the login button tag perms='user_about_me,user_birthday,user_hometown,email'.
This tells the users that our application needs to access their general details (name, surname, gender, etc..), birth date, email and locale.
When the users click on the Facebook Login button, a new popup window appears asking them to login into Facebook and to give your application access to some of their profile’s details.
Once the login process is completed and the popup is closed (regardless of the user accepting your access permissions request or not), a new Javascript Event is raised by the Facebook Javascript SDK.
Facebook makes an extensive use of Javascript events in order to notify your application about something appened on the user’s Facebook profile.
This is the list of Global Events taken from the Facebook Developers page:
auth.login– fired when the user logs inauth.logout– fired when the user logs outauth.sessionChange- fired when the session changesauth.statusChange– fired when the status changesxfbml.render– fired when a call to FB.XFBML.parse() completesedge.create– fired when the user likes something (fb:like)edge.remove– fired when the user unlikes something (fb:like)comments.create– fired when the user adds a comment (fb:comments)comments.remove– fired when the user removes a comment (fb:comments)fb.log– fired on log message
All you have to do is to define a callback function for the auth.login event and depending on the login result, take the desired actions (in our case filling the subscription form inputs with the user details).
Register your callback for the auth.login event by using the following code:
FB.subscribe("auth.login", function(response) { })
In our case, if the user logged in and gave our application the required permissions, we will fill our subscription form in:
FB.subscribe("auth.login", function(response){
if (response.session)
{
//Check for every single permission to fill the related field
if (response.email)
{
$("#email").value(response.email);
}
if (response.first_name)
{
$("#firstName").value(response.first_name);
}
if (response.last_name)
{
$("#lastName").value(response.last_name);
}
if (response.gender)
{
//You might want to convert the returned value with the values in a genders selection list
$("#gender").value(response.gender);
}
}
}
);
Option 2 – Using the Facebook Javascript SDK
You might want (need) to create your own button for logging in the user maybe to perform some custom business logic before executing the Facebook login process. First of all you need to create a button and attach a Javascript function executed when the user clicks on it. Using jQuery we’ll do it in the jQuery.ready() function so that the function gets bound as soon as the page is fully loaded.
<script>
$(this).ready(function()
{
$("#loginButton").click(function()
{
FB.login(function(response)
{
//If the user logged in and authorizes your application...
if (response.session)
{
//This is the unique Facebook User ID.
$("#facebookID").attr("value", response.id);
//Check for every single permission to fill the related field
if (response.email)
{
$("#email").value(response.email);
}
if (response.first_name)
{
$("#firstName").value(response.first_name);
}
if (response.last_name)
{
$("#lastName").value(response.last_name);
}
if (response.gender)
{
//You might want to convert the returned value with the values in a genders selection list
$("#gender").value(response.gender);
}
}
}
, {perms: 'user_birthday, user_hometown, email, user_about_me'});
}
}
</script>
The FB.login function opens the usual Facebook login popup window asking the user to log in and, if her profile is not linked to your application, it will ask the user to give your application the required permissions (in our example, user_birthday, user_hometown, email and user_about_me). This is a comprehensive list of Facebook permissions you can ask the user. Try to ask the users only the permissions you really need for your application. The more permissions you’ll ask, the less the users will be inclined to give your application access to their profile’s details.
Conclusions
I really hope you’ll find this article somehow interesting and useful. We only scratched the surface of the Facebook Javscript SDK.
Plugging Facebook login into your web applications would be very beneficial if you use the user’s Facebook ID as your internal user ID. In this way you allow users to login into your application by using only one login. Let’s Facebook do the dirty job!!
