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

  • Pingback: Facebook App and Timeline Integration (Actions, Objects and Aggregations)()

  • Pingback: 10+ Useful PHP Facebook Login Connect Tutorial : Daily Syntax()

  • Thanks a lot for the post !

  • Magento Themes

    could you also post about twitter and Google+..

  • Sweet post Manish.

    I just have one problem. That is the $user_profile dose not contain anything. Why’s that ? O_o

  • Gud post really helpful

  • juhi jadav

    One Problem i am facing is when i click on login button facebook login dialog opens and after filling id and password nothing happens…

    Also provide Twitterand google+ interaction also assp

    • Manish Prakash

      Hi juhi,
      I think you might be getting some javascript error. Please see console you might
      not using correct appid and secret key.

  • monifahmock

    oh raelly

  • hello once again,

    i am using correct id password as well as correct api key and secret key.

    what i wants to do is i just want to redirect my default page after signing in using facebook.

    how can i do that?

    • Guest

      Nice 🙂

  • love yyou.. this is the best tutorial i found in dozen sites

  • Jenz

    i am getting an error as ‘login is not defined’

  • arunsignit

    Reallly great post…awesome….your post was working fine and clean…wonderfull job..

    Simply Superb…..

    Mr.Manish Prakash….

  • Rishab

    Gud Post works fine

  • Menora Sicher

    Nice one 🙂

  • Piyush Rai

    Awesome tutorial man..!!
    was really helpful.

  • Mouzlo India

    I use http://www.mouzlo.com.but Not Work .

  • Mouzlo India

    good tutorial about the facebook integration…thank you

  • dilip shelake

    Hii,, i have follow all the instructions, but after clicking facebook log In button nothing is happening. dont know why. plz suggestion.

  • gaya3

    Hi,Instead of showing default fb star image in fb authentication,I need to show my website logo besides user profile photo in first time access..I tried to set in app details page.but no use…Could you pls tell where i have to give my website logo??Thanks in advance.

  • gaya3

    Thanks for this…. Instead of showing default fb star image in fb authentication,I need to show my website logo besides user profile photo in first time access..I tried to set in app details page.but no use…Could you pls tell where i have to give my website logo??Thanks in advance.

  • tidalgo22

    any updat?

  • Nidhi Tiwari

    after login i got blank page and there is no any error….. can anybody help me?????

    • Yash

      For that you have to give the link in window.location.href = ”; in script tag

  • Tisha Kumar

    Thank You…Good tutorial..

  • Carla Laurine

    Will this work on Magento 1.9.1? I need to before testing it for my site

  • Rakesh Goyal

    Good Post and really helpful,

    I am having couple of issues and are as follows,

    First: there are few people who are not able to login into my website with their FB account, on the other hand, there are people who didnt find any issues to login into my website using their FB account.

    Question: what could be wrong, as I believe there is no issue in the integration as people are able to login in

    Second: When I have added login with FB in my website, first time my website was having xxxxxx/ beta, after couple of weeks we removed beta from our URL and same from everywhere. Now the issue is people who have logged in earlier with the FB account, currently not able to login again, but new user who is used their credential was able to login.

    Any Help on the above two scenarios would be of great support.

    Thanks in advance..