FB.getLoginStatus() callback not called when user is logged out of Facebook - facebook

FB.getLoginStatus() works fine if the user is logged into facebook. But, if the user is not logged into facebook, then FB.getLoginStatus() callback is not called and I am not able to handle that case in my code because I dont get a callback. I am not in sandbox mode.
I also added 'true' to force the callback eg) FB.getLoginStatus(function(response){}, true) . It did not help. Is this a bug? Is it fixed yet?
If not, please give a work around when user is logged out of facebook. I ma stuck with this issue for a week now.
function GetFBLoginStatus() {
FB.getLoginStatus(function(response) {
alert("inside call back function");
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
alert("Connected FBID = " + uid);
} else if (response.status === 'not_authorized') {
alert("not_authorized");
} else {
alert("Not Logged into facebook");
}
return true;
}, true)
}

You can create an auth.logout event:
FB.Event.subscribe('auth.logout', function(response) {
alert('logged out!');
});
Or a better solution, create an auth.authResponseChange event:
FB.Event.subscribe('auth.authResponseChange', function(response) {
console.log('The status of the session changed to: '+response.status);
alert(response.status);
});
Update:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
status : true,
cookie : true,
xfbml : true,
});
FB.Event.subscribe('auth.login', function(response) {
alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
alert('logged out');
});
};
function GetFBLoginStatus() {
FB.getLoginStatus( function(response) {
console.log(response);
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
alert(accessToken);
} else if (response.status === 'not_authorized') {
//login function
alert('login first');
} else {
//login function
alert('login first');
}
}, true);
}
//Load the SDK Asynchronous
(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));
</script>
<div>
<img src="../FacebookSmall.bmp" />ddd
</div>

Responding to Philip's comment: I tried to refresh the page after logging out of facebook. Here is my code: I am calling the javascript function GetFBLoginStatus() on the click of a link. When I am logged into facebook everything works fine. When I am not logged into facebook, I don't get any alerts.
<div id="fb-root">
</div>
<!-- pull down Facebook's Javascript SDK -->
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with your Facebook API key
FB.init({ apiKey: 'XXXXXXXXXXXXX' });
</script>
<div>
<img src="../FacebookSmall.bmp" />
</div>
<script type="text/javascript" language="javascript">
function GetFBLoginStatus()
{
FB.Event.subscribe('auth.authResponseChange', function(response){
alert(response.status);
});
FB.getLoginStatus(function(response)
{
alert("inside call back function");
if (response.status === 'connected')
{
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
alert("Connected FBID = " + uid);
}
else if (response.status === 'not_authorized')
{
alert("not_authorized");
}
else
{
alert("Not Logged into facebook");
}
}, true) ;
}

Related

Facebook app: permission not updating

I am making a facebook app for which i need permissions other than the basic permission. I have tried using scope as well as changing in the app settings, still I get only the basic permissions and no more other permissions. Below is the code :
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxx',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
// handle the response
}, {scope:'user_photos,user_friends,friends_photos,user_status,publish_stream,user_photo_video_tags'});
} else {
FB.login(function(response) {
// handle the response
}, {scope:'user_photos,user_friends,friends_photos,user_status,publish_stream,user_photo_video_tags'});
}
});
};
// 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));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
});
</script>
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>
I understand that it takes some time for app permissions to propagate, but I have waited for hours. Any hint on whats going wrong here?
Thanks.
Not sure why your code is not working and I am yet to try running it on my machine by I am posting a working code here. Please try using this code after following steps mentioned below
Create a new app on facebook.
In Permissions tab, select the user permissions that you want from user.
In code mentioned below, input your app id and try running it.
Code below is taken from http://hayageek.com/examples/oauth/facebook/oauth-javascript/index.php and is basic implementation of Javascript SDK.
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXX', // App ID
channelUrl : 'http://192.168.1.146/facebook/index.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
document.getElementById("message").innerHTML += "<br>Connected to Facebook";
//SUCCESS
}
else if (response.status === 'not_authorized')
{
document.getElementById("message").innerHTML += "<br>Failed to Connect";
//FAILED
} else
{
document.getElementById("message").innerHTML += "<br>Logged Out";
//UNKNOWN ERROR
}
});
};
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
} else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'user_photos'});
}
function getUserInfo() {
FB.api('/me', function(response) {
var str="<b>Name</b> : "+response.name+"<br>";
str +="<b>Link: </b>"+response.link+"<br>";
str +="<b>Username:</b> "+response.username+"<br>";
str +="<b>id: </b>"+response.id+"<br>";
str +="<b>Email:</b> "+response.email+"<br>";
str +="<input type='button' value='Get Photo' onclick='getPhoto();'/>";
str +="<input type='button' value='Logout' onclick='Logout();'/>";
document.getElementById("status").innerHTML=str;
});
}
function getPhoto()
{
FB.api('/me/picture?type=normal', function(response) {
var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
document.getElementById("status").innerHTML+=str;
});
}
function Logout()
{
FB.logout(function(){document.location.reload();});
}
// 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));
</script>
</div>
</body>
</html>
Update: Hope this solves your problem, I will have a look at your tonight and explain what is going wrong with it.

Facebook API get email address

I have to make a website to login with Facebook. Makes sense to be able to send them an email, but I can't get the email address from Facebook.
I followed exactly the instructions from https://developers.facebook.com/docs/facebook-login/getting-started-web/
I add it {scope:email} in FB.login.
How can I get the email address with Facebook API?
My code by now:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'app', // App ID
channelUrl : '//domain.COM/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
FB.api('/me', function(response) {
console.log(response);
});
} else if (response.status === 'not_authorized') {
FB.login(function(response) {},{scope: 'email'});
} else {
FB.login(function(response) {}, {scope: 'email'});
}
});
};
// 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));
</script>
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
I ran into the same issue. Deauthorize the app from the fb account. Then authorize the app again through your test page
I found that it didn't hit the below block once I authorized the app the first time. (adding the scope:email into FB.login once the app has been authorized does no good... i think)
} else if (response.status === 'not_authorized') {
FB.login(function(response) {},{scope: 'email'});
} else {
FB.login(function(response) {}, {scope: 'email'});
}
hope that helps
If you have logged in successfully, calling response.email will return the user's email address.

User is unknown on when FB.login is triggered

I am new to using the FB JS SDK so please bear with me..
I am currently trying to setup facebook login for a website. The problem I have is that when I click the login button and enter my login details facebook ONLY returns user info when I use the account I made the app on. When I use a different account response.authResponse returns a status of "unknown" which I find unusual.
The main function I'm reffering to here is this.loginUser.
I've also noticed that when I enter my details on the account I made the app on facebook will notify me that the app wants access to ... details however when I use a different account the login panel will disapear on login submit and not ask for permission.
Here is my code:
var FBUser = function(options) {
this.userInfo = null;
var that = this;
/* **********************************************
* Default parameter options
* **********************************************/
this.options = $.extend({
signInBtn: null,
messageContainer: null,
accountContainer: null
}, options);
/* **********************************************
* Initialise functions
* **********************************************/
this.init = function (){
//Load FB JS SDK
this.checkIfLoggedIn();
//Bind event handlers
this.bindEventHandlers();
};
//Check if user is already logged in, if so return data
this.checkIfLoggedIn = function(){
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log("You logged in before so were retrieving your info...");
// the user is logged in and has authenticated your app
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
that.userInfo = response;
that.showUserInfo();
// connected
} else if (response.status === 'not_authorized') {
alert("not connected");
// not_authorized
} else {
// not_logged_in
}
});
};
//Run event handlers to window
this.bindEventHandlers = function() {
if(that.options.signInBtn !== null){
//Trigger fb Login
$(document).on("click", that.options.signInBtn, function(){
console.log("triggered get login");
that.loginUser();
});
}else{
console.log("Btn ID's are null");
}
};
//Trigger FB login
this.loginUser = function(){
FB.login(function(response) {
console.log("RESPONSE IS: ");
console.log(response);
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
console.log('Welcome! You just logged in. Fetching your information.... ');
that.userInfo = response;
that.showUserInfo();
} else {
// sign out
console.log('User does not grant extended permissions');
}
}, {scope: 'email, read_friendlists, user_birthday, user_location'});
};
//Show user info
this.showUserInfo = function (){
var info = this.userInfo;
if(this.userInfo){
FB.api('/me', function(info) {
console.log('Good to see you, ' + info.name);
console.log("USER DATA IS: ");
console.log(info);
//Append user info
if(that.options.messageContainer){
$(that.options.accountContainer).show();
$(that.options.messageContainer).html(info.name)
.prepend('<img src="https://graph.facebook.com/'+info.id+'/picture" alt="'+info.name+'">');
}else{
console.log("facebook container is null");
}
if(that.options.signInBtn){
$(that.options.signInBtn).hide();
}else{
console.log("Login button is null");
}
});
}
};
//Log user out
this.FBLogout = function(){
FB.logout(function(response) {
console.log("user is now logged out");
$(that.options.signInBtn).show();
$(that.options.accountContainer).hide();
});
};
return this.init();
};
/* **********************************************
* Initialise FB app
* **********************************************/
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : ''
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.statusChange', function(response) {
alert('The status of the session is: ' + response.status);
});
/* **********************************************
* Initialise FB user object
* **********************************************/
//Make sure document is ready before creating object due to jquery references
$(document).ready(function (){
//FB initialise options
var FBUserOptions = {
signInBtn: '#fb_login',
messageContainer: '#welcome',
accountContainer: '#account_area'
};
//create FB user object
var fb_user = new FBUser(FBUserOptions);
});
};
/* **********************************************
* Load FB JS 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));
The HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Facebook Login</title>
<script type="text/javascript" src="static/js/plugins/jquery-1.9.1.min.js"></script>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="static/js/fb_login.js?=v33"></script>
<style type="text/css">
body{font-family: Arial, Helvetica, sans-serif;}
#account_area{display: none;}
</style>
</head>
<body>
<div id="fb-root"></div>
Login to facebook
<div id="account_area">
<div id="welcome"></div>
Sign out
</div>
</body>
</html>

FACEBOOK O-AUTH dialog opening on load automatically

i have a login page where i will give link for facebook login but unfortunately the facebook oauth dialog opens up as soon as i land on the the login page .I want it on click of the link and not on page load.Can any help?
<p><a onclick='login(); return false;'>Login</a></p>
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : '3423243443', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow server to access session,
xfbml: true, // enable XFBML and social plugins
oauth: true // enable OAuth 2.0
// channelUrl: 'http://www.yourdomain.com/channel.html' //custom channel
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
alert("connected1"+response.authResponse.expiresIn);
} else if (response.status === 'not_authorized') {
// not_authorized
login();
} else {
// not_logged_in
alert("not logged in");
login();
}
},true);
};
(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));
/*function login() {
FB.login(function(response) {
if (response.authResponse) {
testAPI(response)
// connected
alert("connected2 "+response.authResponse);
} else {
// cancelled
alert("cancelled");
alert("cancelled"+response.authResponse);
}
});
} ;
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.email + '.');
});
} ;*/
</script>
Because you inserted the FB.getLoginStatus, which calls your login function, in window.fbAsyncInit on every page's loads.
You should fire FB.getLoginStatus only though a button, with an onclick trigger.
Here is a little example: http://facebook.stackoverflow.com/a/15720747/2212966
I have mine wrapped with a jquery button click event handler. Here is a snippet from my code:
window.fbAsyncInit = function() {
FB.init({
appId : 'my-app-id',//use your facebook appId in here
status : false,
cookie : true,
xfbml : true,
version : 'v2.2'
});
jQuery('#signUpWithFacebookButtonId').click(function(){
FB.login(function(response) {
if (response.status === 'connected') {
console.log('Logged into your app and Facebook.');
} else if (response.status === 'not_authorized') {
console.log('The person is logged into Facebook, but not your app.');
} else {
console.log('The person is not logged into Facebook, so we are not sure if they are logged into this app or not.');
}
}, {scope: 'public_profile, email'});
});
};//end window.fbAsyncInit function

Facebook UserID working with Desktop Version not working in Mobile Device

This Code Works fine with Facebook Desktop Versions but not working on Mobile Devices I want to get current User Id .
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript"></script>
<script>
// 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 = document.location.protocol + '//connect.facebook.net/en_US/all.js';
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
var called = false;
window.fbAsyncInit = function () {
FB.init({
appId: 'XXXX', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
alert("12");
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
alert("Your UID is " + response.authResponse.userID);
}
else if (response.status === 'not_authorized') {
// not_authorized
alert("3");
login();
alert("5");
} else {
// not_logged_in
alert("4");
login();
}
});
};
if (!called) {
alert("Not Called");
window.fbAsyncInit();
alert(" Called");
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
console.log('Good to see you, ' + response.name + '.');
});
}
function login() {
FB.login(function (response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
});
}
</script>