FB.getLoginStatus does not fires callback function - facebook

I have a difficult problem. Difficult means I searched through the net and StackOverflow as well the whole FBJS SDK documentation and haven't find answer.
I am building a Page Tab application where I'd like to let fans to rsvp events. So I have to check if the user is logged in and if it doesn't I have to login. That sounds pretty easy, but FB.getLoginStatus doesn't fires callback function. This is the code excerpt:
FB.init({
appId: window.appID,
status: true,
xfbml: true,
cookie: true,
oauth: true,
channelUrl: 'http://example.com/fb/channel.html'
});
and then I simply - of course after the user clicks on a button - call FB.getLoginStatus, but it seems it doesn't do anything.
I've already checked sandbox mode, FB.init success, URLs in application settings and developing environment. I can call FB.ui, although FB.ui with method: 'oauth' I get an error message saying " The "redirect_uri" parameter cannot be used in conjunction with the "next" parameter, which is deprecated.". Which is very weird because I didn't used "next" parameter. But when I set next to undefined, it works fine, I get the window, but it says "Given URL is not allowed by the Application configuration.". Expect from that, I can login, then I've got the access_token. But in the new window, getLoginStatus still doesn't do anything.
So any advices are welcome.
Thanks,
Tamas
UPDATE:
function onBodyLoad() { //on body onload
FB.init({
appId: window.appID,
status: true,
xfbml: true,
cookie: true,
oauth: true,
channelUrl: 'http://example.com/fb/channel.html'
});
}
...
function getName() { // on button onclick
FB.getLoginStatus(function(response){
if (response.authResponse)
{
window.loggedIn = true;
debugString('Logged in');
} else
{
window.loggedIn=false;
debugString('Not logged in');
}
}, true);
if (window.loggedIn === undefined) {
debugString('getLoginStatus did not exec'); // I always get this message
}
}
UPDATE 2: I created a new App on a different URL, which is configured as a standalone website. There these codes work perfectly, I can getLoginStatus, I can login, etc. Is there any difference working in the context of FB, and in a standalone website, using FB JavaScript SDK?

FB.getLoginStatus does not fire the callback when you are running the website on a different domain than the one that you registered the app with. I usually find myself in this situation when I am developing locally or on a staging server.
For example, if you registered the site with example.com and your staging server is example.mystagingserver.com, the callback wont fire. In this case, you need to create a second application in Facebook and use the Application ID and Secret for the new app.

I just had the same problem, though it only happened to some users.
I finally found out that if your app is sandbox mode, none-developer users can still see your app as a pagetab. But calling getLoginStatus will fail silently (even logging turned on).
Took a while to figure that one out, I hope this can save someone else some time.

I'm using this code, successfully. I'm not quite sure where the differences are.. but I'm using the ASYNC FB Loader.
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXX', //change the appId to your appId
status: true,
cookie: true,
xfbml: true,
oauth: true});
function authEvent(response) {
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user is not connected to your app or logged out
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email,rsvp_event,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
accessToken = response.authResponse.accessToken;
userid = info.id;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name+"<br /> Your Access Token: " + accessToken;
}
}

You can use the following code to check if the user is logged in:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
From FB JS SDK Documentation.
You can wrap the whole code in jQuery ready :
$('document').ready(function(){
... above code
})
Also you may want to check this question StackOverflow.

I had the same problem. I was working on the facebook login process of our website. During development the "FB.getLoginStatus" did not return a response. I fixed it in the settings of the app on facebook:
-In facebook go to "manage apps"
-Go to the "facebook login" settings of your app
-Add your development url (for example "https://localhost") to the "Valid OAuth Redirect URIs"
(Don't forget to remove the "https://localhost" from the OAuth Redirect URIs when you are finished with developping.)

Something common that causes this is that a browser is blocking cookies, this will cause the event not to fire. Also, make sure that if you or your user have and ad blocker that it is not blocking third party cookies.
Example of warning:

For me after extensive testing can confirm the dialog to log the user will not show unless you use a valid Application ID
These can be found in
https://developers.facebook.com/apps/{{Application__Id}}/settings/
Just make sure you call the api with the correct ID.

Related

facebook users who r not my friends but using the app

The new Facebook graph api has divided friends into Friends & Invitable_friends .
me/friends/ returns my friends who are using the app while me/invitable_friends/ returns only the list of my friends who are not using the app.
But in my app,a user may interact with random users too who may not be on his friend list.
So how do i get user data for those who are using the app but are not on my friend list.
Thanks.
I went through the same issue and solved it like that: when a user starts your app by default you ask for permission to access his public profile information, which includes real ID, name and some other. You simply store the user data (id, name, etc.)in a database. This way you keep track of all the people using your app and they can interact with each other.
JavaScript Example:
window.fbAsyncInit = function () {
FB._https = true;
console.log('here');
FB.init({ appId: 'xxxxxxxxxxxxxxxx', cookie: true, xfbml: true, oauth: true, version : 'v2.0'});
Login();
};
function Login() {
FB.login(function(response) {
if (response.authResponse){
checkUser();
}
else{
console.log('User cancelled login or did not fully authorize.');
}
}
);
}
function checkUser() {
FB.api('/me', function(response) {
$.ajax({
type: "get",
url: "cgi-bin/checkUser.cgi",
cache: false,
data: {"user_name" : response.name, "u_id" : response.id, "link" : response.link},
success: function() //onSuccess,
{
console.log("user " + response.name + " checked!");
},
error: function()
{
console.log("Error with server connection on user checking");
}
});
});
}
I don't know in what language you are writing the app but I believe that in every language you should call the "login" function, which asks the user for permissions and basically gets access to info.
To get details of users who are using the app but are not your friends,call the following
graph.facebook.com/v2.0/
?ids={comma-separated-ids}&access_token=app_access_token&fields=name,picture
access_token is a must else graph-api returns following error-
The global ID xyz is not allowed. Please use the application specific ID instead.
This will work for all users who have authenticated the app no matter their authentication date,but for any non-app user graph-api returns above error message.

Facebook app - Silent "Protocols must match" error

Here is my current login flow for my Facebook app (see this answer for an explanation). logout() and login() are dummy functions that render the page when the user is logged out or logged in.
window.fbAsyncInit = function() {
FB.init({
appId: '...',
channelUrl: window.location.protocol + '//' + window.location.host + '/channel.html',
status: false,
cookie: true,
xfbml: false,
oauth: true
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
login(response);
} else {
FB.Event.subscribe('auth.login', function(response) {
login(response);
});
logout();
}
});
};
With this login flow, I don't have to reload the page when the user logs in, but I get the silent error:
Blocked a frame with origin "http://www.facebook.com" from accessing a
frame with origin "https://s-static.ak.facebook.com". The frame
requesting access has a protocol of "http", the frame being accessed
has a protocol of "https". Protocols must match.
I assume that reloading the page transfers the iframe holding the app to the https:// protocol, but I don't really understand why or what that means. Why is this error occurring, and is it something to be concerned about?
This is a security issue in most browsers. You cant ajax an https link from a http page
possible duplicate of Facebook gives "Unsafe JavaScript attempt to access frame with URL" error in Chrome

Cakephp Facebook Plugin - Sharing through an action

I am using Nick Baker's (webtechnick) CakePHP / Facebook plugin which is awesome and works great, however I have a question that I can't seem to even come close to answer for.
How would I bypass the use of a share button and share directly through an action?
For instance, I make a post through my site and the post adds to the DB as it should, it also shoots a post to the logged in users Twitter account through the action. How can I also have this action handle sharing it to my FB account (connection has already been made).? I tried the first thing I think anyone would obviously try $this->Facebook->share() directly in the action, too no avail...
Any thoughts or solutions would be of great help...
UPDATE AFTER ANSWER
Thx for the help spooney. I voted your answer up because you are 100% spot on from what I can tell. I am loading the JS SDK.
function init($options = null, $reload = true) {
if (empty($options)) {
$options = array();
}
if ($appId = FacebookInfo::getConfig('appId')) {
$session = json_encode($this->Session->read('FB.Session'));
if ($reload) {
$callback = "FB.Event.subscribe('auth.login',function(){window.location.reload()});";
} else {
$callback = "if(typeof(facebookReady)=='function'){facebookReady()}";
}
$callback .= "FB.Event.subscribe('auth.logout',function() {window.location = '/bastards/users/logout'});";
$init = '<div id="fb-root"></div>';
$init .= $this->Html->scriptBlock(
<<<JS
window.fbAsyncInit = function() {
FB.init({
appId : '{$appId}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // use Oauth
});
{$callback}
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/{$this->locale}/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
JS
, $options);
return $init;
} else {
return "<span class='error'>No Facebook configuration detected. Please add the facebook configuration file to your config folder.</span>";
}
}
I have no problem pulling in the user information and working with all that. I have accomplished posting to FB from my site, but it was only through a link, using FB.ui...
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
I have tried replacing the code above with...
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
</script>
But it errors everytime.
I should also throw in there that the post on the users FB wall isn't really coming from the site persay, it's a post from the user on their own wall basically stating, "I made a post on ladala.com, you should go check it out at ."
So now I'm at the point that I need to figure out how to run FB.ui through the action that submits the post.
Based on our conversation, I figured I would just put a more complete description in an answer.
You can fire a share call using the JavaScript SDK.
First, you would need to load the JavaScript SDK as described in the Loading section of https://developers.facebook.com/docs/reference/javascript/.
Once loaded into your page, the two calls you want to look at are FB.getLoginStatus, and FB.api. FB.getLoginStatus will give you back a response telling you if the user is logged in to facebook, and if they have approved your application. This link will describe the functionality of getLoginStatus, but in short, you need to check for response.connected(and then possibly do another call to confirm a user's permissions, if required).
If the user is logged in and has approved your app, you can then attempt to make an API call using FB.api. Keep in mind to do this, you will likely need the user to have allowed the publish_stream permission.
Your code would look something like this:
//Do FB initialization
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
//Post was successful
}
});
}
});
This can be triggered any way you want. On page load, on click, on completion of some other event, etc.
Keep in mind this is just one way to implement this. Also, if you are trying to share something with your FB application, and it is not working, you should confirm that you have all the permissions required to do so.

Facebook - How can i post to a company using the javascript sdk?

Im new to facebook posting but have had some success with posting offline with a user account but cannot post offline with a company page.
I have created my own "Facebook App" called "Nicks Poster App" via my own personal facebook account. I have granted three permissions (offline_access,read_stream,publish_stream) to the app for both my personal page and my company page.
i did this by following these steps for each account...
Creating the app...
1. Login to facebook with the account you want linked to the app
2. Follow this link http://www.facebook.com/developers/apps.php#!/developers/createapp.php
3. Create your app and take a note of you App Id and your App secret Id.
Giving the correct rights to the app and getting the access_token..
Method 1:
1. Get the account in question to login to facebook
2. However you like, direct the user to this link (replacing <App-Id> with the App Id of the created app) https://graph.facebook.com/oauth/authorize?client_id=<App-Id>&scope=offline_access,read_stream&redirect_uri=http://www.facebook.com/connect/login_success.html
3. Take a note of the result of the “code” querystring.
4. Goto this url (replace “<APP-ID>” with you appId and “<APP-SECRET>” with your apps secret id and “<code>” with the copied code)
https://graph.facebook.com/oauth/access_token?client_id=<APP-ID>&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret=<APP-SECRET>&code=<code>
5. Copy what you see, minus the expires querystring. That is your access_token.
After i had the access token for both accounts i used this code to make the post.
<!-- FACEBOOK -->
<div id="fb-root"></div>
<script>
(function () {
var e = document.createElement('script');
// replacing with an older version until FB fixes the cancel-login bug
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//e.src = 'scripts/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
</script>
<!-- END-OF-FACEBOOK -->
<script>
//initialise
window.fbAsyncInit = function () {
FB.init({
appId: '351023398277068',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true // Enable oauth authentication
});
};
function sendPost(inMessage) {
var opts = {
message: inMessage,
access_token: '<SAVED-TOKEN>'
};
FB.api('/me/feed', 'post', opts, function (response) {
if (!response || response.error) {
alert('Posting error occured');
}
else {
alert('Success - Post ID: ' + response.id);
}
});
}
</script>
When executing the "sendPost" command with the perameter 'Test post', it will work for my personal account (providing i put my access_token in place). This does not work for my company page, and im at a loss as to why(i do put my acess_token in place).
Facebok also havent documented this very well and it makes it hard to make progress, does anyone understand why this doesnt work for company pages?
Thank you in advance.
You can set the "to" parameter to target the page you wish to post to, "manage pages perms will be needed if you wish to post as your page to your page as the application.
<div id="msg"></div>
<script>
// uid is the id of the page or user you wish to post to.
function feedthis2(uid) {
// calling the API ...
var obj = {
method: 'feed',
to: ''+uid+''
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
feedthis2('AnotherFeed'); // to http://facebook.com/anotherfeed
//feedthis2('135669679827333');
</script>

FB.getLoginStatus returns a session even after the user has logged out of Facebook

This is driving me crazy. A user logs into my Facebook app, does some stuff. Then goes to Facebook and logs out. I've got a little timer that calls FB.getLoginStatus() every once in a while to see if the user is still logged in. But whenever FB.getLoginStatus() gets called it returns a response with a session object. WTF? Shouldn't it return undefined/unknown?
I'm using the absolute most basic call to Facebook evar:
FB.init({
appId: 'MY APP ID',
cookies: false,
status: true,
xfbml: false
});
FB.getLoginStatus(function (response) {
if (response.session) {
console.info("Session exists");
} else {
console.info("Session empty");
}
});
setInterval(function () {
FB.getLoginStatus(function (response) {
if (response.session) {
console.info("Session exists");
} else {
console.info("Session empty");
}
});
}, 10000);
I checked and double checked the permissions that are being requested with the allow. I am only requesting email and sms. So.... any advice?
don't do it in the hard way. This situation has a simple solution, just add a "true" statement as a second parameter from the getLoginStatus method:
FB.getLoginStatus(function (response) {
if (response === undefined || response.status === 'connected') {
// Do something after logout
}
}, true);
Just be careful and aware that every call to this function will make your App to go to Facebook's servers and can give you a considerable amount of network load depending on your implementation. Hope this helps!
I had the same problem using your code.
The only way I got round it so far is to initialise the sdk each time login status is queried:
setInterval(function () {
FB.init({
appId : 'xxxx', // App ID
channelUrl : 'xxxx', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
FB.getLoginStatus(function (response) {
if (response.authResponse) {
console.info("Session exists");
} else {
console.info("Session empty");
}
});
}, 10000);
In this way I always get the correct session status. If there's a more efficient way to do this please let me know!
Try initializating FB with
status: false
So it will work as you expect. It worked for me
Are you sure the session always gets destroyed when the user logs out? Maybe it's just a var inside the session that changes if the users logs in or out....?