Facebook Login Integration

Most applications are using the combination of a valid email address and a hashed password to authenticate and login a user into the system. This post will be discussing mainly on how we can let a Facebook user log into our system using their existing FB account.

Facebook App Creation

Before anything else, we need to create a Facebook App (iOS, Android, FB Canvas or Website) that will generate a Facebook App ID and App Secret. Keep an eye on these two important tokens because we will be needing them before we can use the Facebook SDK. Also, we need to configure our app to be able to use the “website” platform by providing the root URL of the existing web app.

How do user log in?

When a Facebook user logs in, they are authenticated via the Graph API using OAuth. There are lots of good references in the internet regarding OAuth. At this point, we are considering two ways to log a Facebook user into our site, by either Facebook JavaScript SDK or PHP SDK.

Basically, we can generate the Facebook Login button based on your requirement and attached it in the template. See sample code below:

<div class="fb-login-button" scope="public_profile,email" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="false" onlogin="checkLoginState();" ></div>

The generated button will trigger the FB.login() method which will prompts the user a popup Login dialog. The checkLoginState() function is called when someone triggers the button.

  • Logging in using FB JavaScript SDK

This is the easiest way (and also the recommended method) to integrate Facebook login in a web application. We need to include the required JavaScript snippet below inside the HTML <body> tag to load the SDK and configure it.

<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id', //insert the generated App ID here
            xfbml      : true,
            cookie     : true,     //set a cookie in the domain with details of user and allows to access the authentication data
            status     : true,
            version    : 'v2.5'
        });
    };

    (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'));
</script>

When the FB Login button was clicked, the FB.getLoginStatus() will be called and check the login status of the user. Values for the user status are:

  1. connected – user is logged in both app and Facebook.
  2. not_authorized – user is logged into Facebook, but not in the app.
  3. unknown – user is not logged into Facebook

Checking the status would be something like below:

FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
        // Logged into your app and Facebook. 
        // we will put here the redirect callback URL to read accessToken using PHP SDK               
    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
    } else  {
        // The person is not logged into Facebook
    }
});

The JavaScript SDK is packed with a method named FB.api(). This sends the user’s requests to the Graph API.

FB.api('/me?&fields=id,name,first_name,last_name,email,gender', function(response) {
    console.log(response);
    console.log('Successful login for: ' + response.name);
    document.getElementById('status').innerHTML = 'You are logged in as ' + response.name + '!';				      			     
});

Notice the fields param from the code above, this just says we grab the Facebook user’s id, name, first_name, last_name, email, and gender.

  • Logging in using FB PHP SDK

Facebook PHP SDK can be installed by either manually or by Composer. We need to create a PHP file (i.e. fb-login-callback.php) . We will then include the autoloader here.

require_once '/path/to/src/Facebook/autoload.php';

To initialize the PHP SDK, we can use the next lines of code:

use Facebook\Facebook;
use Facebook\FacebookRequest;
$fb = new Facebook(['app_id' => '{your-app-id}', 'app_secret' => '{your-app-secret}', 'default_graph_version' => '{version}', ]);

Now, we can make a graph requests with the initialzed SDK.

$phpHelper = $fb->getRedirectLoginHelper();
try {
    // Returns a `Facebook\FacebookResponse` object
    $response = $fb->get('/me?fields=id,name,email,gender', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}
// Returns a `Facebook\GraphNodes\GraphUser` collection
$graphUser = $response->getGraphUser();

We have the user’s Facebook ID, name, email address and gender and manipulate these information on the backend.

  • JavaScript SDK and PHP SDK – Working Together

Using JavaScript SDK combined with the PHP SDK of Facebook can give us more control in terms of functionality and flexibility. How? We let the user login with JavaScript and retrieve the Access Token with PHP. We need to tweak the FB.getLoginStatus() method and use the window.location.replace(“fb-login-callback.php”) to redirect to a callback URL. In the callback URL, we use the FacebookJavaScriptHelper in the Facebook PHP SDK to obtain the access token. Remember that we have set the cookie to true in the FB.init() method of the JavaScript SDK? The callback URL will look something like this:

$jsHelper = $fb->getJavaScriptHelper();
try {
    $accessToken = $jsHelper->getAccessToken($facebookClient);	
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
}

Now, we are holding the accessToken and proceed with retrieving the Graph User the PHP SDK way.

$phpHelper = $fb->getRedirectLoginHelper();
if (isset($accessToken) && !empty($accessToken)) {
    $response = $fb -> get('/me?fields=id,name,email,gender,birthday', $accessToken -> getValue());
    $graphUser = $response -> getGraphUser();
    if (isset($user)) {
        $logoutUrl = $phpHelper -> getLogoutUrl($accessToken, __DIR__ . '/fblogin/login.php');
        // manipulate $graphUser, set to cookie, save details to database, etc.
    }
}

Saving FB Details in Database

After acquiring the information from a successful Facebook login, we may want to save these details into our database. The flow may look something like this:

  1. Login using JavaScript SDK and retrieve the Access Token with PHP SDK.
  2. Get the graph user details (Facebook ID, name, email address, gender, etc).
  3. Check the existence of the user’s Facebook ID from your database.
  4. Create new entry if the ID does not exists, otherwise, the account is a return user.
  5. Set the account as “logged in” into your web application.

Logging out a user

To log a user out from our web application, we may attach the FB.logout() function of the Javascript SDK to a button or link.

FB.logout(function(response) {
    // User is now logged out
});

Note: Calling FB.logout() may also log the user out of Facebook.

Together with the FB.logout() function of the Javascript SDK, we will need the following codes in our logout.php file.

$retUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_GET['returl'];
unset($_COOKIE['FBData']);
setcookie('FBData', null, -1, "/");
session_destroy();

The above code will (1) unset the cookie and (2) destroy the current session.

Now, you may start integrating Facebook login into your own web application.