Javascript SDK: Check if a user liked a facebook page - facebook

I want to check if a user has liked a page or not and based on it display the contents of the website!
Following is the code using FQL. Is there any way for the same using Javascript SDK?
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "1553725881514063"; //Swoopshows page id
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
alert("Liked");
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
alert("not liked");
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
alert("Please Login to continue");
}
});
});
Also, in my SDK initiation, i have mentioned the version to be 2.0. Still this doesn't work. Any help would be appreciated.

This doesn't work anymore, because Facebook is discouraging "Like-gating" content.
See
https://developers.facebook.com/docs/apps/changelog#v2_1_90_day_deprecations
The 'liked' property will no longer be returned in the 'signed_request' object for Page Tab apps created after today. From November 5, 2014 onwards, the 'liked' property will always return 'true' regardless of whether or not the person has liked the page.
https://developers.facebook.com/docs/facebook-login/permissions/v2.1#reference-user_likes
As you'd need the user_likes permission to determine whether a user has likes the page, and thereby need an app review, you'll very likely not be able to get the permission approved:
Not allowed: Gate access to your app, or some content within your app based on whether or not someone has liked a page.

Related

get user images twitter | angular.js | firebase

im quite new to angular.js and firebase, so im starting to edit some code from an open source script to expens my knowledge ... i used a chat script with a facebook login.
i decided to go change the facebook login to a twitter login. (firebase lets you use logins pretty easy)
function onLoginButtonClicked() {
auth.login("Twitter");
}
the code also automaticly gets the user image from facebook with
<div id="comments">
<script id="template" type="text/template">
<img class="pic" src="https://graph.facebook.com/{{userid}}/picture">
<span><b>{{name}}</b><br/>{{body}}</span>
</script>
But now i changed it to an twitter app i wonder how i can get the twitter user icons instead?
--edit--
whats wrong with the question?
If you check out the user info returned from the login process, you'll see that it contains a an object called thirdPartyUserData. It contains all of the information provided by twitter during login; this is their purview and could change when their API or policies change in the future, but has (for as long as I've been familiar with the Twitter API) contained URLs for user's avatars:
var ref = new Firebase(URL);
var auth = new FirebaseSimpleLogin(ref, function(err, user) {
if( err ) console.error(err);
console.log('avatar is ', user && user.thirdPartyData.profile_image_url);
});
$('button').click(function() {
console.log('clicked it');
auth.login('twitter');
});
(Side note: the login provider is twitter vs Twitter)
There is another way to get the Twitter avatar which works better since getting it from the login user object is only for the logged in user and so would require that the URLs be saved which would then be a problem if the user ever changed their twitter avatar since the URL would then be missing. After some searching around I found that the twitter avatar (or facebook) avatar can be reached from the firebase user id as follows:
var info = userId.split(':');
var provider = info[0];
var id = info[1];
if ( provider === 'facebook' ) {
return 'https://graph.facebook.com/' + id + '/picture?type=square';
} else if ( provider === 'twitter' ) {
return 'http://twitter.com/api/users/profile_image/' + id + '?size=normal';
}

How to check user is fan (or not) of any page with javascript in my ASP.NET site (without fb app)?

In my ASP.NET site, assume that I have facebook user_id and page_id and want to determine user like page or not. I found a samples with creating application, then check user like. I dont want that, firstly user login to application, then cheking. Can I check this without application? What should I do for this? Or other advice please.. If witout application it is not possible, so, how can I hide application login window?
I want user dont use any application, dont know I check his likes.
I need result like this: yes or no
(Sorry for my bad english)
facebook Fan gate, don't forget to include the javascript sdk in your page
FB.getLoginStatus(function (response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "00"; //page id of the page that should be liked
var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
//user like page
}
else {
//user not like page
}
});
} else {
//user not logged in
}
});
}
Put it in a .js file and name it something like facebookscript.js and then in include it in
<head> <script src="facebookscript.js" type="text/javascript"></script> </head> like this.
Take a look at this page how to include the javascript sdk: https://developers.facebook.com/docs/reference/javascript/ otherwise this code wont work.
if the user isn't logged in or have auth... your app send them to login function like this:
function login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Access Token: ' + response.authResponse.accessToken);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
Put the login function where I put the comment tags "//user not like page and //user not logged in" in my last comment.

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.

I cannot access other's facebook page insights though i connected through login pop up

i have create Facebook app for my external website and i created an Access token for that app with the "offline" access Permission (access token) with that token, i placed the Login button in my site ,i'm trying to fetch the insights data's,of those who log in through my External website with Facebook while connect i'm passing the offline_access, Manage_page **read_insights** permission, though permission granted by the page Admins i'm difficult to fetch the insights datas.Please some one help me to figure this
aspx file
<fb:login-button scope="manage_pages,offline_access,read_insights" size="large" style="opacity:.01 !important; width:250px !important;line-height: 31px !important;margin-top:0 !important;" onlogin="getPages()"> Sign In With Facebook Account </fb:login-button></div>
scrpit file
window.getPages = function () {
loadingImage($('#divSettings'), true, ($('.divSettings').outerHeight() - 50) + 'px');
//test
FB.getLoginStatus(function (response) {
if (response.status.toString().indexOf("connected") > -1) {
//User is conected and granded perms Good to go!
// alert('1');
FB.api('/me/accounts', function (resp) {
//var txtpageid = document.getElementById('ctl00_contentPlaceHolderRight_txtFBPageID').value;
var txtpageid = $.trim($('#ctl00_contentPlaceHolderRight_txtFBPageID').val());
// alert(2);
$('#spnFBsignMo').removeClass('Dsh_pop_MessTxt Pop_Facebk_Txt_error').addClass('Dsh_pop_MessTxt Pop_Facebk_Txt');
// if (response.error && response.error.type == "OAuthException") { alert('OAuth2.0 Exception Access token Expired or AppID miss matched'+'<br>'+'please contact Admin'); }
if (txtpageid != '') {
FBactualID = '';
for (var i = 0, l = resp.data.length; i < l; i++) {
var page = resp.data[i];
if (page.id == txtpageid) {
FBactualID = txtpageid;
varFBResponseFlag = true;
//alert('inside the page id validation');
}
}
}
getCheckedValue(FBactualID);
// alert('3');
});
}
else {
//measures to take the users to login again
// alert('You must login to Facebook to Validate the Page ID');
$('#spnFBsignMo').removeClass('Dsh_pop_MessTxt Pop_Facebk_Txt').addClass('Dsh_pop_MessTxt Pop_Facebk_Txt_error'); //DSh_Input_cus DSh_Input_width
loadingImage($('#divSettings'), false, ($('.divSettings').outerHeight() - 50) + 'px');
alert(4);
}
}); // login sta
i'm just give a call to with my access token to fetch information
something like this
https://graph.facebook.com/246355928767490/insights/page_views&access_token=xxxxxx-xxx-xx&since=2011-12-25&untill=2012-01-04
The call to
https://graph.facebook.com/app_id/insights
Will only give you access to insights about your app, not "other's facebook page insights". If you are actually trying to get your own insights, check first that there is any data by going to the insights page and looking at your specific application here:
http://www.facebook.com/insights/
If you are trying to get the visiting, logged in user's Insight stats for pages they own, there are already a number of answers to this. You will need to troubleshoot whether your user is indeed logged in or not but the function you are using to retrieve insights should be right. Have a look at theses previous answers:
Facebook page insights via API
Facebook Insights for Page via the API

In facebook connect, how can I check if a user is a fan of my facebook page? Is it possible to track?

I am trying to determine if a user is a facebook fan. I load the facebook JS library and initialize:
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"></script>
FB_RequireFeatures(["XFBML","Connect","Api"], function() { FB.init("my_api_key","xd_receiver.htm") });
FB.ensureInit(function () {
FB.ApiClient.pages_isFan(my_profile_id,"some_UID",callback);
});
However when I call the API client with FB.ApiClient.pages_isFan, I get a JS error -
FB.ApiClient is undefined
I am also using the FBML fan tag to display the "become a fan" button:
<fb:fan profile_id="my_profile_id" stream="0" connections="10" logobar="1" width="300"></fb:fan>
And would like to be notified when either the "become a fan" button is clicked or a user has successfully become a fan.
The business logic is pretty simple - If they become a fan, track it in my database. Then if they try to become a fan again, check with the library if they are a fan and say "You are already a fan" if they are a fan, show the widget if not.
Using the new JS SDK:
<fb:login-button perms="user_likes">
Grant Permissions to Allow access to Likes
</fb:login-button>
<button onclick="checkDoesLike()">Check if user Likes the Page</button>
<h1>Like this Application's Page</h1>
<fb:like-box profile-id="184484190795"></fb:like-box>
<script>
window.checkDoesLike = function() {
FB.api({ method: 'pages.isFan', page_id: '184484190795' }, function(resp) {
if (resp) {
Log.info('You like the Application.');
} else {
Log.error("You don't like the Application.");
}
});
};
</script>
A working example: http://fbrell.com/fb.api/does-like
Please note that #daaku's answer is true only in two cases:
If your app grant the user_likes permission or
The user's pages privacy setting is set to everyone.
Source:
Note: This call no longer requires a
session key. You must pass a user ID
if you don't pass a session key. If
the user's pages are set to less than
everyone privacy, you must ask the
user for the user_likes extended
permission and include a valid user
access token in the API call.
Try this code to better understand:
<button onclick="checkDoesLike()">Check if user Likes the Page (wrong way)</button>
<button onclick="checkDoesLike2()">Check if user Likes the Page (right way)</button>
<script>
window.checkDoesLike = function() {
FB.api({ method: 'pages.isFan', page_id: '184484190795', uid: '579187141' }, function(resp) {
if (resp) {
Log.info('579187141 likes the Application.');
} else {
Log.error("579187141 doesn't like the Application.");
}
});
};
window.checkDoesLike2 = function() {
FB.api({ method: 'pages.isFan', page_id: '184484190795', uid: '579187141' }, function(resp) {
if (resp == true) {
Log.info('579187141 likes the Application.');
} else if(resp.error_code) {
Log.error(resp.error_msg);
} else {
Log.error("579187141 doesn't like the Application.");
}
});
};
</script>
Working example.
I've also written a full tutorial about this today.
not sure if this is helpful at all, but I inspected the DOM with firebug and I found that it has moved onto the Facebook object
var pageID = 'your page';
var uid = FB.Facebook.apiClient.get_session().uid;
FB.Facebook.apiClient.pages_isFan(pageID, uid, function(result){ alert("boo!");});