Facebook Login Integration on Website

In this tutorial we will see how to integrate facebook login on your website. This is useful because user’s can easliy create account through facebook instead of filling up the registration form, so it makes registration and login faster.

This tutorial is not related to magento, but rather just focuses on facebook api’s. There are many tutorial’s available online on this topic, but i personally had a tough time figuring out the correct method to use. So i am writing down here the best method which i found out.

Facebook Login and Authentication

Facebook provides an authentication api which you can use as an alternate for the traditional login system or also to import facebook user profile information to your website. Basically how this works is you create a facebook app, ask user to grant permission to your app to access his profile information, after he has granted access you can create account on your website using his profile information.
This is the workflow which gets followed when integrating facebook login on your site (helpful for a beginner)

  • Create a facebook app for your domain
  • Place a login button on your website
  • When user clicks on the login button there conditions are possible.

    1. User is Not Logged In: Facebook dialog pop’s up and asks user to login.

    Facebook Login Box

    Facebook Login Box

    2. User is Logged In, but has not authorized the app: Facebook pop’s up a dialog asking user to give permission to your app.

    Facebook Authorization Dialog

    Facebook Authorization Dialog

    3. User is Logged In and has already authorized the app
    In this case, facebook will directly redirect to a page specified by us.

  • On the page where facebook redirects, we retrieve user information like name, email, facebook id etc and create his account on our website.

The entire code is divided in two part
1. javascript
2. php

Below is the java script code to be applied

<div id="fb-root"></div>
<script type="text/javascript">
//<![CDATA[
window.fbAsyncInit = function() {
   FB.init({
     appId      : 'XXXXXXXXXXXXXX', // App ID
     channelURL : '', // Channel File, not required so leave empty
     status     : true, // check login status
     cookie     : true, // enable cookies to allow the server to access the session
     oauth      : true, // enable OAuth 2.0
     xfbml      : false  // parse XFBML
   });
};
// logs the user in the application and facebook
function login(){
FB.getLoginStatus(function(r){
	 if(r.status === 'connected'){
        	window.location.href = 'fbconnect.php';
	 }else{
		FB.login(function(response) {
	        	if(response.authResponse) {
			  //if (response.perms) 
		        	window.location.href = 'fbconnect.php';
			} else {
			  // user is not logged in
			}
	 },{scope:'email'}); // which data to access from user profile
 }
});
}
// Load the SDK Asynchronously
(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>

The above code is divided in three parts
Part1

<div id="fb-root"></div>

// Load the SDK Asynchronously
(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);
}());

This code simply add the facebook library javascript to the page, it appends it to the ‘fb-root’ element.
Part2

<script type="text/javascript">

window.fbAsyncInit = function() {
   FB.init({
     appId      : 'XXXXXXXXXXXXXX', // App ID
     channelURL : '', // Channel File, not required so leave empty
     status     : true, // check login status
     cookie     : true, // enable cookies to allow the server to access the session
     oauth      : true, // enable OAuth 2.0
     xfbml      : false  // parse XFBML
   });
};

This code initializes FB object. In the appID you need to provide your application id of the app you created on facebook.
Keep the parameters ‘status’ = true. On making this false, i have noticed in the internet explorer that problem arises with popup blocker.
Part3

function login(){
FB.getLoginStatus(function(r){ //check if user already authorized the app
	 if(r.status === 'connected'){
        	window.location.href = 'fbconnect.php';
	 }else{
		FB.login(function(response) { // opens the login dialog
	        	if(response.authResponse) { // check if user authorized the app
			  //if (response.perms) {
		        	window.location.href = 'fbconnect.php';
			} else {
			  // user is not logged in
			}
	 },{scope:'email'}); //permission required by the app
 }
});
}

This function needs to be added to an onclick event on any html element. e.g you can have an image and on clicking on that image you want the facebook login box to open. In that case you need to call the login() function on its on click event.

<a href='#' onclick='login();'>Facebook Login</a>

Next in the php file i.e fbconnect.php we need to add code to retrieve facebook user profile details. We need facebook php-sdk for this purpose which can be downloaded from https://github.com/facebook/php-sdk

require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
		'appId'  => 'XXXXXXXXXXXXXX',    //app id
		'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // app secret
));
$user = $facebook->getUser(); 
if ($user) { // check if current user is authenticated
	try {
		// Proceed knowing you have a logged in user who's authenticated.
		$user_profile = $facebook->api('/me');  //get current user's profile information using open graph
            }
         catch(Exception $e){}
}

The varaible $user_profile will contain the profile information of the user like firstname, lastname, email, facebook id etc. You can use this information to create his account on your website.

The content of the $user_profile depends on the permission which we have asked in the app. There permission are set in ‘scope’ parameter in our javascript code. A full list of all facebook permissions are given here