Sunday 9 December 2018

Integrating Facebook Login in Your Websites

Nowadays in almost all websites, You can find login via Social media accounts. So its inevitable for all the developers to learn more about these processes & integrate into their own websites. Their are many benefits of integrating this.

1) You can reduce the time consumption for the long form filling process during the registration
2) You doesn't want to wait for the customers to verify their email address or anything.
3) You can retrieve much more information about the personal info from their social media accounts.

Steps For Integration 

1) Creating Developer Account & Creating App

  • For Integrating this, first the developer has to create a developer account in facebook by going to https://developers.facebook.com/.
  • Now Create an App in that
  • Select Website as platform.
  • Now Give the Category, Email, App Type, Request URLS Approved.etc..




  • Keep the App ID & APP Secret safely in your hands. Dont Forget to make the app Live.
  • Also You can add Products in the app through this panel.


2) Downloading Facebook SDK

Download Facebook SDK from the web.
You can either install via composer or Can download from Github..  Download from here:- https://github.com/facebook/php-graph-sdk


3)Creating Our Login Script

Create two files in the application folder; index.php and myprofile.php.

Add the following code to index.php file. Comments are added to explain the code.

<?php
//initialize facebook sdk
require 'vendor/autoload.php'; //Link to the Folder Downloaded for afcebook graph sdk
session_start();
$fb = new Facebook\Facebook([
 'app_id' => 'Put Your App ID Here',
 'app_secret' => 'Put App Secret',
 'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
  $accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
  // OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id');           // To Get Facebook ID
$fbfullname = $profile->getProperty('name');   // To Get Facebook full name
$fbemail = $profile->getProperty('email');    //  To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used            
$loginUrl = $helper->getLoginUrl('http://sitename.com/url.php', $permissions);echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
?>

Once done, go to the application URL in browser. You will see the Facebook button for login. Click it and the page will redirect to Facebook login page. Sign into the Facebook account. After successful login, the page will be redirected to the myprofile page.

Add the following code to myprofile.php to show the retrieved information. For the purpose of this tutorial, I will retrieve user id, Facebook profile picture, name and email.

<?php
session_start();
?>
<head>
     <title>Login with Facebook</title>
     <link
        href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        rel = "stylesheet">
  </head>
  <body>   

  <?php if($_SESSION['fb_id']) {?>
        <div class = "container">
           <div class = "jumbotron">
              <h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>
              <p>Welcome to PHP Dudes</p>
           </div>
              <ul class = "nav nav-list">
                 <h4>Image</h4>
                 <li><?php echo $_SESSION['fb_pic']?></li>
                 <h4>Facebook ID</h4>
                 <li><?php echo  $_SESSION['fb_id']; ?></li>
                 <h4>Facebook fullname</h4>
                 <li><?php echo $_SESSION['fb_name']; ?></li>
                 <h4>Facebook Email</h4>
                 <li><?php echo $_SESSION['fb_email']; ?></li>
              </ul>
          </div>
<?php } ?>
  </body>
</html> 


  • Now when the visitor, login via clicking the link, we will get info like this:-
  • Store the ID & token received in your Database & validate every time when use logins.. 

Download sample code from here:-  https://github.com/litto/Facebook

2 comments:

  1. i didnot get the facebook button in my suitecrm interface.

    ReplyDelete
    Replies
    1. This is for normal websites.. For application like suitecrm, you have to develop addon for that..

      Delete