0
我一直試圖解決這個問題,現在幾天了,但似乎無法理解我做錯了什麼。這個想法是讓用戶使用Javascript登錄並在通過PHP進行重新驗證之前,在數據庫中輸入用戶的信息,但它一直說「沒有設置cookie或不能從cookie獲取OAuth數據」。Facebook登錄使用Javascript和PHP
的index.php:
var appLoginFlag = false;
var appAccessToken = null;
window.fbAsyncInit = function() {
FB.init({
appId: 'xxxxxxxxx',
cookie: true,
status: true,
xfbml: true,
oauth: true,
version: 'v2.2'
});
checkLoginState();
};
function statusChangeCallback(response) {
if (response.status === 'connected') {
appLoginFlag = true;
if (response.authResponse) {
console.log(response.authResponse);
FB.api('/me?fields=id,name,first_name,last_name,email', function(response) {
console.log('Email: ' + response.email);
console.log('Name: ' + response.name);
$.ajax({
type: "POST",
url: "user_insert.php",
success: function(result) {
document.getElementById('login-wrap').innerHTML = 'Hi <strong>' + response.first_name + '</strong>!';
}
});
});
}
}
else {
console.log(response.status);
appLoginFlag = false;
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
(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/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
function FBLogin() {
FB.login(function(response) {
FB.api("/me/feed", "post", {message: "Some message"}, statusChangeCallback(response));
},
{scope: 'public_profile, email, publish_actions'
});
}
user_insert.php:
<?php session_start();
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxxxxxxxxx',
'app_secret' => 'xxxxxxxxxxxxxxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
// instructions to insert into database
?>