Facebook SDK 4 - 获取用户数据

Facebook SDK 4 - Get user data

我遵循了一个几乎有效的在线教程。代码看起来像这样。尝试使用 require_once __DIR__ . "/Facebook/autoload.php"; 但它 returns Fatal error: Class 'Facebook\FacebookSession' not found.

编辑** 按照建议添加 autoload.php。

   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!";
   }

这是登录 url,位于每个页面的 header 中。我不会包括整个代码,但只有未登录的访问者才能看到以下代码:

<?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>';
?>

登录url:

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

编辑**

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

使用 Facebook 的 JS-Sdk 获取用户 access_token 是更好的选择。
获得用户的 access_token 后,使用 AJAX.
将其传递到您的 php 文件(即 facebook.php) 所以你的 index 文件看起来像这样:

<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>



现在让我们看一下 facebook.php 文件:

<?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 最新的 PHP-Sdk: Here is the link for "facebook-php-sdk-v4"