Interfejs API Facebooka: Zaloguj się za pomocą JavaScript SDK, a następnie sprawdź stan logowania za pomocą PHP
Używam SDK JavaScript na Facebooku, aby wywołać wyskakujące okienko logowania, gdy użytkownik kliknie przycisk Logowanie.
Kod, jak podaje Facebook, jest następujący:
$(".loginButton").click(function(){
FB.login(function(response) {
FB.api('/me', function(response) {
console.log(response.id);
//User ID shows up so I can see that the user has accepted the app.
});
});
Mogę także użyćFB.getLoginStatus()
sprawdzić, czy użytkownik rzeczywiście się zalogował i zaakceptował aplikację.
Jednak teraz chciałbym wykonać funkcję z PHP. O ile rozumiem, PHP ma$user
któremu przypisano identyfikator użytkownika po pomyślnym zalogowaniu.
Problem występuje po zalogowaniu JS$user
jest wciąż0
. Utknąłem i nie mogę zrozumieć, dlaczego nie przypisze poprawnego identyfikatora użytkownika$user
Oto mój JS:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $AppId; ?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true,
channelUrl : '<?php echo $ServerPath; ?>channel.php' // custom channel
});
};
//Get Login Status
function amILoggedIn(){
var toreturn = "";
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
window.userId = response.authResponse.userID;
toreturn = "GetLoginStatus: logged in" + " " + "<?php echo $user; ?>";
} else {
toreturn = "GetLoginStatus: Logged Out";
}
console.log(toreturn);
});
};
// 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/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
var obj = {
method: 'feed',
link: 'http://www.google.com'
};
$(".loginPopupButton").click(function(){
FB.login(function(response) {
FB.api('/me', function(response) { //user-specific stuff
console.log(response.id);
});
});
});
</script>
A oto PHP:
<?php
include_once('fbapi/facebook.php');
include_once('fbapi/Authenticated_User.php');
include_once('config.php');
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $AppId,
'secret' => $AppSecret
));
//Facebook Authentication part
$user = $facebook->getUser();
$perms = "manage_pages";
if(isset($_GET['backlink']))
$redirectUrl = urldecode($_GET['backlink']);
else
$redirectUrl = $fullserverpath;
$cancelUrl = $ServerPath."index.php?page=loginWFb";
//AA - where to go to get FB popup.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => $perms,
'redirect_uri' => $redirectUrl,
'cancel_uri' => $cancelUrl
)
);
//AA- Defining that a powerUSER is someone who's logged in
if(isset($user)){
$_SESSION['loggedIn'] = $user;
}
?>