Facebook App in Profile Tab: problems getting the user session - facebook

I'm working in a mini-app, which will have 3 pages, and i want all the interaction to happen inside a profile-tab.So, using javascript, i want to show/hide a few divs, which i'll populate using the FBJS ajax object.
My problem is, i'm not getting the user session in the ajax calls.As documentation is extremely confusing, i've ended up not knowing if this is possible at all.Any ideas?

You can get the user's id if you require login from your ajax request on a profile tab. For instance:
var ajax = new Ajax();
ajax.responseType = Ajax.RAW;
ajax.ondone = function(data) {
console.log('done');
console.log(data);
}
ajax.onerror = function(data) {
console.log('error');
console.log(data);
}
ajax.requireLogin = true;
ajax.post('http://DOMAIN/add_story', {story: story});
The requireLogin = true part will cause an authorization window to popup. If they agree, you can get the user ID in your AJAX handler using the PHP SDK, like:
$facebook->getUser();

Related

Unexpected behavior for Facebook Sharing [duplicate]

This question already has an answer here:
Facebook ignoring OG image on first share
(1 answer)
Closed 6 years ago.
First of all hi and thanks in advance to anyone who can help with this because I've been going crazy over this for weeks now.
So I've got a website which lists gif taken from my mobile application (which are then stored on AWS and my visitors ( I haven't found a use for me to have users) can share these gifs on facebook using the facebook sdk.
The problem appears when I try sharing an image for the first time
This is what the share dialog shows the first time I click on my sharing button:
http://i.stack.imgur.com/lNVNF.png
and then I close and reclick the same button and now it works:
http://i.stack.imgur.com/YsDUm.png
Now I've been trying to find a way to make this work on the first sharing attempt but to no avail.
I am using meteor in combination with biasport:facebook-sdk and Amazon S3 for the hosting of my files.
Edit here is the code used:
FRONT SIDE
HTML
<div class="facebook share">
<img src="/gallery/fb.png">
</div>
Javascript
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
FB.ui({
method: 'share',
href: url
});
}
SERVER SIDE
JAVASCRIPT
if(Meteor.isClient) {
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
status : true,
xfbml : true,
version : 'v2.5'
});
};
}
Edit: I found a manual solution using exec future and curl
so first I added a call to a meteor method on the share that updates the facebook crawler
JAVASCRIPT
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
Meteor.call('updateCrawler', url, function(){
FB.ui({
method: 'share',
href: url
});
});
}
Then I defined my meteor method as such
JAVASCRIPT
Meteor.methods({
updateCrawler: function(url){
var future = new Future();
cmd = 'curl -X POST -F "id=' + url + '" -F "scrape=true" -F "access_token={my_access_token}" "https://graph.facebook.com"';
exec(cmd, function(error){
if (error){
console.log(error);
}
future.return();
});
future.wait();
}
});
it's ugly but since I'd have to wait for the crawler to update and it works I'll leave this here for future use for someone maybe
Edit2:
I did not use og tags at all since I was simply sharing a url to aws directly and not a url to my website
I worked around this problem by calling the Facebook API direct from the server to make it scrape the og data by requesting info on the page. First time round it doesn't have the image cached but second time it does so this workaround does the initial call before sharing.
Use an access token for your facebook app and call the below in an ajax call and await the response before opening share dialog. Replace Google address with your own uri encoded address https://graph.facebook.com/v2.5/?id=http%3A%2F%2Fwww.google.co.uk&access_token=xxxxx
EDIT:
As per comments, here is my server side method for calling this which I use when posts etc are inserted to make the initial call and prompt a scrape from fb:
var getTheOGInfo = function (link)
{
if (!link || link.slice(0, 4).toLowerCase() != "http"){
throw new Meteor.Error("og-info-bad-url", "Function requires an unencoded fully qualified url");
return false;
}
var url = "https://graph.facebook.com/v2.5/{{{{id}}}}?access_token={{{{token}}}}&fields=og_object{id,description,title,type,updated_time,url,image},id,share";
var token = Meteor.settings.private.fb.token;
if (!token){
throw new Meteor.Error("og-info-no-token", "Function requires a facebook token in Meteor.settings.private.fb.token");
return false;
}
var link_id = encodeURIComponent(link);
url = url.replace('{{{{token}}}}', token).replace('{{{{id}}}}', link_id);
var result = HTTP.get(url, {timeout:1000});
return result;
}
Or for your purposes you may not want anything that might be blocking so you could change the last two lines to be aynchronous:
var result = HTTP.get(url, {timeout:1000});
return result;
//Replace with non blocking
HTTP.get(url, {timeout:1000}, function(err, result){console.log('something asynchronous', err, result);});
return true;

auth.logout is not working in my app using firebase facebook authentication

I have tried basic steps of Firebase Facebook authentication. So in my app the user can successfully log in using Firebase Facebook authentication. But I have a problem in logout.
I used logout button and bind click event on that, as shown below:
$(function(){
$('#lgout').click(function(){
auth.logout();
});
});
For login I use this code:
var chatRef = new Firebase('https://my-firebase-url');
var auth = new FirebaseSimpleLogin(chatRef, function(error, user) {
if (error) {
// an error occurred while attempting login
alert("please login first");
} else if (user) {
// user authenticated with Firebase
//alert('User ID: ' + user.id + ', Provider: ' + user.provider);
$.ajax({
type: "GET",
url: "https://graph.facebook.com/"+user.id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#user').text("Welcome "+data.name);
}
});
} else {
// user is logged out
//auth.login('facebook');
}
});
auth.login('facebook');
In login also, I got one problem as you can see in else part I used auth.login('facebook'); that is not working showing error
auth is not defined. But if I used outside of else then it working fine.
Please help me to figure out this problem.
Separate from the issue regarding auth.logout(), you should never call auth.login('facebook'); from within this callback. Rather, it should be called after a user click event, as your browser will prevent the Facebook pop-up from launching.
From https://www.firebase.com/docs/security/simple-login-overview.html:
Third-party authentication methods use a browser pop-up window to
prompt the user to sign-in, approve the application, and return the
user's data to the requesting application. Most modern browsers will
block the opening of this pop-up window unless it was invoked by
direct user action.
For that reason, we recommend that you only invoke the "login()"
method for third-party authentication methods upon user click.

display my feeds from facebook on my webpage with javascript api?

Im trying to get all the feed from my facebook page whit the javascript api.
Does anybody have a working example?
I have tryed but I cant get it right, I can get photos from albums, but I cant get the feeds and I dont know what Im doing wrong.
Any input really appreciated. Thanks!
I have this code:
Edit
OK, I have the code inside the init code like below and it doesnt work, it is not executing the code and I get no errors:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<%=facebookAppId%>', // App ID
channelUrl : 'www.mypage.se/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
// get the wall - feed
var page_id = '<%=facebookPageId%>';
FB.api('/' + page_id, {fields: 'access_token'}, function(resp2) {
if(resp2.access_token) {
alert(resp2.access_token);
FB.api('/page id/feed?access_token='+resp2.access_token, function(response) {
var ul = document.getElementById('feed');
for (var i=0, l=response.data.length; i<l; i++) {
var
feed = response.data[i],
li = document.createElement('li'),
a = document.createElement('a');
a.innerHTML = feed.message;
a.href = feed.link;
li.appendChild(a);
ul.appendChild(li);
}
});
}
});
};//end window.fbAsyncInit
// 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>
So why can I have for example:
FB.api('/facebook id', function(response) {
alert('Your name is ' + response.name);
});
inside the init code and not the other code?
I would still need some structure help writing the callbacks out on the page so it looks good as it does on facebook.
I like to write out "message, picture, link, name" and maybe something else?
As I test to get the messages in this example and some of the callback is displayed as "undefined" on the page? Does that mean that the message doesnt have a value when I get it?
If so how can I not write out emty values - undefined ones?
Thanks!
UPDATE:
If I use this code then it reads the feed, but only if Im logged in to Facebook?
Im starting to get confused, since I think that the above code should work:
I first ask for the access token in the first call, and when I get the access token, then using it in the second call, what Im I doing wrong?
FB.api('/my userid or pageid/feed?access_token=the acces token that I get from the Graph API Explorer', {limit:5} , function(response){
if (response && response.data && response.data.length){
alert(response.message);
var ul = document.getElementById('feed');
for (var j=0; j<response.data.length; j++){
var feed = response.data[j],
li = document.createElement('li'),
a = document.createElement('a');
a.innerHTML = feed.message;
a.href = feed.link;
li.appendChild(a);
ul.appendChild(li);
}
}
});
I get a couple of undefined responses, how can I not write them out on the page?
How can I get the above code to work even if the user that visit the webpage is not logged in to facebook?
I make other calls that gets the photos of an album with no problem displaying them on the webpage, I dont understand why this is different?
If I want to set this up for a customer(when its finished) what are the steps I need to take? Getting a bit confused... :-)
I would like to get the message, picture, likes etc with the call
and display it like it is on the feed-wall, any suggestions here?
Ok, finally I got it working :-)
I got the right acces token and now I can display the feeds.
I got the right token here:
https://graph.facebook.com/oauth/access_token?client_id=myapp_id&client_secret=myapp_secret&grant_type=client_credentials
And now I can use the below code both for getting user feeds and page feeds, just changing the page_id!
var page_id = '<%=facebookPageId%>';
var pageaccessToken='xxxxxxxxxxxxxxxxxxxxxxxxxx';
FB.api('/' + page_id + '/feed?access_token='+ pageaccessToken, {limit:5} , function(response){
if (response && response.data && response.data.length){
var ul = document.getElementById('pagefeed');
for (var j=0; j<response.data.length; j++){
var feed = response.data[j],
li = document.createElement('li'),
a = document.createElement('a');
a.innerHTML = feed.message;
a.href = feed.link;
li.appendChild(a);
ul.appendChild(li);
}
}
});
Ok, now it works, but I get the undefined in the response?
What is causing this, is it because it is a empty value that I get in the response?
What can I do so it is not displayed on the page?
I don't understand what it is you're trying to do, I have the feeling though that you took the wrong path..
Let's start with the fact that you don't need any special permission or a page access token to query for the page feed, it's public and so all you need (quoted from the docs) is: "any valid access_token or user access_token".
Which means that if a user authorized your application, you then acquired an access token for him and can get any page feed.
For example try the southpark page feed in the Graph API Explorer.
Another issue is that asking the user for the "manage_pages" permission and then asking the graph api for the access token of your own app would not work. When a user grants your app to manage his pages that's exactly what you get, the permissions to his pages, and so this request for example: /southpark?feilds=access_token won't get you the token since you are not the admin of this page (even if you grant the app with the "manage_pages" permission).
Last thing is the use of window.onload, which in your situation just does not address the problem.
You don't want to execute that code when the window is loaded but when the facebook sdk is loaded and intialized. That's why facebook tells you to use the fbAsyncInit event.
The code you had before the window.onload is the correct form, what exactly do you mean when you say "it didn't work"? Did you get any errors? It did not get executed?
Edit
From what I understand you want to display the content of a facebook Page feed in your website.
As I already told you, all you need in order to get the feed of a page is an active access token ("any valid access_token or user access_token").
If you follow the Authentication doc, the App Login section you'll see that you can issue an access token for your facebook app. With that token you can then get the feed of ANY PAGE you want on the server side.

facebook javascript sdk not posting via ajax using fb.api and .post

I have a facebook application. The users are logged in and authorized. I am calling fb.api to post the user's name to my textfile. The alert shows the name. The post doesn't seem to post to my aspx file..
FB.Event.subscribe('edge.remove', function (href, widget) {
alert("outside");
FB.api('/me', function (response) {
alert(response.name);
var paramsObj = { 'name': response.name };
$.post("ajax/delete.aspx", paramsObj);
});
window.location.replace("Default.aspx");
});
I've updated my code to include showing the encapsulating facebook calls to give a broader picture as well as to include #Lix changes [thank you!].
Few things you might want to try :
Define your post parameters object before and only place the objects name in the jQuery $.post method.
Wrap your json keynames with quotes.
var paramsObj = { 'name':response.name};
$.post("ajax/write.aspx", paramsObj );
Use firebug/chrome developers tools to debug the AJAX request and see if any value is being passed and/or use breakpoints in your code to help you understand where the value is missing.
The page was being redirected prior to the api call/ajax post. This is what worked:
FB.Event.subscribe('edge.remove', function (href, widget) {
FB.api('/me', function (response) {
var paramsObj = { 'name': response.name };
$.post("ajax/delete.aspx", paramsObj);
window.location.replace("Default.aspx");
});
});

Facebook login hangs at "XD Proxy" when page is installed via Chrome Web Store

The created the following web application:
http://www.web-allbum.com/
I also added it to the Chrome Web Store:
https://chrome.google.com/webstore/detail/idalgghcnjhmnbgbeebpdolhgdpbcplf
The problem is that when go to the Chrome Web Store and install this app the Facebook login windows hangs at a "XD Proxy" window. While the connect itself works, this blank window can confuse the users.
I did my research, and this seems to be a Chrome issue:
https://code.google.com/p/chromium/issues/detail?id=59285#c26
If you uninstall the app from Chrome, the problem disappears.
Is there any workaround for this problem?
Similar stackoverflow questions:
Facebook connect login window locking in Chrome
FB.login dialog does not close on Google Chrome
facebook connect blank pop up on chrome
https://stackoverflow.com/questions/4423718/blank-page-with-fb-connect-js-sdk-on-after-permission-request
This is my Facebook connect in case it helps:
FB.init({
appId : window.__FACEBOOK_APP_ID__,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : window.__MEDIA_URL__ + 'channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
FB.XD.Flash.init();
FB.XD._transport = "flash";
if (A.networks.facebook.connected) {
FB.getLoginStatus(function (response) {
// Stores the current user ID for later use
that.network_id = response.authResponse.userID;
if (!response.authResponse) {
// no user session available, someone you dont know
A.networks.facebook.connected = false;
}
callback();
});
}
else {
callback();
}
};
The Solution
Thanks to the reekogi reply I was able to workaround this issue. Here is the full implementation:
In order to avoid the XD Proxy problem, you have to connecte to Facebook without using the FB.login, this can be achieved by manually redirecting the user to Facebook page.
I had this login function in my code:
_facebook.connect_to_network = function (callback) {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
// Stores the current user Id for later use
that.network_id = response.id;
console.log('Good to see you, ' + response.name + '.');
callback();
});
}
else {
console.log('User cancelled login or did not fully authorize.');
that.connected = false;
callback();
}
}, {scope: window.__FACEBOOK_PERMS__});
};
Which I replaced by this code:
_facebook.connect_to_network = function (callback) {
var url = 'https://www.facebook.com/connect/uiserver.php?app_id=' + window.__FACEBOOK_APP_ID__ + '&method=permissions.request&display=page&next=' + encodeURIComponent(window.__BASE_URL__ + 'authorize-window?my_app=facebook&my_method=login') + '&response_type=token&fbconnect=1&perms=' + window.__FACEBOOK_PERMS__;
window.open(url);
};
The new code opens a popup which connects to Facebook and returns to the url specified in the 'next' parameter. I added some extra parameters in this callback url so that the javascript code could check for it and close the popup.
This code is executed when the Facebook redirects to the callback url:
_facebook.parse_url_params = function () {
// This is the popup window
if (URL_PARAMS.my_method === 'login') {
window.opener.A.networks.facebook.connected = true;
self.close();
}
};
URL_PARAMS is just a helper object that contains all the url parameters.
I still believe that this is a Chrome issue, but since this workaround has worked and solved my problem I am marking this question as solved.
Could you call a javascript redirect to get permissions then redirect back to the http://www.web-allbum.com/connected uri?
I described this method in detail here ->
Permissions on fan page
EDIT:
The method I demonstrated before will be deprecated when OAuth 2.0 comes into the requirements.
Here is the code, adapted for OAauth 2.0 (response.session is replaced with response.authResponse)
<div id="fb-root"></div>
<script>
theAppId = "YOURAPPID";
redirectUri = "YOURREDIRECTURI"; //This is the page that you redirect to after the user accepts the permissions dialogue
//Connect to JS SDK
FB.init({
appId : theAppId,
cookie: true,
xfbml: true,
status: true,
channelURL : 'http://yourdomain.co.uk/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
//Append to JS SDK to div.fb-root
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
//Check login status and permissions
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
//Redirect to permissions dialogue
top.location="https://www.facebook.com/connect/uiserver.php?app_id=" + theAppId + "&method=permissions.request&display=page&next=" + redirectUri + "&response_type=token&fbconnect=1&perms=email,read_stream,publish_stream,offline_access";
}
});
</script>
Just tried and tested, worked fine in chrome.
I didn't try the solution proposed by Cesar, because I prefer to stick with Facebook's official javascript SDK.
Nevertheless I would like to add a few observations:
Indeed, the blocking problem only happened on Chrome after installing from Chrome Web Store. Uninstalling the web app solves the problem. (tested with legacy authentication method, without oauth 2.0). After closing the XD Proxy popup manually, my application was working properly.
After switching to asynchronous FB.init() and enabling oauth 2.0 option, my application would not even get a valid facebook connect status at login time ({authResponse: null, status: "unknown"})... Again, uninstalling it from the Chrome Web Store, it's working... ({authResponse: Object, status: "connected"})
No problem encountered with Safari, in any of these cases.
In IE8 - this can be caused by your flash version. I tried everything and nothing worked until I disabled flash. More details from this blog:http://hustoknow.blogspot.com/2011/06/how-facebooks-xdproxyphp-seemed-to-have.html#comment-form
Open a new browser tab in Chrome and see if you have the Facebook 'App' installed. If so, drag it to the bottom right corner to uninstall. Once uninstalled the XD Proxy will work.
Reference: facebook connect blank pop up on chrome
I was experiencing same problem for all browsers. When user clicked "login" button, a popup opened and hanged; and unless user killed browser process, it caused a high load on CPU. If user managed to see "allow" button and click it however, then it appeared a "xd proxy" blank window and nothing happened. That was the problem.
After long investigations, I noticed my new JS code which proxies setInterval/clearInterval/setTimeout/clearTimeout methods, caused this problem. Code is as follows:
window.timeoutList = new Array();
window.intervalList = new Array();
window.oldSetTimeout = window.setTimeout;
window.oldSetInterval = window.setInterval;
window.oldClearTimeout = window.clearTimeout;
window.oldClearInterval = window.clearInterval;
window.setTimeout = function(code, delay) {
window.timeoutList.push(window.oldSetTimeout(code, delay));
};
window.clearTimeout = function(id) {
var ind = window.timeoutList.indexOf(id);
if(ind >= 0) {
window.timeoutList.splice(ind, 1);
}
window.oldClearTimeout(id);
};
window.setInterval = function(code, delay) {
window.intervalList.push(window.oldSetInterval(code, delay));
};
window.clearInterval = function(id) {
var ind = window.intervalList.indexOf(id);
if(ind >= 0) {
window.intervalList.splice(ind, 1);
}
window.oldClearInterval(id);
};
window.clearAllTimeouts = function() {
for(var i in window.timeoutList) {
window.oldClearTimeout(window.timeoutList[i]);
}
window.timeoutList = new Array();
};
window.clearAllIntervals = function() {
for(var i in window.intervalList) {
window.oldClearInterval(window.intervalList[i]);
}
window.intervalList = new Array();
};
Removing these lines solved my problem. Maybe it helps to who experiences the same.
It appears this has been fixed in Chrome. No longer happens for us in Mac Chrome 15.0.874.106
Another workaround is to use this code after you call FB.init():
if (/chrome/.test(navigator.userAgent.toLowerCase())) {
FB.XD._origin = window.location.protocol + '//' + document.domain + '/' + FB.guid();
FB.XD.Flash.init();
FB.XD._transport = 'flash';
}
The pop-up window remains open and blank, but I found that in my Chrome Web Store app, the authentication goes through when this code is used.
This bug is also filed on Facebook Developers here: http://developers.facebook.com/bugs/278247488872084
I've been experiencing the same issue in IE9, and it seemed to stem from upgrading to Flash Player 10. The answers suggested already did not work for me and I'd lost hope in trying to fix it since finding an open bug at Facebook covering it. But Henson has posted an answer on a similar question that fixed it for me. In the JavaScript in my site master I removed the lines
FB.UIServer.setLoadedNode = function (a, b) {
//HACK: http://bugs.developers.facebook.net/show_bug.cgi?id=20168
FB.UIServer._loadedNodes[a.id] = b;
};
and now it works. (N.B. I have not checked to see if the IE8 issue those lines were intended to overcome returns.)