Facebook API:使用JavaScript SDK登录,然后使用PHP检查登录状态


Facebook API: Login using JavaScript SDK then checking login state with PHP

当用户单击"登录"按钮时,我正在使用Facebook的JavaScript SDK来显示"登录弹出菜单"。

正如Facebook在文档中提供的那样,代码是:

$(".loginButton").click(function(){
 FB.login(function(response) {
    FB.api('/me', function(response) {
       console.log(response.id);
       //User ID shows up so I can see that the user has accepted the app.
     });
 });

我还可以使用FB.getLoginStatus()来检查用户是否确实登录并接受了应用程序。

不过,现在我想用PHP执行一个函数。据我所知,PHP有$user,它在成功登录后被分配UserID。

问题是在JS登录$user仍然是0之后。我被卡住了,我不明白为什么它不会为$user 分配正确的用户ID

这是我的JS:

    <script type="text/javascript">  
        window.fbAsyncInit = function() {
            FB.init({
                appId  : '<?php echo $AppId; ?>',
                status : true, // check login status
                cookie : true, // enable cookies to allow the server to access the session
                xfbml  : true,
                channelUrl  : '<?php echo $ServerPath; ?>channel.php' // custom channel
            });
    }; 

    //Get Login Status
    function amILoggedIn(){
        var toreturn = "";
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                window.userId =  response.authResponse.userID;
            toreturn = "GetLoginStatus: logged in" + " " + "<?php echo $user; ?>";
            } else {
            toreturn = "GetLoginStatus: Logged Out";
            }
            console.log(toreturn);
        }); 

    };

    // 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/all.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
            var obj = {
                    method: 'feed',
                    link: 'http://www.google.com'
                };

    $(".loginPopupButton").click(function(){
         FB.login(function(response) {
            FB.api('/me', function(response) { //user-specific stuff
               console.log(response.id);
             });
         });
    });
    </script>

这是PHP:

    <?php
    include_once('fbapi/facebook.php');
    include_once('fbapi/Authenticated_User.php');
    include_once('config.php');

    // Create our Application instance.
    $facebook = new Facebook(array(
                    'appId'  => $AppId,
                    'secret' => $AppSecret
                ));
    //Facebook Authentication part
    $user = $facebook->getUser();

    $perms = "manage_pages";
    if(isset($_GET['backlink']))
        $redirectUrl   = urldecode($_GET['backlink']);
    else
        $redirectUrl   = $fullserverpath;
    $cancelUrl   = $ServerPath."index.php?page=loginWFb";
    //AA - where to go to get FB popup.    
    $loginUrl = $facebook->getLoginUrl(
            array(
                'scope' => $perms,
                'redirect_uri' => $redirectUrl,
                'cancel_uri' => $cancelUrl
            )
    );

    //AA- Defining that a powerUSER is someone who's logged in
    if(isset($user)){
        $_SESSION['loggedIn'] = $user;
    }
    ?>

使用JS SDK登录将登录数据存储在Facebook cookie中,而使用PHP SDK登录将数据存储在PHP会话中。因此,如果您使用JS SDK登录,PHP SDK将不会意识到这一点。

要使用JS SDK数据登录PHP SDK,您需要使用查询参数中的签名请求调用PHP页面:

FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
        // Full redirect or ajax request according to your needs
        window.location.href = 'login.php?signed_request='+response.authResponse.signedRequest;
    }
});

然后$facebook->getUser()将在您的PHP代码中为您提供用户id。

在PHP中初始化Facebook对象时,尝试将sharedSession参数设置为true:

$facebook = new Facebook(array(
    'appId'         => $AppId,
    'secret'        => $AppSecret,
    'sharedSession' => true
));