How to use Facebook API to login

Users don’t like signing up to things except when it is easy. This is where Facebook and other social media companies come in. You can use their API’s to login to your website, which I will demo here how you login to your website using Facebook credentials.

Facebook is one of the biggest social media platforms and therefore one of the best ones to have integrated into your website. They use the programming language JavaScript and then do AJAX calls to the Facebook service to return the responses. Here is how it is done:

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Login the user

First we need to get the Facebook API plugged in and to do this you simply put the code below in the top of the JavaScript file or basically above where you are going to do the Facebook code.

window.fbAsyncInit = function () {
    FB.init({
       
appId: LoginCall.getCookie(‘fb_id’),
        
cookie: true,  // enable cookies to allow the server to access
       
// the session
       
xfbml: true,  // parse social plugins on this page
       
version: ‘v2.2’ // use version 2.1
       
});

// Load the SDK asynchronously
   
(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 = “//connect.facebook.net/en_US/sdk.js”;
   
fjs.parentNode.insertBefore(js, fjs);
   
}(document, ‘script’, ‘facebook-jssdk’));

This is the basic to set up any call to Facebook and as you can also see it has the prefix ‘FB’. All the calls to Facebook will use the ‘FB’ call.

Now to do the call to Facebook to login, you use one JavaScript call from their API. From the top you have the API call ‘FB.login’, this is the pre-built function Facebook uses to show the pop up for the user to enter their details. Once the user has entered their details it responds back with its ‘response’. This you can see is passed to the ‘statusChangeCallback’ which I will show next. You can see what the ‘response’ should respond back with as an Object. The final piece to take note is the ‘scope’, this is what permissions you are requesting from the users account. The standard things you need is ‘public_profile’ and ’email’, which returns enough information for you to log your user in.

//Log user in
FB.login(function (response) {
    //Check Facebook Response
    statusChangeCallback(response);
    //Display Response
    console.log(response.authResponse.accessToken);
    console.log(response.authResponse.expiresIn );
    console.log(response.authResponse.signedRequest );
    console.log(response.authResponse.userID);
    //Add Scope
    }, { scope: ‘public_profile,email’ });

To check that the user has entered the correct information and is logged in your need to check the status. Before I mentioned a function I added to the login called ‘satusChangeCallback’. This function simply takes the response back from Facebook and checks what status they have given. There are three different outcomes that can be sent from Facebook. First is that the user has entered the correct information and all details have been given back, which is ‘connected’. The other is a part connected response ‘not_autorized’, which means they have been or are already logged into Facebook, but they have not given you permissions to access their account. This would mean you will have to request their details again to give permissions. If the response is neither of these then the only out come is that the user is not logged in at all and has of course not given your website permissions. You can call in any of the out come another function or pop up to tell the user what to do next.

// This is called with the results from from FB.getLoginStatus().            
function statusChangeCallback(response) {
    if (response.status === ‘connected’) {
        // Logged into your app and Facebook.
    } else if (response.status === ‘not_authorized’) {
        // The person is logged into Facebook, but not your app.
    } else {
        // The person is not logged into Facebook, so we’re not sure if they are logged into this app or not.
    }
}

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Get User Information

If you didn’t get all the users information that you wanted you can request more about the user using the below API call. You will have to had already request them to login so that you have permission to get the users detail, but you can then call this to get all the details as below. As before, top to bottom, you use the call ‘FB.api’ which is not just for this call and can be used for other functionalities. In this call we use ‘/me’ that is the key for Facebook to know what you are requesting. This will automatically use the logged in users credentials to return their details. The function after the comma is the response from Facebook using the ‘response’. Facebook will then reply with a JSon object response with all the details you will need.

//Get User Details
function GetUser() {
   //Get user details
   FB.api(‘/me’, function (response) {
      //Facebook response
      Console.log(JSON.stringify(response));
   });
}

If the user has not given or you forgot to request a certain permission, then you can re-request that permission with the following call to Facebook. As you can see it is the same as the login call, but I have adapted it so that you can pass the new comma separated scope to the function for it to re-request the permission. As the user is already logged in they will not have to enter details again, but will just have to accept the new permissions request. For Facebook to know that it is a re-request you have to add after the scope an ‘auth_type’ this just lets Facebook know that you need this scope for your website.

//Update Facebook permissions Scope
function AddToScope(NewScope) {
   FB.login(function (response) {
      statusChangeCallback(response);
   }, { scope: NewScope
   ,auth_type: ‘rerequest’
   });
}

Logout the user

Don’t forget to log out the user as they won’t want that to be locked in. To log the user out is simple and as quick as logging in. You first need to check that the users status is logged in as Facebook requires you to, which you just use ‘FB.getLoginStatus’. You can then use that calls response to call the ‘FB.logout’ that logs the user out of their Facebook account. The response from this function will then be placed inside where you can log the user out of your own website as well.

//Logout user
FB.getLoginStatus(function (response) {
   FB.logout(function (response) {
      //Logged out
   });
});

Look around at Pure Random for more post about how to send post update and images to Facebook as well.

If you need any help with errors or other calls, please feel free to contact Pure Random at info@purerandom.co.uk

Advertisements

Leave a message please

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s