Create Facebook login for your website

So. Made a new website and want an easy login from Facebook. Facebook has a Javascript SDK and we are going to utilize that for creating FB login for our website.

All References from  : https://developers.facebook.com

1. Create a facebook App

You need to create a facebook app for your website and get app ID and access to facebook javascript api.

Go to : https://developers.facebook.com/apps/

Click on Add new app and choose the website.

After Creating an APP,

1. In Settings –> Basic you will get an APP ID and APP Secret.

2. In Settings –> Advanced you will get an API Version.

We need that keep those with you.

2. Use Javascript SDK to create login.

  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{your-app-id}',
      cookie     : true,
      xfbml      : true,
      version    : '{api-version}'
    });
      
    FB.AppEvents.logPageView();   
      
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

Here Put your APP ID and the version you are using. The code given has been created using reference from the Facebook developer’s website. So now coming to the point. I will show the part of the code that you need to edit.

 function testAPI() {                      
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me?fields=name,email,first_name,last_name,gender,locale', function(response) {
      console.log('Successful login for: ' + response.name);
      var string = 'Thanks for logging in, <h2><strong>' + response.name + '!</strong></h2>' ;
      string += '<p> Your Email : '+ response.email + '</p> ';
      document.getElementById('status').innerHTML = string;  
    });
  }

Here, we make a login call and get a response .

Specify the things you want to receive in response. Here  '/me?fields=name,email,first_name,last_name,gender,locale'

Now, you can access to all those using response._property_.

Complete Code-

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>

function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
    console.log('statusChangeCallback');
    console.log(response); // The current login status of the person.
    if (response.status === 'connected') { // Logged into your webpage and Facebook.
        testAPI();
    } else { // Not logged into your webpage or we are unable to tell.
        document.getElementById('status').innerHTML = 'Please log ' +
            'into this webpage.';
    }
}

function checkLoginState() { // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) { // See the onlogin handler
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId: '197468851707624',
        cookie: true, // Enable cookies to allow the server to access the session.
        xfbml: true, // Parse social plugins on this webpage.
        version: 'v7.0' // Use this Graph API version for this call.
    });

    // Now that we've initialized the JavaScript SDK, we call 
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
        statusChangeCallback(response); // Returns the login status.
    });
};

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me?fields=name,email,first_name,last_name,gender,locale', function(response) {
        console.log('Successful login for: ' + response.name);
        var string = 'Thanks for logging in, <h2><strong>' + response.name + '!</strong></h2>';
        string += '<p> Your Email : ' + response.email + '</p> ';
        document.getElementById('status').innerHTML = string;
    });
}
</script>


<!-- The JS SDK Login Button -->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
</body>
</html>

If you are having understanding some piece of code. Please comment here, We are here to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *