我希望新用户能够使用我网站上的fb连接按钮“连接”,一旦连接,它将显示他们的第一个+姓氏和个人资料照片。
如果用户已连接,则连接按钮将变为注销。
通过文档,我已经实现了以下代码;
<html>
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'xxxxxxxxxx', cookie:true,
status:true, xfbml:true
});
FB.api('/me', function(user) {
if(user != null) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
</script>
<div align="center">
<img id="image"/>
<div id="name"></div>
</div>
</body>
</html>
唯一的问题是它没有显示facebook连接按钮,当我尝试插入它时,代码会中断。
非常感谢任何帮助!
回顾:网站检查用户是否已连接并且有有效会话,如果没有,则显示fb connect / login按钮,如果是,则显示注销按钮,无论哪种方式,都应向用户显示他们的姓名和个人资料照片。< / p>
谢谢!
答案 0 :(得分:7)
Facebook PHP-SDK将完全符合您的要求:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
// Session based API call.
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
// login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>', // App ID
channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if ($user): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<?php endif ?>
<?php if ($user): ?>
<div align="center">
<img id="image" src="https://graph.facebook.com/<?php echo $uid; ?>/picture" />
<div id="name"><?php echo $me['name']; ?></div>
</div>
<?php endif ?>
</body>
</html>