Get Facebook Photo of a Album with oauth2.0 - facebook

Hello I have a script working well with the previous release of facebook API.
With oauth 2.0 is not more working.
I solved the first problem of login, now I’m getting the list of Album of Me but I cannot have the pictures.
This first script make the authorization and retrieve the album list.
When I select an album I pass the id and token to a php file that is in the second script. There I should load the picture of the specifyied album, but is not working.
I wonder if the problem is in the cover call https://graph.facebook.com/'+album+'/picture?access_token='+access_token+
And in the
FB.api("/"+albumid+"/photos",function(response){…
call..
Saomeone can help me to finde where I’m wrong?
Here is it possible to finde the complete script. goo.gl/HY59u
Thanks
Federico
<div id="fb-root"></div>
<script>
var loggedIn = false;
var isLoaded = false;
function loginFacebook() {
if(!isLoaded) {
alert("SDK is not yet loaded or something went wrong!");
return false;
}
//initializes the facebook API
document.getElementById("status").innerHTML = "In attesa del permesso Facebook";
//opens the Facebook login window for user
FB.login(function(response) {
if (response.authResponse) {
document.getElementById("status").innerHTML = "Logged In. Ora puoi caricare gli album.";
loggedIn = true;
//disables the login button after the user has loggedIn
document.getElementById("loginBtn").disabled = "Disabilitato";
document.getElementById("loginBtn").style.display = "None";
document.getElementById("albumBtn").style.display = "inline";
document.getElementById("fb_logo").style.display = "None";
document.getElementById("label_fb").style.display = "None";
} else {
document.getElementById("status").innerHTML = "Non hai effettuato il Facebook Login";
loggedIn = false;
}
},{scope:'user_photos'});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxx', // App ID
channelUrl : 'www.xxxxx.com/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
});
// Additional initialization code here
isLoaded = true;
};
// Load the SDK Asynchronously
(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));
//loads the all the album currently present in user's facebook profile
//Requests to '/me/albums'
function loadAlbums() {
if(loggedIn) {
document.getElementById("status").innerHTML = "Caricando gli album dal tuo profilo Facebook";
var counter = 0;
FB.api('/me/albums', function(response) {
document.getElementById("albumsList").innerHTML = '';
for(var c in response["data"]) {
addOption(response["data"][c].name,response["data"][c].id);
counter++;
}
document.getElementById("albumBtn").style.display = "none";
document.getElementById("status").innerHTML = "<p>Ci sono "+ counter +" album sul tuo profilo Facebook.</p><p> Scegli quello che vuoi inserire</p>";
});
} else {
document.getElementById("status").innerHTML = "Non hai effettuato il Facebook Login. Fai il Facebook login per caricare gli album.";
}
}
//Adds a new album link into albumsList div
function addOption(opText,opVal) {
document.getElementById("albumsList").style.display = "block";
var v = document.getElementById("albumsList");
v.innerHTML += '<br/><a target="_self" href="../facebook/album.php?id='+opVal+'&name='+opText+'">'+opText+'</a>';
}
function init() {
var v = document.getElementById("loginBtn");
v.onclick = loginFacebook;
v.disabled = "";
var v1 = document.getElementById("albumBtn");
v1.onclick = loadAlbums;
v1.disabled = "";
}
//calls init function once all the resources are loaded
window.addEventListener("load",init,true);
other script
<!-- Include the Facebook Javascript API -->
<script src="http://connect.facebook.net/en_US/all.js"></script>
<!-- Include the normal stylesheet-->
<link href="style.css" rel="stylesheet" />
<script type="text/javascript">
var album = "";
var access_token = "";
function init() {
FB.init({
appId : 'xxxxxxx', // App ID
channelUrl : 'www.sssss.com/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
});
var _album = getParameter('id');
if(_album!="") {
album = _album;
access_token = getAccessToken();
document.getElementById("album_desc").innerHTML = unescape(getParameter('name'));
//Album Header Photo link, https://graph.facebook.com/ALBUM_ID/picture?access_token = ACCESS_TOKEN
document.getElementById("album_cover").innerHTML += '<img src="https://graph.facebook.com/'+album+'/picture?access_token='+access_token+'" />';
getAlbumPhotos(album);
} else {
album = "No Album ID passed";
document.getElementById("album_cover").innerHTML = '<span class="error">'+album+'</span>';
}
}
//queries the cookie on browser, to get the access_token
function getAccessToken() {
splitArray = document.cookie.split(";");
access_token = "";
for(var v in splitArray) {
if(splitArray[v].substr(0,4)==" fbs") {
access_token = splitArray[v];
break;
}
}
var arr = access_token.split("&")[0].split("=");
return arr[arr.length-1];
}
//gets all the photos in the album
function getAlbumPhotos(albumid) {
//Queries /ALBUM_ID/photos
FB.api("/"+albumid+"/photos",function(response){
var photos = response["data"];
document.getElementById("photos_header").innerHTML = "Foto("+photos.length+")";
for(var v=0;v<photos.length;v++) {
var image_arr = photos[v]["images"];
var subImages_text1 = "("+(v+1)+")";
//this is for the small picture that comes in the second column
var subImages_text2 = '<img src="'+image_arr[(image_arr.length-1)]["source"]+'" class="imagedropshadow" />';
//this is for the third column, which holds the links other size versions of a picture
var subImages_text3 = "";
//gets all the different sizes available for a given image
for(var j = 0 ;j<image_arr.length;j++) {
var Maxsize = Math.max(image_arr[0]["width"]);
if(image_arr[j]["width"]== Maxsize)
{
subImages_text3 += '<a target="_blank" href="'+image_arr[j]["source"]+'">Seleziona</a> <input type="checkbox" name="checkbox_fb[]" value="'+image_arr[j]["source"]+'"> <input type="hidden" name="w_prev" id="w_prev" value="'+image_arr[(image_arr.length-1)]["width"]+'"/> <input type="hidden" name="h_prev" id="h_prev" value="'+image_arr[(image_arr.length-1)]["height"]+'"/> <br/>';
}
}
addNewRow(subImages_text1,subImages_text2,subImages_text3);
}
});
}
function addNewRow(data1,data2,data3) {
//inserts a new row into the table
var table = document.getElementById("album_photos");
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = data1;
cell = row.insertCell(1);
cell.innerHTML = data2;
cell = row.insertCell(2);
cell.innerHTML = data3;
}
//This function gets the value of album, passed in the request string
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
//the regular expression that separates the album from the queryString
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
//calls init function once all the resources are loaded
window.addEventListener("load",init,true);
</script>

Related

FB api with firebase

I am having difficulty figuring out how to link a facebook account with an existing firebase email/password account. I can link it but then have no clue how to make calls to the FB api. Or i can not have it linked and used the FB api itself to make the login. I really want to be able to link the account to an existing email/password account.
var facebook = document.getElementById('facebook');
//var twitter = document.getElementById('twitter');
//var google = document.getElementById('google');
var fbunlink = document.getElementById('fbunlink');
//var twitunlink = document.getElementById('twitunlink');
//var googleunlink = document.getElementById('googleunlink');
var fbList = document.getElementById('fbList');
var provider = "";
var fbToken = "";
var fbId = [];
var fbName = [];
var fbLength = 0;
var fbAccessToken ="";
var fbUID = "";
var auth = firebase.auth();
var user = firebase.auth().currentUser;
window.fbAsyncInit = function() {
FB.init({
appId : '1899992333573742',
xfbml : true,
version : 'v2.10'
});
FB.AppEvents.logPageView();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
}
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
facebook.addEventListener('click', e => {
provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('email');
provider.addScope('user_photos');
provider.addScope('publish_pages');
provider.addScope('business_management');
provider.addScope('read_insights');
provider.addScope('manage_pages');
provider.addScope('public_profile');
auth.currentUser.linkWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
var credential = result.credential;
var user = result.user;
// ...
}
document.getElementById('fbunlink').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'visible';
document.getElementById('facebook').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You are logged in.';
getInfo();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
/*
FB.login(function(response) {
if (response.status === 'connected') {
document.getElementById('fbunlink').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'visible';
document.getElementById('facebook').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You are logged in.';
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
fbAccessToken = uid;
fbUID = accessToken;
getInfo();
linkInfo();
} else if (response.status === 'not_authorized') {
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You have logged out of Facebook.';
} else {
document.getElementById('status').innerHTML = 'You are not logged in.';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('fbList').style.visibility = 'hidden';
}
}, {scope: 'email, user_photos, publish_pages, business_management, read_insights, manage_pages, public_profile'});
});*/
fbunlink.addEventListener('click', e => {
var user = firebase.auth().currentUser;
user.unlink("facebook.com");
document.getElementById('picture').innerHTML = "";
document.getElementById('status').innerHTML = 'You are not logged in.';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('fbList').style.visibility = 'hidden';
});
function getInfo(){
FB.api('/me/accounts?limit=200', 'GET', {fields: 'business, name, data, id, picture', access_token : fbToken}, function(response){
document.getElementById('status').innerHTML = "";
console.log(response.data);
fbLength = response.data.length;
for(var i = 0; i < fbLength; i++){
fbId.push(response.data[i].id);
fbName.push(response.data[i].name);
document.getElementById('status').innerHTML += "<img src='https://graph.facebook.com/" + fbId[i] + "/picture?type=square'>" + " " + "<input type=" + "'checkbox'" + " id=" + "'" + fbId[i] + "'" + " value=" + "'" + fbId[i] + "'" + ">" + fbName[i] + "<br>";
}
});
}
/*function linkInfo(){
var credential = firebase.auth.FacebookAuthProvider.credential(fbUID, fbAccessToken);
auth.currentUser.link(credential).then(function(user) {
console.log("Account linking success", user);
}, function(error) {
console.log("Account linking error", error);
});
}*/
fbList.addEventListener('click', e => {
document.getElementById('picture').innerHTML = "";
for(var i = 0; i < fbLength; i++){
var temp = document.getElementById(fbId[i]);
if(temp.checked){
document.getElementById('picture').innerHTML += "<img src='https://graph.facebook.com/" + fbId[i] + "/picture?type=square'>" + " " + fbName[i] + "<br>";
}
}
});
So it seems you need to make calls to the Facebook API, so continue using Facebook API as Firebase Auth doesn't manage OAuth tokens and you need the FB API to do that for you.
In order to link the Facebook account to an email/password account, you need to use the Facebook API to get the FB user's OAuth access token.
You then link that to the currentUser:
firebase.auth().currentUser.linkWithCredential(firebase.auth.FacebookAuthProvider.credential(fbAccessToken))
This links that Facebook user to the email/password currentUser.

Facebook auto posting from website

i need to make script like this one here:
http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/?ref=top
after few seconds of viewing the post automaticly redirect you to facebook APP and request you to loggin to see the post. After the first login everytime you see any other post automaticly post to your timeline.
Its javascript and can be find in the source of the website but wont work... something missing there...
can some one help me please?
<div
id="fb-root"></div><script>
var app_id = '467647329957056'; var cookie_prefix = 'onion_mk_';
var appdomain = 'onion.mk';
var appdomain_formatted = appdomain.charAt(0).toUpperCase() + appdomain.substring(1);
function setCookie(c_name, value, exdays, time) {
var exdate = new Date();
if(time!='')
{
exdate.setTime( exdate.getTime() + (time*60*1000));
}else{
exdate.setDate(exdate.getDate() + exdays);
}
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/;domain=" + appdomain;
document.cookie = cookie_prefix + c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = ARRcookies.length - 1; i >= 0; i--) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookie_prefix + c_name) {
return unescape(y);
}
}
}
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
window.fbAsyncInit = function() {
FB.init({
appId : app_id,
status : true,
cookie : true,
xfbml : true
});
FB.Event.subscribe('edge.create', function (response) {
document.getElementById('likeboxbgr').style.display='none';
document.getElementById('likebox').style.display='none';
});
FB.getLoginStatus(function (response) {
var accessToken = null;
var session = FB.getAuthResponse();
if (session != null) {
accessToken = session.accessToken;
}
var token = accessToken;
var userID;
if(response.status == 'connected')
{
FB.api('/me', function (resp) {
userID = resp.id;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + 487604931274728 + " and uid=" + userID;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == userID) {
document.getElementById('likeboxbgr').style.display='none';
document.getElementById('likebox').style.display='none';
}else
{
document.getElementById('likeboxbgr').style.display='block';
document.getElementById('likebox').style.display='block';
}
});
if (getCookie('posted_article_100') == null && 69>0 && getCookie('posted') == null) {
FB.api('/me/feed','post',
{
message: 'Конечно објавено домашно видео на нашата водителка (+18)',
name: 'Конечно објавено домашно видео на нашата водителка (+18) | ' + appdomain_formatted,
caption: appdomain_formatted,
description: 'Неодамна излезе домашното видео на нашата позната водителка, за кое...',
link: 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1',
picture: 'http://onion.mk/wp-content/uploads/2013/02/SuperSexyGirls1.jpg'
},
function (rsp) {
if (rsp.id) {
setCookie('posted_article_100', '1', 5);
setCookie('posted', '1', 5, 15);
} else {
console.log(rsp);
top.location.href = 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1';
};
}
);
}
});
}else if (response.status === 'not_authorized')
{
document.getElementById('wrapper').style.opacity = 0.12;
top.location.href = 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1';
}else
{
console.log('not logged!');
}
});
};
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
</script>
From a quick look, it looks like that code should work.
Have you set up your app in facebook developer properly - and asked for the correct permissions to post on to the user's timeline?

Facebook FB.login dialog fails with error

New to Facebook apps, developing a test app using JavaScript:
I am logged-in to Facebook as the app administrator (regular user).
I get to the point where FB.getLoginStatus returns response.status === 'not_authorized'.
I call FB.login.
I get a popup saying "An error occurred. Please try again later."
FB.login calls back with response.authResponse = null.
The console log says "LOG: Could not find callback 1".
I get the same error in all browsers...
Help?
Here is the relevant code - I replaced actual strings by ######:
<div id="fb-root"></div>
<script>
var init_status = 1;
var login_status = 1;
var signedRequest = ' ';
window.fbAsyncInit = function() {
FB.init({
appId : '######', // App ID from the App Dashboard
channelUrl : 'http://#####/channel.php', // Channel File for x-domain communication
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : false // parse XFBML tags on this page?
});
getLoginStatus();
};
// 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));
call_proceed1_when_ready(); // wait for init_status > 1
function proceed1() {
// Login the user and/or authenticate with app, if necessary:
if (init_status > 2) {
login ();
} else {
login_status = 2;
}
call_proceed2_when_ready(); // wait for login_status > 1
} //proceed1
function proceed2() {
alert('DONE');
} //proceed2
////////////////
// FUNCTIONS: //
////////////////
function call_proceed1_when_ready () {
if (init_status > 1) {
proceed1();
} else {
setTimeout(call_proceed1_when_ready, 500); // 0.5 second
}
}
function call_proceed2_when_ready () {
if (login_status > 1) {
proceed2();
} else {
setTimeout(call_proceed2_when_ready, 500); // 0.5 second
}
}
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
signedRequest = response.authResponse.signedRequest;
init_status = 2;
} else if (response.status === 'not_authorized') {
init_status = 3;
} else {
init_status = 4;
}
});
}
function login() {
FB.login(function(response) {
if (response.authResponse) {
login_status = 2;
} else {
login_status = 3;
}
});
}
</script>

FB.API Facebook Open Graph returns empty data for user likes for some users

I have a page in which when the app is permitted by a user, it will list down the user's page likes, and checks whether the user liked my certain facebook page and is a member of that facebook page (in a way both are similar), using FB.API
The problem is that certain users are not returning any data at all, regardless of OS or browser. I already set the 'user_likes' permission on the app, but to no avail.
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<div id="lblName"></div>
<div id="lblAccessToken" style="display: none;"></div>
<br><br>
<fieldset>
<legend>Your Page Likes</legend>
<div id="lblLikes"></div>
</fieldset>
<fieldset>
<legend>Check whether you like [My Fan Page] </legend>
<div id="lblYouLike"></div>
</fieldset>
<fieldset>
<legend>Check whether you are a fan of [My Fan Page]</legend>
<div id="lblMem"></div>
</fieldset>
<div id="divLogin" style="display:none;">
<div class="fb-login-button">Login with [App]</div>
</div>
<script>
var accessToken;
var uid;
var lblName = document.getElementById("lblName")
var divLogin = document.getElementById("divLogin")
var lblAccessToken = document.getElementById("lblAccessToken")
var lblLikes = document.getElementById("lblLikes")
var lblYouLike = document.getElementById("lblYouLike")
var lblMem = document.getElementById("lblMem")
window.fbAsyncInit = function () {
FB.init({
appId: 'APP_ID', // App ID
channelUrl : 'http://www.example.com/testing/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
});
FB.getLoginStatus(
function (response) {
checkStatus(response)
}
);
FB.Event.subscribe(
'auth.authResponseChange',
function (response) {
checkStatus(response)
}
);
FB.Event.subscribe(
'edge.create',
function (response) {
//alert('You liked the URL: ' + response);
ufCheckLike()
}
);
};
// Load the SDK Asynchronously
(
function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document)
);
function checkStatus(response){
if (response.status === 'connected') {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
lblAccessToken.innerHTML = accessToken;
FB.api(
'/me',
'get',
function(response) {
lblName.innerHTML = response.name;
}
);
divLogin.style.display = "none";
ufCheckLike()
}
else {
divLogin.style.display = "";
}
}
function ufCheckLike() {
if (isLoggedIn()) {
FB.api(
'/me/likes?' +
'access_token=' + accessToken,
'get',
function(likes) {
if (likes) {
if (likes.data && likes.data.length > 0) {
for (var i = 0; i < likes.data.length; i++) {
var like_detail = likes.data[i]
var lsHTML = like_detail.name + " : " + like_detail.id + "<br>"
if(like_detail.id == "<PAGE_ID>")
lblLikes.innerHTML = lsHTML + lblLikes.innerHTML
else
lblLikes.innerHTML += lsHTML
}
}
}
}
);
FB.api(
'/me/likes/<PAGE_ID>?' +
'access_token=' + accessToken,
'get',
function(likes) {
if (likes) {
if (likes.data && likes.data.length > 0) {
lblYouLike.innerHTML = "You Like [Fan Page]!"
}
}
}
);
FB.api(
'/<PAGE_ID>/members/' + uid + '?' +
'access_token=' + accessToken,
'get',
function(likes) {
if (likes) {
if (likes.data && likes.data.length > 0) {
lblMem.innerHTML = "You are a fan of [Fan Page]!"
}
}
}
);
}
}
function isLoggedIn() {
if (!accessToken) {
divLogin.style.display = "";
return false;
}
return true;
}
</script>
</body>
</html>
I also implemented an FQL which practically does the same thing to check whether a user has liked my page and the same scenario is happening on certain users where data object returns empty rows.
var query = "SELECT uid FROM page_fan where uid=me() and page_id = PAGE_ID ' + 'and access_token = " + accessToken;
//Access token is optional
var names = FB.Data.query(query);
names.wait(
function (rows) {
if (rows.length > 0) {
// liked, do codes here
}
else {
// not yet liked, show like button
}
}
);
I have applied some of the suggestions found here and the script still doesn't work for some users. I am out of clue what particular account/privacy/app setting should be modified to allow querying of the user's page likes, apart from setting the 'user_likes' in the App's user and friend permissions settings.
You've given no indication how often this is happening so i'm assuming
It's rare
You're only ever asking about the current user, not their friends.
If so, some users don't actually have any likes, so this can easily happen and shouldn't be a problem.
If you can verify the user DOES have likes, and has authorised your app with user_likes permission, file a bug in Facebook's bug tracker and include the user IDs, page IDs, access tokens etc
This can be related to this reproducable bug:
http://developers.facebook.com/bugs/106991419491608
Read my post there for more info.
I posted a detailed solution to a similar issue I faced with the JS api in this post:
Why is the Facebook API returning an empty array for albums?
if(jQuery.type(response.data[i].location) == 'object' )

Detect if a user liked my fanpage

EDIT:
Finally after a long search, I found a solution to this:
heres my code:
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<fb:like href="http://developers.facebook.com" send="true" width="450" show_faces="true"></fb:like>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
FB.Event.subscribe('edge.create', function(href, widget) {
//alert('like '+href);
document.getElementById('download').style.visibility = 'visible';
});
FB.Event.subscribe('edge.remove', function(href, widget) {
//alert('dislike '+href);
document.getElementById('download').style.visibility = 'hidden';
});
</script>
<div id="download">Download</div>
</body>
</html>
This works as I wanted, but on page load by default the Download is shown, how do I detect on page load whether the user liked my page or not?
OLD QUESTION
I am having a website where I have some files for users for download, and have a like button next to it. I just want that download button to be visible only if the current user liked my page.
I am new to FB open graph and JS SDK, I tried following code(pasted in my website) :
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
// the user is logged in to Facebook,
// but has not authenticated your app or
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
});
};
(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));
Even though I am logged in FB and using same browser, it always returns me with following error(firebug debug log)
code:2500
message : "An active access token must be used to query information about the current user."
I dont know much about FB API, am I doing something wrong?
Here's an edit of your code that should work:
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
// the user is logged in to Facebook,
// but has not authenticated your app or
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
});
};
(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));
To explain a bit, what I added was a function which checks whether a user has authorized your app yet (FB.getLoginStatus) and within the success handler of that function, I've added your API call. Within the else of this function, I've added a call to FB.login which will prompt un-authorized users to auth your app. If they successfully do this, your API call is made, if they chose not to, I've just left in the example console.log call, but you could replace that with anything you wanted.
Now, in order to track whether a user has liked your page or not, you need to make use of the FB.Event.subscribe function by tracking the 'edge.create' event.