douyijin7741 2015-03-27 04:19
浏览 89
已采纳

Facebook SDK 4 - 获取用户数据

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";
}
  • Sometimes the fb_token doesn't set. When someone clicks on the login url, they are redirected to the login page with the no token message. If the login url is clicked again while on the login page, everything works.

Edit **

  • For some reason now it's not detecting the fb_token at all. Even when I'm logged into Facebook. Which is very weird because I never had this problem until now.

展开全部

  • 写回答

1条回答 默认 最新

  • dqkf36241 2015-03-31 03:52
    关注

    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"

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部