Check if user liked my FB page on my external website - javascript

I know, that there are lot of questions with this error, but still I can't find solution for this error:
Given URL is not permitted by the application configuration.: One or
more of the given URLs is not allowed by the App's settings. It must
match the Website URL or Canvas URL, or the domain must be a subdomain
of one of the App's domains.
I'm working with this example:
$(document).ready(function() {
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "383152115092391"; //"383152115092391"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
FB.api('/me/likes/'+page_id, function(response) {
if (response.data[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
});
} else {
// user is not logged in
}
});
});
jsfiddle example
And this is my DB app configuration:
basic settings
advanced settings
Can you please tell me, what am I missing?

Related

get facebook user email and user first/last name with Phonegap FB Plugin for IOS app

Working on my first phonegap ios app.
Trying to incorporate this plugin https://github.com/Wizcorp/phonegap-facebook-plugin/tree/master/platforms/ios/www
Basically I just need to alert the users email and first/last name, although I'm a bit stuck on how to do so using this plugin.
What I wanted to do was retrieve that information, then pre populate some forms to create a new user to use with Parse.
I'm able to get a response from this function that displays a status and an authResponse with tokens and the user ID:
var login = function () {
if (!window.cordova) {
var appId = prompt("Enter FB Application ID", "");
facebookConnectPlugin.browserInit(appId);
}
facebookConnectPlugin.login( ["email"],
function (response) { alert(JSON.stringify(response)) },
function (response) { alert(JSON.stringify(response)) });
}
I'm just unsure in terms of next steps on how to go about retrieving the users email and first/lastname..and whther or not I have to dig deeper into facebooks API.
any help is appreciated.
* UPDATED *
Figured it out. I was missing a step that i found over at the facebook api page
var login = function() {
if (!window.cordova) {
facebookConnectPlugin.browserInit('APPID');
facebookConnectPlugin.browserInit(appId);
}
facebookConnectPlugin.login(["email"], function(response) {
if (response.authResponse) {
facebookConnectPlugin.api('/me', null,
function(response) {
alert('Good to see you, ' +
response.email + response.name + '.');
});
}
});
}
Try this plugin(http://plugins.cordova.io/#/package/com.ccsoft.plugin.cordovafacebook) this covers all of your needs.

Javascript not running on Facebook iframe

I have a django project which is intended for a facebook application. In the project, the invite friends module runs fine in localhost!
But while it is loaded in facebook application, the javascript responsible for displaying the friends list doesn't work. Although the libraries are properly loaded.
I don't know why it is so. May be some iframe problem.
Here is the javascript code
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '460948667348013', cookie: true});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', function(response) {
// alert('Your name is ' + response.name);
console.log('Your name is ' + response.name);
init();
});
} else if (response.status === 'not_authorized') {
alert('the user is logged in to Facebook, but has not authenticated your app');
} else {
alert('the user is not logged in to Facebook.');
}
});
}
function init() {
FB.api('/me', function(response) {
$("#username").html("<img src='https://graph.facebook.com/" + response.id + "/picture'/><div>" + response.name + "</div>");
$("#jfmfs-container").jfmfs({
max_selected: 15,
max_selected_message: "{0} of {1} selected",
friend_fields: "id,name,last_name",
pre_selected_friends: [1014025367],
exclude_friends: [1211122344, 610526078],
sorter: function(a, b) {
var x = a.last_name.toLowerCase();
var y = b.last_name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
});
$("#jfmfs-container").bind("jfmfs.friendload.finished", function() {
window.console && console.log("finished loading!");
});
$("#jfmfs-container").bind("jfmfs.selection.changed", function(e, data) {
window.console && console.log("changed", data);
});
$("#logged-out-status").hide();
$("#show-friends").show();
});
}
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
$("#selected-friends").html(friendSelector.getSelectedIds().join(', '));
});
function sendRequest() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(', ');
// Use FB.ui to send the Request(s)
FB.ui({method: 'apprequests',
to: sendUIDs,
title: 'My Great Invite',
message: 'Check out this Awesome App!',
}, callback);
}
function callback(response) {
// alert('callback called');
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendUIDs = friendSelector.getSelectedIds().join(',');
var uids = sendUIDs.split(',');
var query = '';
for(i=0;i<uids.length;i++){
if(i==0){
query = query + 'to[' + i + ']=' + uids[i];
}
else{
query = query + '&to[' + i + ']=' + uids[i];
}
}
console.log(query);
if(response){
// alert('successful');
window.location.assign("/?"+ query)
}
else{
alert('failure');
}
}
</script>
Please help ! I am stuck with this problem.
The issue may be SSL issues.
Facebook has made many changes in few months ago.
Also you need to keep update with Facebook developer blog.
So I am going to try to explain few things I suspected.
App on Facebook
Your Canvas Page should be https://apps.facebook.com/yourchoosenname
1a. Your Canvas URL should be https://yoursite.com/yourapplication/
Website
http://yoursite.com/
Page Tab
Your Secure Canvas should be https://yoursite.com/yourapplication/
Your Page Tab URL should be https://yoursite.com/yourapplication/
Your Secure Page Tab URL should be https://yoursite.com/yourapplication/
In this case you will need SSL Certificate for site so You can find reliable yet cheap digital certificate from Here .
This mandatory for any Application to work on facebook.
Hope this will help you and others

javascript detect if the user liked a page [duplicate]

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/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) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// 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));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

extended permission publish_actions

I'm trying to post an action on user's timeline. I have 2 users, developer and normal user(not registred in app) and i can post on developer page but can't normal user
here my code
FB.api('/me/MYNAMESPACE:MYACTION?BYOBJECT=' + link, 'post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += '\n\nSomething wrong \n\n' + response.error.message;
}
alert(msg);
}
else {
alert('Done! Please check your activity log');
}
});
"link" is encoded url
sendbox mode is off and permition "publish_actions" in extended permissions is checked
If the action isn't approved you cannot post as a regular user. Only developers can do this.
Submit your action for approval.

Facebook Javascript, How to detect if user is a fan of my facebook page? While on my site?

I have the following JS code.
The code's purpose is to first get the users facebook id, and then using FQL check that id against my page ID and make sure the user is a fan.
The problem I am running into is that the only time the code actually works is if i login with my own personal facebook profile. I think its because my profile and the FB.init appid are somehow linked?
Can someone take a look at this code and show me where I am going wrong?
My goal again is to use JS to first get the users id (thus their thumbnail image), and then cross reference that against my own facebook page to check and see if they are a fan. If they are a facebook fan, then I will probably give them a coupon or something.
Thanks in advance.
<script src="http://connect.facebook.net/en_US/all.js"></script>
//Connect to facebook with my app id..
FB.init({
appId:'135445813195028',
cookie:false,
status:true,
xfbml:true
});
//Check to see if user is actually CONNECTED???
FB.getLoginStatus(function(response) {
if (response.session) {
// USER IS CONNECTED
FB.api('/me', function(user) {
if (user != null) {
var image = document.getElementById('imagez');
image.src = 'http://graph.facebook.com/' + user.id + '/picture?type=large';
var name = document.getElementById('name');
name.innerHTML = user.name;
FBID = user.id;
console.log('Facebook ID:' + FBID);
//assemble an FQL query to see if the guy is a fan of our page...
myquery = 'SELECT uid FROM page_fan WHERE page_id = 126923080686340 AND uid = ' + FBID;
console.log('query = ' + myquery);
///Run FQL Query to see if user is a fan
FB.api({
method: 'fql.query',
query: myquery
}, function(resp) {
if (resp.length) {
var IsFan = true;
alert('You are A fan!')
console.log('Visitor is a fan');
//show coupon code...
} else {
alert('Signed into facebook, but Not a fan!');
var IsFan = false;
console.log('Visitor is not a fan');
//show like button...
//once like is clicked then refresh the page...
}
});
//END Run FQL Query to see if user is a fan
}
});
//Figure out if they are a fan...
} else {
// USER IS NOT CONNECTED
alert('NO USER session, user is not logged into facebook!!!');
}
});
The FB.getLoginStatus check to see if the user is connected to your application .. not to facebook.
But when the user is not connected to your application, the .status property can tell you the reason of the fail (if the user is not logged-in at all, or just to your app).
So the structure you should use is
FB.getLoginStatus(function(response) {
if(response.session) {
alert('connected to Application');
} else {
// no user session available, someone you dont know
if(response.status == "notConnected") {
// But user is logged into facebook
alert("Not connected to Application, but is logged in to Facebook");
} else {
// User is not logged into facebook
alert('Not logged in to facebook');
}
}
});
But you cannot access the ID of a user that has not authorized your Application.
Not through Javascript API.

Categories