php 如果用户已登录 Facebook,则 FB 登录回调函数不响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8541162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:56:41  来源:igfitidea点击:

FB login callback function not responding if user is already logged in facebook

phpfacebookfacebook-login

提问by Hafiz

I am using fb connect using js. This is my code:

我正在使用 js 使用 fb 连接。这是我的代码:

<script>
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'xxxxxxxxxxxxxxxx',
        status     : true, 
        cookie     : true,
        xfbml      : true,
        oauth      : true
      });

      FB.Event.subscribe('auth.login', function(response) {
        obj=response.authResponse;
        token=obj.accessToken;
        setCookie("access_token_fb", token, '2');

        window.location.reload();
      },true);
    };
    (function(d){
       var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
       js = d.createElement('script'); js.id = id; js.async = true;
       js.src = "//connect.facebook.net/en_US/all.js";
       d.getElementsByTagName('head')[0].appendChild(js);
     }(document));
  </script>

for login I am using:

登录我使用:

 <div class="fb-login-button" scope="email,user_checkins"  >Login with Facebook</div>

'auth.login' in subscribe function has a response handler it is only being called when user click on fb button and not already logged into FB, enter his/her email address and password in fb window . While if a user is already logged in facebook then fb dialog open and close. It doesnot then pass control to response hander. I read somewhere that force="true" enable it to detect status change and call call back function. But I don't know where to add force ture. I think it should be in login div. Is it true or is there some other approach?

订阅功能中的“auth.login”有一个响应处理程序,只有当用户点击 fb 按钮并且尚未登录 FB 时才会调用它,在 fb 窗口中输入他/她的电子邮件地址和密码。如果用户已经登录 facebook,则 fb 对话框打开和关闭。然后它不会将控制权传递给响应处理程序。我在某处读到 force="true" 使其能够检测状态变化并回调回调函数。但我不知道在哪里添加力量。我认为它应该在登录div中。这是真的还是有其他方法?

thanks for you time.

谢谢你的时间。

采纳答案by Jai Pandya

Method 1:

方法一:

Though I believe that DMCS has given a correct solution to the problem, here is another way to approach. Use FB.login method with a custom login link.

虽然我相信 DMCS 已经为问题提供了正确的解决方案,但这是另一种方法。使用带有自定义登录链接的 FB.login 方法。

<script>
window.fbAsyncInit = function() {
    FB.init({
        appId: 'YOUR-APP-ID',
        status: true,
        cookie: true,
        xfbml: true,
        oauth: true
    });
};

function facebookLogin() {
    FB.login(function(response) {
        if (response.authResponse) {
            console.log('Authenticated!');
            // location.reload(); //or do whatever you want
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    },
    {
        scope: 'email,user_checkins'
    });
}

(function(d) {
    var js,
    id = 'facebook-jssdk';
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
} (document));
</script>

Body markup:

身体标记:

<div id='fb-root></div><!-- required for SDK initialization -->
<a id='fb-login' href='#' onclick='facebookLogin()'>Login with Facebook</a>

When you click on the button, it will run the callback function inside FB.login.

当您单击按钮时,它将运行 FB.login 中的回调函数。

Method 2:

方法二:

Alternatively, using FB login button plugin, you can subscribe to auth.statusChangeand check for the status of the user in response.

或者,使用 FB 登录按钮插件,您可以订阅auth.statusChange并检查用户的状态作为响应。

FB.Event.subscribe('auth.statusChange', function(response) {
  // check for status in the response
});

Note if you are using fb login button plugin, and the user is already logged in and connected to the app, no login button is shown (read it in the documentation here)

请注意,如果您使用的是 fb 登录按钮插件,并且用户已经登录并连接到应用程序,则不会显示登录按钮(在此处的文档中阅读)

回答by DMCS

I'd suggest letting Facebook do the heavy lifting for you. Please note some changes: 1. channelUrl specified, 2. use of FB.getLoginStatus 3. removal of setting a cookie. 4. change of event to listen to (so in case they log out in a different window, or deauth your app elsewhere, etc )

我建议让 Facebook 为你做繁重的工作。请注意一些更改:1. 指定了 channelUrl,2. 使用 FB.getLoginStatus 3. 删除设置 cookie。4. 更改要监听的事件(以防万一他们在不同的窗口中注销,或在其他地方取消您的应用程序等)

    <script>
        window.fbAsyncInit = function() {
        FB.init({
            appId      : 'xxxxxxxxxxxxxxxx',
            status     : true, 
            cookie     : true,
            xfbml      : true,
            oauth      : true,
            channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html' // Channel File
        });

        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {

                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;

                // Do something with the access token


            } else {
                // Subscribe to the event 'auth.authResponseChange' and wait for the user to autenticate
                FB.Event.subscribe('auth.authResponseChange', function(response) {
                    // nothing more needed than to reload the page
                    window.location.reload();
                },true);      

                // now dynamically show the login plugin
                $('#mydiv').show();      
            }
        });


        };
        (function(d){
            var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
            js = d.createElement('script'); js.id = id; js.async = true;
            js.src = "//connect.facebook.net/en_US/all.js";
            d.getElementsByTagName('head')[0].appendChild(js);
        }(document));
  </script>

回答by nav

When you intialize the FB SDK with status:trueit will fetch the login status from the user and store it. From that point on when you make calls to FB.getLoginStatus()it isnt accessing fetching the latest data from FB but is instead referring to the locally stored variables that were set at the point of FB.init()- I think its only refreshed once every 20 mins (see https://github.com/facebook/facebook-js-sdk/commit/5b15174c7c9b9ea669499804d4a4c7d80771b036) - however you can force the refresh by doing this:

当您使用status:true它初始化 FB SDK 时,它将从用户那里获取登录状态并存储它。从那时起,当您调用FB.getLoginStatus()它时,它不是访问从 FB 获取最新数据,而是指当时设置的本地存储变量FB.init()- 我认为它每 20 分钟只刷新一次(参见https:// github.com/facebook/facebook-js-sdk/commit/5b15174c7c9b9ea669499804d4a4c7d80771b036) - 但是你可以通过这样做来强制刷新:

FB.getLoginStatus(function() {...}, /*FORCE*/ true);

This should then fire your auth.loginevent or you could just pass the handler you defined for that event to FB.getLoginStatusas well.

这应该会触发您的auth.login事件,或者您也可以将您为该事件定义的处理程序传递给FB.getLoginStatus

Can even go a set further and poll this function like:

甚至可以更进一步并轮询此功能,例如:

setTimeout(function() {
    FB.getLoginStatus(function() {...}, /*FORCE*/ true);
}, 10000); // poll every 10 seconds

回答by Guy Goldstein

Change from "status : true," to "status : false," and I believe it'll do what you want. The problem is status : true makes the status check happen on init, so there is nothing to change when the user clicks the button.

从“状态:真”更改为“状态:假”,我相信它会做你想做的。问题是 status : true 使状态检查发生在 init 上,因此当用户单击按钮时没有任何更改。

Found the answer on next-to-last comment here: http://www.bubblefoundry.com/blog/2011/03/the-facebook-login-button-and-logging-into-your-webapp/

在这里找到倒数第二条评论的答案:http: //www.bubblefoundry.com/blog/2011/03/the-facebook-login-button-and-logging-into-your-webapp/

回答by Clinton J Calhoun

This works:

这有效:

FB.getLoginStatus(function(response) {
//only works when page loads, use FB.Event.subscribe for status change      
    statusChangeCallback(response);
    FB.Event.subscribe('auth.statusChange', function(response){
        //yay! do whatever here, there was a status change
    },true);  

});

回答by Hafiz

You need to replace

你需要更换

FB.Event.subscribe('auth.authResponseChange', function(response){     

with

FB.Event.subscribe('auth.statusChange', function(response){ 

As auth.authStatusChange event trigger on status change whether already logged in or login by giving credentials.

作为 auth.authStatusChange 事件触发状态更改,无论是已经登录还是通过提供凭据登录。

thanks

谢谢