0

我已经编写了这段代码,但它只有在我已经登录Facebook的时候才能正常工作,否则会出现一个弹出窗口,需要我通过电子邮件和密码登录Facebook。如何与访问令牌共享?

这是代码:

window.fbAsyncInit = function() { 
    FB.init({ 
     appId: 'xxx', 
     frictionlessRequests: true, 
     status: true, 
     cookie: true, 
     xfbml: true, 
     oauth: true 
    }); 

    function update(response) { 
     if (response.authResponse) { 
      FB.api('/me', function (info) { 
       login(response, info); 
      }); 

     } else { 

     } 
    } 

    FB.getLoginStatus(update); 
}; 
(function() { 
    var e = document.createElement('script'); 
    e.async = true; 
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
    document.getElementById('fb-root').appendChild(e); 
}()); 


function login(response, info) { 
    if (response.authResponse) { 
     publish(); 
    } 
} 

function publish() { 
    var publish = { 
     method: 'feed', 
     access_token: '<?php echo $token; ?>', 
     message: 'How are you ?', 
     name: 'hi friends', 
     caption: 'yuhuuuuuuuu', 
     description: (' '), 
     link: 'http://www.example.com', 
     picture: 'http://cdn1.hark.com/images/000/004/514/4514/original.jpg', 
     actions: [{ 
      name: 'Hello', 
      link: 'http://www.example.com/' 
     }], 
     user_message_prompt: 'Share on facebook' 
    }; 

    FB.ui(
    publish, function (response) { 
     if (response && response.post_id) { 
      alert('Post was published.'); 

     } else { 
      alert('Post was not published.'); 
     } 
    }); 
} 

回答

0

在你update方法,在空白else你应该调用FB.login方法:

调用的FB.login提示用户进行身份验证您的应用程序 使用OAuth对话框。

但是,你不能只是这样做:

function update(response) { 
    if (response.authResponse) { 
     FB.api('/me', function (info) { 
     login(response, info); 
     }); 

    } else { 
     FB.login(function(response) { 
      if (response.authResponse) { 
       console.log("user is logged in!", response.authResponse); 
      } 
     }); 
    } 
} 

因为它在文档中指出:

调用的JS SDK的FB.login结果试图打开一个弹出 窗口。因此,只有在用户点击 事件后才能调用此方法,否则弹出窗口将被大多数浏览器阻止。

您必须向用户显示一个按钮或其他东西,告诉他点击才能登录,然后您可以调用FB.login方法。

+0

那么即使我有访问令牌,用户也必须重新登录? – xRobot

+0

如果用户已经登录并且已经通过身份验证,那么调用'FB.getLoginStatus'应该足够了,它会返回'authResponse'并提供所有需要的信息。否则,你需要调用'FB.login'。另外,如果您调用'FB.login'并且用户已经被授权,那么弹出窗口将立即自动关闭,并且您的回调将被调用。 –

+0

好的,但用户必须先重新点击“登录”。有没有办法避免这种情况?谢谢:D – xRobot