在服务器端使用JavaScript SDK登录后获取会话并获取用户名

时间:2014-10-01 07:58:02

标签: facebook facebook-graph-api facebook-javascript-sdk facebook-php-sdk

我正在尝试进行我的第一次Facebook登录。所以我使用Facebook SDK for JavaScript实现弹出登录,然后我想使用SDK for PHP将用户名存储在数据库中(用于显示)在我的网络应用程序中。)

问题是我使用的这个PHP代码在通过JavaScript弹出并首次刷新登录后无法获得会话。它会在第二次刷新后获得信息。

第二个问题是我无法找到从id获取用户名的方法。 用户名为facebook.com/ john.doe1 ,与id facebook.com/ 1241245235 等效。

所以现在我正在使用Facebook Login for the Web with the JavaScript SDK这是JavaScript的标准登录。

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
  FB.init({
    appId      : '{your-app-id}',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.1' // use version 2.1
  });

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });

  };

  // Load the SDK asynchronously
  (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'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }
</script>

<!--
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

</body>
</html>

登录后我想将信息传递给服务器端(PHP),所以我使用的是这段代码:

    require_once 'lib/fb/autoload.php';

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

    FacebookSession::setDefaultApplication('xxxxx','xxxxx');

    $helper = new FacebookJavaScriptLoginHelper();
    try {
        $session = $helper->getSession();
    } catch(FacebookRequestException $ex) {
        // When Facebook returns an error
    } catch(\Exception $ex) {
        // When validation fails or other local issues
    }

    if($session) {

      try {

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

        echo "Name: " . $user_profile->getName();
        echo '<br>';
        echo "Id: " . $user_profile->getId();
        echo '<br>';
        echo "Link: " . $user_profile->getLink();

      } catch(FacebookRequestException $e) {

        echo "Exception occured, code: " . $e->getCode();
        echo " with message: " . $e->getMessage();

      }   

    }

1 个答案:

答案 0 :(得分:1)

使用Graph API v2.0已弃用username字段。看看

https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api

  

/me/username已不再可用。

为什么你从前端切换到后端对我来说也不是很清楚。我建议您决定是否要使用PHP或JavaScript。但是,你将无法再获得username