Facebook SDK返回错误:
跨站点请求伪造验证失败。 URL和会话的“状态”参数不匹配。
我在同一控制器中使用fblogin()
和fbcallback()
。但是面对这个错误。还要在developer.facebook.com中执行所有步骤。会话也开始。但是错误说,不匹配。
public function fblogin(){
$this->load->library('session');
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID', // Replace {app-id} with your app id
'app_secret' => '{APP_SECRET}',
'default_graph_version' => 'v2.5',//v2.5
]);
$helper = $fb->getRedirectLoginHelper();
// if (isset($_GET['state'])) {
// $helper->getPersistentDataHandler()->set('state', $_GET['state']);
// }
// $sURL = $helper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://www.collegeprintsusa.com/maintenance/signin/fbcallback', $permissions);
// echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
header("location: ".$loginUrl);
}
public function fbcallback() {
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.5',//v2.5
]);
// $serializedFacebookApp = serialize($fb);
// $unserializedFacebookApp = unserialize($serializedFacebookApp);
// echo $unserializedFacebookApp->getAccessToken();
$helper = $fb->getRedirectLoginHelper(); //'https://www.collegeprintsusa.com/maintenance/signin/fblogin'
// $_SESSION['FBRLH_state'] = $_REQUEST['state'];
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$fbClient = $fb->getClient();
$accessToken = $helper->getAccessToken($fbClient);
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: collegeprintsusa.com');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email', $accessToken);
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
// echo $fbid.','.$fbfullname; die();
# save the user nformation in session variable
$get_user_email = $this->user_model->get_single_user(['email' => $fbemail]);
if($get_user_email){
$res_user_fbid_update = $this->user_model->update_users(['id' => $get_user_email['id']],['facebook_id' => $fbid]);
if($res_user_fbid_update){
$this->session->set_userdata(['username' => $get_user_email['usename'],
'name' => $get_user_email['name'],
'last' => $get_user_email['last_name'],
'email' => $get_user_email['email'],
'type' => $get_user_email['user_type'],
'uid' => $get_user_email['id'],
'phone' => $get_user_email['phone'],
'address' => $get_user_email['address'],
'profile_image' => $get_user_email['profile_image'],
'disable' => $get_user_email['sms_update']]);
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}else{
$res_user_reg = $this->user_model->add_users([
'name' => $fbfullname,
'email' => $fbemail,
'phone' => 0,
'user_type' => 'customer',
'username' => $fbemail,
'password' => SALT . sha1($fbemail),
'token' => SALT . sha1($fbemail),
'facebook_id' => $fbid
]);
if($res_user_reg){
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: index.php");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
}
答案 0 :(得分:1)
在这里,我想提出一个更好的解决方案,以使用Facebook登录。请使用JavaScript而不是PHP,因为PHP会在Facebook页面上重定向,而JavaScript不会重定向,它将在自己的网站上打开Facebook登录弹出窗口,并且根据性能,该过程非常快速简便。
请按照以下代码使用JavaScript登录Facebook。
$(document).ready(function($) {
window.fbAsyncInit = function() {
FB.init({
appId : '186770818730407', // Set YOUR APP ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fbLogin()
{
FB.login(function(response) {
if (response.authResponse) {
getFBUserInfo();
}else {
showToaster('error','User cancelled login or did not fully authorize.');
return false;
}
},{scope: 'email,user_photos,user_videos'});
}
function getFBUserInfo() {
FB.api('/me',{fields: "id,picture,email,first_name,gender,middle_name,name"}, function(response) {
$.ajax({
url : "http://example.com/welcome/facebook_login",
type : "POST",
data : {response:response},
dataType : "JSON",
beforeSend:function(){
ajaxindicatorstart();
},
success: function(resp){
ajaxindicatorstop();
if(resp.type == "success"){
fbLogout();
showToaster('success',resp.msg);
setTimeout(function(){
window.location.href = base_url() + 'account-setting';
},1000);
}
else{
showToaster('error',resp.msg);
}
},
error:function(error)
{
ajaxindicatorstop();
}
});
});
}
function fbLogout()
{
FB.logout(function(){ console.log('facebook logout') });
}
// 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));
});
希望您会喜欢。
谢谢