好吧,您需要先验证您是否有活动的访问令牌。如果没有,您应该显示 Facebook 登录按钮。
<?php
$userId = $facebook -> getUser();
if ($userId) {
$userInfo = $facebook->api('/' . $userId); ?>
Welcome <?= $userInfo['name'] ?>
<?php } else { ?>
<div class="fb-login-button" data-show-faces="true" data-width="200" data-max-rows="1"></div>
<?php } ?>
根据您的代码,它应该是这样的:
<?php
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxx', // App ID
channelUrl : 'http://YOURDOMAIN.com/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
//alert(me.name);
});
}
</script>
<?php
$userId = $facebook -> getUser();
if ($userId) {
$userInfo = $facebook->api('/' . $userId); ?>
Welcome <?= $userInfo['name'] ?>
<?php } else { ?>
<div class="fb-login-button" data-show-faces="true" data-width="200" data-max-rows="1"></div>
<?php } ?>
<script>
// Load the SDK Asynchronously
( function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
您的服务器中应该有一个 channel.php 文件,该文件将包含以下内容:
<?php
$cache_expire = 60*60*24*365;
header("Pragma: public");
header("Cache-Control: max-age=".$cache_expire);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
?>
<script src="//connect.facebook.net/en_US/all.js"></script>