我已经使用Facebook PHP和JS API创建了一个页面。
首先,用户必须进行身份验证(login.php)。然后将用户重定向到index.php。这很好,但如果用户在加载之前导航到另一个页面或重新加载页面,它将再次将用户返回到login.php进行身份验证。(这是因为$session中的if/else)。当我关闭重定向到登录时,如果没有$session并记录异常,我会得到这个错误:
exception 'Facebook'FacebookAuthorizationException' with message 'This authorization code has been used.' in /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookRequestException.php:104 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookRequest.php(280): Facebook'FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 400) #1 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(328): Facebook'FacebookRequest->execute() #2 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(242): Facebook'Entities'AccessToken::request('/oauth/access_t...', Array, NULL, NULL) #3 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(187): Facebook'Entities'AccessToken::requestAccessToken(Array, NULL, NULL) #4 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSession.php(271): Facebook'Entities'AccessToken::getAccessTokenFromCode('AQCcnkOOMQ9l2Qk...') #5 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSession.php(252): Facebook'FacebookSession::newSessionAfterValidation(Object(Facebook'Entities'SignedRequest)) #6 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSignedRequestFromInputHelper.php(93): Facebook'FacebookSession::newSessionFromSignedRequest(Object(Facebook'Entities'SignedRequest)) #7 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/db/FbAuth.php(19): Facebook'FacebookSignedRequestFromInputHelper->getSession() #8 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/pages/index.php(3): require('/Applications/X...') #9 {main}
Notice: Undefined variable: session in /Applications/XAMPP/xamppfiles/htdocs/ntsosial/db/FbAuth.php on line 28
我的文件(删除css和内容):
index.php:
<?php
require '../db/FbAuth.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
console.log("Not authorized. Redirecting ..");
window.location = "login.php";
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
console.log("Not logged in to FB. Redirecting..");
window.location = "login.php";
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'removed',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.1' // use version 2.1
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status !== 'connected') {
window.top.location = 'login.php';
}
});
};
// 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/nb_NO/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Logging user out
function logout() {
console.log("Signing out");
FB.logout(function(response) {
// user is now logged out
console.log("Signed out");
});
}
</script>
</head>
<body>
</body>
</html>
db/FbAuth.php
<?php
require '../fb/autoload.php';
use Facebook'FacebookSession;
use Facebook'FacebookRequest;
use Facebook'FacebookJavaScriptLoginHelper;
use Facebook'GraphUser;
use Facebook'FacebookRequestException;
// Initialize the Facebook SDK.
FacebookSession::setDefaultApplication('removed','removed');
$helper = new FacebookJavaScriptLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch('Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
try {
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
$userID = $me->getId();
} catch (FacebookRequestException $e) {
// The Graph API returned an error
} catch ('Exception $e) {
// Some other error occurred
}
}
else {
header("Location: ../pages/login.php");
die();
}
?>
我使用的是FB PHP SDK v4和JS SDK v2.1。
这是因为JavaScript还没有完成吗?我该如何避免这种情况?
存在一些问题:
1-缺少session_start()
。
2-FacebookSession::setDefaultApplication(string $appId, string $appSecret)
,你放错了参数
3-在尝试/捕获之前启动$session = null;
样品:http://www.inmotionhosting.com/support/website/api/connecting-to-the-facebook-api-using-the-facebook-php-sdk