Ciprian
Ciprian

Reputation: 3226

Facebook SDK 4 - Get user data

I followed an online tutorial which almost works. The code looks something like this. Tried using the require_once __DIR__ . "/Facebook/autoload.php"; but it returns Fatal error: Class 'Facebook\FacebookSession' not found.

Edit ** Added the autoload.php like suggested.

   session_start();

    require __DIR__ . "/facebook-php-sdk-v4-4.0-dev/autoload.php";

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\GraphLocation;
use Facebook\FacebookOtherException;

  $appId = 'xxx';
  $appSecret = 'xxx';
  $redirect_url = 'http://example.com/com/login';

  //initialize Facebook
  FacebookSession::setDefaultApplication($appId, $appSecret);
  $helper = new FAcebookRedirectLoginHelper($redirect_url);

  try {
      $session = $helper->getSessionFromRedirect();
  } catch(FacebookRequestException $ex) {
      die(" Error : " . $ex->getMessage());
  } catch(\Exception $ex) {
      die(" Error : " . $ex->getMessage());
  }

   var_dump($_SESSION['fb_token']); //Notice: Undefined index: fb_token

  if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
    $session = new FacebookSession($_SESSION['fb_token']);
  }

  if($session) {

      //store token in php session
      $_SESSION['fb_token'] = $session->getToken();

      try {

        $user = (new FacebookRequest(
          $session, 'GET', '/me'
        ))->execute()->getGraphObject(GraphUser::className())->asArray();

      } catch(FacebookRequestException $e) {

      }

      $name = $user['name'];
      $firstName = $user['first_name'];
      $lastName = $user['last_name'];
      $fbId = $user['id'];
      $fbEmail = $user['email'];

   }else{
      echo "No session!";
   }

This is the login url which is located in the header on every page. I won't include the whole code, but the below is only seen by visitors who aren't logged in:

<?php
     echo '<li class=" fb right"><a href="'.$helper->getLoginUrl().'" ><img style="height: 29px;" src="img/login_fb.png" alt="Facebook Log in" /></a> </li>';
?>

Login url:

if( isset($_SESSION['fb_token']) ) {
  //do stuff with user info
}else{
  echo "no token";
}

Edit **

Upvotes: 3

Views: 3151

Answers (1)

Rakesh
Rakesh

Reputation: 744

Facebook PHP-Sdk have some issues with access_token specially when you have pretty(seo friendly) URLs.

Using Facebook's JS-Sdk for getting users access_token is better option.
Once you have user's access_token, pass it to your php file(i.e facebook.php) using AJAX.
So your index file would look like this:

<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
  <!----facebook js sdk---->
  <div id="fb-root"></div>
  <script>
    window.fbAsyncInit = function() {
      FB.init({
        appId: 'PASTE YOUR APP ID',
        cookie: true,
        xfbml: true,
        version: 'v2.1'
      });
    };

    function Login() {
      FB.login(function(response) {
        if (response.authResponse) {
          /*AJAX call to send access_token to php file.*/
          jQuery.ajax({
            url: 'facebook.php',
            /*facebook.php is the file where we'll make API request to get user data.*/
            type: 'POST',
            data: {
              'access_token': response.authResponse.accessToken /*this is the access_token provided by Facebook.We are passing it to our facebook.php file. */
            },
            success: function(result) {
              var res = result;
              if (res) {
                document.getElementById("fb_status").innerHTML = res;
              }
            }
          });
        }
      }, {
        scope: 'email,user_friends,user_location,user_events,publish_actions'
      });
    }

    /*function Logout(){
            FB.logout(function(response) {
            location.reload();
            // Person is now logged out
        });
        }*/
    (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>
  <!----------------------->

  <div id="fb_status"></div> <!--Division to print response just to check every thing is working fine.-->
  <a onclick="Login();">Sign In With Facebook</a> <!--Log-In/Sign-In Link-->
</body>

</html>



Now lets take a look at facebook.php file:

<?php
require_once('autoload.php' );  

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

$app_id = 'PASTE YOUR APP ID HERE';         
$app_secret = 'PASTE YOUR APP SECRET HERE';

FacebookSession::setDefaultApplication($app_id, $app_secret);
$session = new FacebookSession($_POST['access_token']);   /*$_POST['access_token']  is the access_token we sent to this file in AJAX call. */
/*So now we have your session , we can proceed further by making api request to get user data*/
try{
  $me = (new FacebookRequest(
        $session, 'GET', '/me'
        ))->execute()->getGraphObject(GraphUser::className())->asArray();
/* `$me`  will hold the user-data provided by Facebook.To check the data just dump this variable like this:*/
echo '<pre>';
var_dump($me);
echo '</pre>';

/*Now You have user data Do whatever you want to do with it.
Probably store user data in the DATABASE & START LOCAL SESSION*/
}catch(FacebookRequestException $e){
  var_dump($e);
}

?>



NOTE:USE Facebook's latest PHP-Sdk: Here is the link for "facebook-php-sdk-v4"

Upvotes: 3

Related Questions