Facebook API - User object returning strange values - facebook

I have a user object, but it's only properties are education, first_name, id, last_name, link, locale, location, name, timezone, updated_time, verified. Not only is this missing properties that should be public (like picture), but also these values are different from the documentation (updated_time vs last_updated). Finally, strangely, I get the same thing from the link on the documentation page (here). Ultimately, I'm trying to get user.feed.
Any ideas about what's going on will be greatly appreciated. Am I missing something obvious?
visiting https://graph.facebook.com/me/feed gives the following:
{ "error": {
"type": "OAuthException",
"message": "An active access token must be used to query
information about the current user."
} }
Why do I need an active access token? the docs say that picture and feed are public!
Here is the code. The user object is logged to Firebug.console:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
function update_user_box() {
var user_box = document.getElementById("user");
FB.api('/me', function(user) {
user_box.innerHTML = "<fb:profile-pic uid=\"loggedinuser\" useyou=\"false\"></fb:profile-pic>"
+ "Hey " + user.first_name + "<br>";
FB.XFBML.parse();
console.log(user);
});
}
</script>
</head>
<body>
<div id='user'><fb:login-button onlogin="update_user_box();"></fb:login-button></div>
<br><br>
<div id="fb-root"></div>
<script>
FB.init({
appId : 'b07e858317c9069d450023b7500b4511',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.session) {
update_user_box();
} else {
// no user session available, someone you dont know
}
});
</script>
</body>
</html>

There are a couple of things that you can try
check if the data is matching correctly with https://graph.facebook.com/{YOUR_FB_ID}
Is there any data (that are null) needs extended permission. See here
Are you using right auth_token and oAuth2.0
I hope these will help you debugging.
Edit:
We faced a problem where we were using old API (FB-connect) and trying to get data mentioned in extended permission. We were not able to -- for some reason. We switched to oAuth2.0, and it worked. #3 bullet was just to share my experience.
Also, for photos we just fetched data from http://graph.facebook.com/{user_id}/picture

Get permission from user for offline_access.
Feed https://graph.facebook.com/{ID#username}/feed/

Related

How can I give the Facebook App access to the Facebook Page via the API?

As we all know, inside the Facebook for Developers interface, you can add Facebook Pages to a Facebook App as in the picture below and generate the Page Access Token.
I'm trying to do this programmatically via the API requests. Unfortunately, I did not find in the documentation of the request how to do this.
What have I done so far?
I can get the User ID and User Access Token via Facebook Login (Documentation).
I can get the list of Facebook Pages that a person owns. In the response, I have the Page ID and the Page Access Token (Documentation).
I have the Facebook app that is in development mode. That app has App ID and App Secret. With these values, I can get the App Access Token (Documentation).
I can set Webhook to the Facebook App with App ID and App Access Token (Documentation).
I can set the Webhook Subscriptions Fields for my Facebook App (Documentation).
Question: What kind of API request should I use to add a Facebook Page to the Facebook App?
The list of my requests:
I take Page ID and Page Access Token with this GET request cause this request returns the list of Facebook Pages that a person owns:
https://graph.facebook.com/v9.0/{user-id}/accounts?access_token={user-access-token}
I set the Webhook in my Facebook App with this POST request:
https://graph.facebook.com/v9.0/{app-id}/subscriptions?access_token={app-access-token}&callback_url={url-address}&verify_token={verify-token}&object=page&include_values=true
It successfully works and I see this Webhook in the "Webhooks" block of the Dashboard interface.
Then I make this POST request to set Webhook Subscriptions Fields:
https://graph.facebook.com/{page-id}/subscribed_apps?subscribed_fields=messages,messaging_postbacks,messaging_optins,message_deliveries,message_reads,messaging_payments,messaging_pre_checkouts,messaging_checkout_updates,messaging_account_linking,messaging_referrals,message_echoes,messaging_game_plays,standby,messaging_handovers,messaging_policy_enforcement,message_reactions,inbox_labels&access_token={page-access-token}
In this request, I use Page ID and Page Access Token from the first step.
Unfortunately, I have such an error message:
To subscribe to the messages field, one of these permissions is
needed: pages_messaging
I've been following down a similar rabbit hole. Indeed, Facebook documentation is confusing, but it ended up being pretty simple. Here is the modified Facebook Login example, which gets page access token and then adds necessary webhook subscriptions for page messaging. After you've run it, you will see the page is added to the App settings with the requested webhook subscriptions. Hope it helps πŸ€“
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
let page_access_token = null
let page_id = null
function statusChangeCallback(response) {
// Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback')
console.log(response) // The current login status of the person.
if (response.status === 'connected') {
// Logged into your webpage and Facebook.
testAPI()
} else {
// Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML =
'Please log ' + 'into this webpage.'
}
}
function checkLoginState() {
// Called when a person is finished with the Login Button.
FB.getLoginStatus(function (response) {
// See the onlogin handler
statusChangeCallback(response)
})
}
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR_APP_ID',
cookie: true, // Enable cookies to allow the server to access the session.
xfbml: true, // Parse social plugins on this webpage.
version: 'v12.0', // Use this Graph API version for this call.
})
FB.getLoginStatus(function (response) {
// Called after the JS SDK has been initialized.
statusChangeCallback(response) // Returns the login status.
})
}
// add webhooks to page subscriptions
function addPageSubscriptions() {
FB.api(
`/${page_id}/subscribed_apps`,
'POST',
{
subscribed_fields: [
'messages',
// any other webhook event: https://developers.facebook.com/docs/messenger-platform/webhook/#events
],
access_token: page_access_token,
},
function (response) {
if (response && !response.error) {
console.log({ response })
} else {
console.error(response.error)
}
},
)
}
// pages I have access to
function getPages() {
FB.api('/me/accounts', function (response) {
if (response && !response.error) {
console.log({ response })
page_access_token = response.data[0].access_token
page_id = response.data[0].id
addPageSubscriptions()
} else {
console.error(response.error)
}
})
}
function testAPI() {
// Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ')
// Me
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name)
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!'
getPages()
})
}
</script>
<!-- The JS SDK Login Button -->
<!-- IMPORTANT: Define the scopes for managing pages metadata and pages_messaging for the webhooks -->
<fb:login-button
scope="public_profile,email,pages_manage_metadata,pages_messaging"
onlogin="checkLoginState();"
>
</fb:login-button>
<div id="status"></div>
<!-- Load the JS SDK asynchronously -->
<script
async
defer
crossorigin="anonymous"
src="https://connect.facebook.net/en_US/sdk.js"
></script>
</body>
</html>

Facebook Requires extended permission: publish_actions

I'm in the process of developing a Contest and Promotion-related Facebook app and my intent is to to create a tab on my company's page that will provide access to the app.
Once their, users can nominate local companies for awards. Later on; once the nominations are in, users can vote for a winner.
I've integrated Open Graph into my app so that I can take advantage of Object Types (Organization), Action Types (Nominate, Vote For), and Aggregations (Nominations). My main objective is to then transfer these actions onto the user's timeline.
I've used the recipebox example as my base. I've provided my code to demonstrate authentication and the post action required to submit an action type/object type combination.
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head prefix="og: http://ogp.me/ns# og_<<app namespace>>: http://ogp.me/ns/apps/<<app namespace>>#">
<meta property="fb:app_id" content="<<app id>>" />
<meta property="og:type" content="<<app namespace>>:organization" />
<meta property="og:title" content="Client 1" />
<meta property="og:image" content="<<client image path>>" />
<meta property="og:description" content="Client 1 description here ... " />
<meta property="og:url" content="<<custom client URL>>">
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
// 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));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : '<<app id>>', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
// respond to clicks on the login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
function nominate () {
FB.api('/me/<<app namespace>>:Nominate&organization=<<custom client URL>>', 'post', function(response) {
if (! response || response.error) {
alert('Error occured');
console.log(response);
} else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<div id="auth-status">
<div id="auth-loggedout">
Login
</div>
<div id="auth-loggedin" style="display:none">
Hi, <span id="auth-displayname"></span>
(logout)
</div>
</div>
<h2>Client 1</h2>
<form>
<input type="button" value="Nominate" onclick="nominate()" />
</form>
<fb:activity actions="<<app namespace>>:nominate"></fb:activity>
</body>
</html>
A test user is encountering the following error:
Requires extended permission: publish_actions
And I am encountering the following error (I am an Admin for this app):
This method must be called with an app access_token
The first error is troubling to me. I cannot select publish_actions from Apps | <My App> | Permissions | Extended Permissions. Also, remedies I've encounted suggest I re-categorize my app to Games (this does not work) and to complete my Aggregations (I did; still does not work).
How can I overcome this error?
What can I do to fix my This method must be called with an app access_token error?
Thanks in advance,
Mike
EDIT
I believe the access_token error I was encountering was due to the fact that I was testing/interacting with the app directly on the Page Tab URL; not through Facebook.
I am no longer receiving the Requires extended permission: publish_actions error; however, my testers and developers are. I know that I am encountering this error because the publish_actions permission is not requested at the initial facebook.com login prompt.
If my Developers/Testers logout of Facebook, then log back in with my prompt:
FB.login(function (response) { }, { scope:'publish_actions'});
Then this permission and app is integrated into their Facebook session.
My final question is- is there a defacto, preferred method to request this permission without logging in/out of Facebook?
I have fixed both of my errors. Thank you to those who provided me with feedback and put me on the right path.
These errors have been resolved:
1. Requires extended permission: publish_actions
2. This method must be called with an app access_token
For starters, CBroe is right. Since I require extended permissions (publish_actions) I need to specify this is my options object after the callback function in FB.login() like so:
FB.login(function (response) {
if (response.authResponse) { // The user has authenticated
authenticatedSoDoSomething();
}
else { // The user has not authenticated
notAuthenticatedSoDoSomethingElse();
}
}, { scope:'publish_actions' });
Lastly, I had no success using the JavaScript SDK to publish an action to a user's timeline via FB.api(). This is the code I was using:
FB.api('/me/<<app namespace>>:<<my action>>&<<my object>>=<<a URL>>', 'post',
function(response) {
if (! response || response.error) {
alert('Error occured');
} else {
alert('Post was successful! Action ID: ' + response.id);
}
})
I neglected to include the app access token. The app access token can be constructed by concatenating the app id, followed by a pipe, followed by the app secret.
I used the PHP SDK to fulfill this request as I wanted to keep my api secret a secret. Here is [most] of the code I used:
require_once('facebook-php-sdk/src/facebook.php');
$facebook = new Facebook(
array(
'appId' => '<<my app id>>',
'secret' => '<<my app secret>>'));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
echo json_encode(array('success' => false));
}
}
try {
$facebook->api('/' . $user . '/<<app namespace>>:<<my action>>&<<my object>>=<<a URL>>', 'POST', array('access_token' => $facebook->getAppId() . '|' . $facebook->getApiSecret()));
}
catch (FacebookApiException $e) {
echo var_dump($e->getResult());
}
Hope this helps!
For the second one, make the call with your App Access Token like the error says; if you're already doing this and it's failing, check the app isn't set to 'Native/Desktop' mode in the app's settings in the facebook App Dashboard. If it is, the app access token is untrusted and the API acts as though you didn't provide it.
For the first, are you sure users are granting publish_actions permission to your app? A call to /me/permissions with the user's access token will show you which permissions are granted. Note that the authenticated referrals / app center login flow is separate to your app's regular flow for users that end up there other than via an authenticated referral or the app center, so check you're including publish_actions in the scope in your call to the Oauth Dialog.

Errors in IE 8 from connect.facebook.net/en_US/all.js caused by credits callback

Setup:
Got a working facebook app and am correctly setup for facebook credits transactions (i.e. everything on the serverside is working fine).
In Firefox and chrome transactions complete without issue, however in IE8 the callback upon completing/closing the purchase dialog throws the following errors:
Error 1:
Line: 52 Error: Object doesn't support this property or method
Object doesn't support this property or method JScript - script block, line 52 character 37
Where the function it points to is:
ui: function( params )
{
obj = FB.JSON.parse( params );
method = obj.method;
cb = function( response ) { FBAS.getSwf().uiResponse( FB.JSON.stringify( response ), method ); }
FB.ui( obj, cb );
},
Specifically highlighting this bit:
FBAS.getSwf().uiResponse( FB.JSON.stringify( response ), method )
in the http://connect.facebook.net/en_US/all.js file
Error 2:
Line: 65 Error: Object doesn't support this action
Object doesn't support this action all.js, line 65 character 2198
[The line it points to is a stupidly long unformatted unreadable mess so I'll omit it unless requested]
Specifically highlighting this bit:
delete d._old_visibility
again in the http://connect.facebook.net/en_US/all.js file
The html I'm using (with the app identifying stuffs removed) is as follows:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Expires" content ="0" />
<meta http-equiv="Pragma" content ="no-cache" />
<meta http-equiv="Cache-Control" content ="no-cache" />
<title>[ APP NAME ]</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
$(document).ready
(
function()
{
var appId = [ APP ID ];
var host = [ APP HOST ];
// If the user did not grant the app authorization go ahead and
// tell them that. Stop code execution.
if (0 <= window.location.href.indexOf ("error_reason"))
{
$(document.body).append ("<p>Authorization denied!</p>");
return;
}
// Loads the Facebook SDK script.
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
// When the Facebook SDK script has finished loading init the
// SDK and then get the login status of the user. The status is
// reported in the handler.
window.fbAsyncInit = function()
{
//debugger;
FB.init(
{
appId : appId,
status : true,
cookie : true,
oauth : true,
});
FB.getLoginStatus (onCheckLoginStatus);
};
// Handles the response from getting the user's login status.
// If the user is logged in and the app is authorized go ahead
// and start running the application. If they are not logged in
// then redirect to the auth dialog.
function onCheckLoginStatus (response)
{
if (response.status != "connected")
{
top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + encodeURIComponent (host+"[ RELATIVE APP PATH ]") + "&scope=publish_stream,user_about_me,read_friendlists,user_photos";
}
else
{
// Start the application
loadGame();
}
}
}
);
function loadGame()
{
var flashvars = {};
var params = {};
var attributes = {};
params.allowscriptaccess = "always";
attributes.id = 'flashContent';
attributes.name = 'flashContent';
swfobject.embedSWF("[ APP SWF ]?"+Math.floor(Math.random()*10000), "flashContent", "100%", "99%", "10.0", null, flashvars, params, attributes);
}
</script>
<div id="flashContent" >
Loading...
</div>
</body>
This is just a problem for IE 8 but is stopping the app going live since a significant number of users transactions would fail (or rather would complete, be charged and not take effect due to the failed callback).
For the past few days I've been searching for others with this or a similar problem but to no avail.
I've seen some similar issues where people are warned about javascript variables being created globally and causing interfereance or variables being names using keywords reserved in IE but as far as I can tell neither is the case here. The facebook javascript code is fairly boilerplate stuff lifted from facebook dev pages and reliable sources. It may be JQuery (which I have little experience with), however, again, this is lifted from working examples and if there is a problem I can't see it.
Can anyone help?
SOLVED
I won't accept this answer because I honestly don't think the question was answerable/solvable with the info provided and feel it would be bad form. But I want to leave this here for anyone that might be looking for a solution.
Cause of the error
The problem is the result of the combination of facebook hiding the app during 'normal' facebook actions (in this case, displaying the pay prompt) and external interface calls not working in Internet explorer when the app is hidden/not visible.
Solution
Found at http://flassari.is/2012/02/external-interface-error-object-expected/#comment-1743
All of these steps may not be neccessary but in the end what I did was:
Stop facebook hiding the app by overriding the visibility using
<style>
#[ ID OF THE FLASH OBJECT]
{
visibility: visible !important;
}
</style>
Adding wmode = "opaque"; to the swfobject params
Using the optional flash_hide_callback by adding hideFlashCallback:"OnHideFlash" to the FB.init options in the actionscript to move/hide the app instead, where OnHideFlash is a javascript function:
function OnHideFlash(params)
{
if (params.state == 'opened')
{
getSwf().style.top = '-10000px';
} else
{
getSwf().style.top = '';
}
}
Where getSwf() is your prefered method of getting the flash app object.
Hopefully this will save some people the suffering of pouring through the endless 'reasons that XYXY doesn't work in IE' questions and solutions that has been my last few days.
I suggest putting your code through a JavaScript Lint tool and correcting any errors you find. IE8 is extremely picky about how JavaScript is coded, while Firefox and Chrome are ok with minor mistakes. If your code is error free (after linting), it should work properly.

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>

JS SDK FB.login() works but pop-up dialog is staying open after logged in

I am using the JS SDK for Facebook based on the NEW GraphAPI for Auth/Login.
Has anyone had this issue when logging in after FB.login() was called via the JS SDK?
The problem: after I initialize by calling FB.Init() asynchronously (because this all wrapped in a window.fbAsyncInit function) the login pops up; I log in but then that pop-up refreshes to show a white page and the pop-up stays open and does not close...why? I am waiting to check response.session in the FB.login() callback but it seems as though I never get it back because this pop-up seems to just stick there and the process appears to just halt after you're logged in and I just figured this pop-up would just close and return me the response.session in the callback automatically. Why would that pop-up not go away?
I copied the url from the pop-up after I'm logged in and showing white the following url so it looks like the response is there but then why isn't that pop-up window closing so my callback can handle the response??
http://static.ak.fbcdn.net/connect/xd_proxy.php#?=&cb=f18fe0b7c66da54&origin=http%3A%2F%2Flocalhost%2Ff3745f32ed63a7a&relation=opener&transport=postmessage&frame=f18adb488566372&result=user_photos&session={%22session_key%22%3A%222.vH4SVCisnh8HJWjEI1Vy_Q__.3600.1280106000-100001379631246%22%2C%22uid%22%3A%22100001379631246%22%2C%22expires%22%3A1280106000%2C%22secret%22%3A%22TH45WFg8I_5r_cOoVIujjg__%22%2C%22access_token%22%3A%22132444323462464|2.vH4SVCisnh8HJWjEI1Vy_Q__.3600.1280106000-100001379631246|q123iPQcKY45xWXtOZ2ebOOZTQQ.%22%2C%22sig%22%3A%22a75e85af2354292bfdcf90b9d319ebf7%22}
I did notice that when FB.login() is called and the login pop-up comes up, I see this error in FireBug talking about how it doesn't like the fact that I'm testing over localhost or something I guess:
uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMLocation.host]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: chrome://smarterwiki/content/smarterwiki.js :: anonymous :: line 1225" data: no]
that error bothers me...I need to figure out why it's coming up and I bet you I'm not the only one who has seen this when testing locally. I see no info though on troubleshooting this on the net anywhere either on the Facebook forums or elsewhere. I see others have had this issue but no resolution.
So when you implemented yours, did your facebook pop-up just close after the user is logged in or did you need to do something special to finish this process?
Also, I notice if I manually close that pop-up then go to check if that cookie was generated to contain my session, it's not (the fbs_[yourappid] cookie). So it looks like something ends prematurely here. I've got in my init cookie: true so I wonder if this problem were the pop-up dialog is not closing is related to the cookie also not being created client-side on my test PC.
This problem appeared out of nowhere for my site, when facebook made a recent change to its "all.js".
In an earlier version of their javascript I had a problem specific to IE, and I copied this little snippet of code from someone's post on the internet. It seemed cryptic, but solved the problem at the time:
// http://developers.facebook.com/bugs/204792232920393
// Hack to fix http://bugs.developers.facebook.net/show_bug.cgi?id=20168 for IE7/8/9.
FB.UIServer.setLoadedNode = function (a, b) { FB.UIServer._loadedNodes[a.id] = b; };
FB.UIServer.setActiveNode = function(a, b) { FB.UIServer._active[a.id]=b; };
It turns out those lines were causing this problem for me. I removed them, and the problem went away. The original bug specific to IE has also been fixed, I believe, in the most recent "all.js".
I don't know what your code is, but my problem was I forget to add
<div id="fb-root"></div>. My code :
<div id="fb-root"></div>
<script src="http://static.ak.fbcdn.net/connect/en_US/core.js"></script>
<script>
FB.init({ apiKey: 'app key'});
</script>
<div class="fbloginbutton" id="fb-login" onclick="Login();">
<span id="fb_login_text" >Login with Facebook</span>
</div>
<asp:Label ID="errMsg" runat="server"></asp:Label>
<script type="text/javascript">
function Login() {
FB.login(function(response) {
document.getElementById('fb_login_text').innerHTML = 'Logout';
if (response.session) {
FB.api('/me', function(response) {
var str;
str = response['id'] + ";" +
response['name'] + ";" +
response['first_name'] + ";" +
response['last_name'] + ";" +
response['link'] + ";" +
response['birthday'] + ";" +
response['gender'] + ";" +
response['email'];
alert(str);
});
}
else {
document.getElementById('fb_login_text').innerHTML = 'Login with Facebook';
}
}, { perms: 'user_birthday,email' });
};
</script>
As you see I don't use div fb-root anywhere but It is requered to facebook login work!
I struggled with this issue recently. The problem appeared from no where, presumably from some change in the Facebook JS SDK. For what its worth I plan to never use the JS SDK again, these random issues eat up my time.
Anyway here is the hack that I used to get around the issue.
var accessToken, fb_response;
if (window.location.hash.length < 30) {
window.location = "http://www.facebook.com/dialog/oauth?client_id=YOUR_ID&redirect_uri=YOUR_URL&scope=YOUR_PERMISSIONS&response_type=token";
} else {
fb_response = window.location.hash;
accessToken = fb_response.substr(14, fb_response.indexOf("&expires") - 14);
FB._authResponse = {
accessToken: accessToken
};
window.location.hash = "";
FB.api("/me", function(profile) {
if (profile.id) {
app_init();
} else {
alert("Problem connecting to Facebook");
}
});
}
Basically I send the user to the Facebook oauth dialog and when they return I grab the access token from the hash. I then set the internal access token parameter on the Facebook Object. Once this is done you can make all the normal Facebook Api calls.
Hopefully this helps someone!
For future projects I will definitely stick to a server side auth flow, you have a lot more control!
It seems that you are trying the localhost, can you try it with the public url.
I already faced this problem. But I solved it by configuring the canvas url in application as the public url (example. www.something.com/test/).
This is a working sample for me:
<!DOCTYPE html>
<html>
<head>
<title>Facebook Client-side Authentication Example</title>
</head>
<body>
<div id="fb-root"></div>
<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 = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : '00000000000000', // Your App ID
channelUrl : '//'+window.location.hostname+'/channel', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
// respond to clicks on the login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
</script>
<h1>Facebook Client-side Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
Login
</div>
<div id="auth-loggedin" style="display:none">
Hi, <span id="auth-displayname"></span>
(logout)
</div>
</div>
</body>
</html>
The website clearly says that all.js is expired. However, I get the same error you got only with sdk.js. Problem was fixed when went back to the depreciated all.js
// Old SDK (deprecated)
js.src = "//connect.facebook.net/en_US/all.js";
// New SDK (v2.x)
js.src = "//connect.facebook.net/en_US/sdk.js";
facebook sdk