In my website, when the visitor visit my web, if they have not liked my facebook page yet, i want to show Iframe like box.
I have seen many code in the web as well as in stackoverflow, but it seem doesn't work well. Here is my javascript code:
$(document).ready(function(){
FB.init({
appId : 'IDAPP',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "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) {
alert(rows);
if (rows.length == 1 && rows[0].uid == user_id) {
alert("like");
} else {
alert("not like");
}
});
} else if (response.status === 'not_authorized') {
alert("not authorized");
} else {
alert("not login");
}
});
});
Request with login or not login or not_authorize it work well, but when check for page is like or note, it doesn't run anything.
FQL is deprecated, and you would need to authorize a user with the user_likes permission - after that, it´s just a call to the /me/likes endpoint. You will not get that permission approved for like gating, because that´s not allowed. And you will not get it approved for "please like my page" overlays/iframes either :) - because the user does not benefit from that overlay in any way, it is only annoying.
There is only one possible way:
Subscribe to the like event: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
In the event callback, store a cookie so next time the user visits your page you don´t show the overlay/iframe anymore
Problem is, you don´t get the information if the liked or unliked something. And the user could just clear his cookies, so you can never be sure. My advice: don´t annoy your users with it.
Related
I need to fire my server side code after calling the FB.logout from Facebook JS sdk. Here's how my html looks
<asp:LinkButton ID="lbtnSignOut" runat="server" Text="Sign Out" OnClientClick="return Logout();" OnClick="lbtnSignOut_Click"></asp:LinkButton>
and the js code
function Logout() {
var currentToken = "<%= Session["AccessToken"]%>";
if (currentToken != null && currentToken != '') {
FB.logout(function (response) {
});
}
return true;
}
and subsequently in the server side code, i clear out all application specific session and signs the user out using FormsAuthentication sign out call and redirect to different page.
Now the problem is, the moment I return true from the js function, the server side code fires without waiting for fb.logout to complete the call and the user token does not expire and user is automatically logged back in the FB.Event.subscribe('auth.authResponseChange', function (response) {}; call in the page load which i have picked from standard code.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
//SUCCESS
//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 currentToken = "<%= Session["AccessToken"] %>";
if (currentToken == null || currentToken == '') {
// Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var accessToken = response.authResponse.accessToken;
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/facebookLogin.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'AccessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
}
}
else if (response.status === 'not_authorized') {
//FAILED
console.log('User cancelled login or did not fully authorize.');
}
else {
//UNKNOWN ERROR
console.log('Logged Out.');
}
});
};
while if i set the value to false, user is logged out from facebook but my custom code does not fire.
So my question is how to call the server side code after the facebook js sdk logout code has fired?
Any help or pointers will be much appreciated!!!
Paritosh
Put the return true inside the function(response){} block, so that is only called when the FB.logout call returns
How does the plugin communicate with the facebook server without exposing too much information.
I would like to know how I can build myself a plugin that would communicate between the website it's installed on and my website.
My knowledge is limited to HTML5, CSS3, PHP5, Javascript and some Jquery.
I realise that there could be alot of ways, I was just wandering if you could point me in the right direction, or give me an idea. (: thanks in advance!
Take a look at the easyXDM framework, which allows you to do this quite easily, and if you have a chance, read Third Party JavaScript, which explains what you want to do in detail.
Some years ago, I wrote about this topic on scriptjunkie, it's as relevant now as then (although more browsers support postMessage now).
Create an application on developers.facebook.com
Download the facebook SDK for PHP since this is what you know (https://developers.facebook.com/docs/reference/php)
Read their guideline on how to implement login (it is easy and helpful)
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
This is a sample PHP function that you can build on:
function facebook_login()
{
$user = new user();
// Call Facebook API
if (!class_exists('FacebookApiException')) {
require_once ('facebook.php');
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/me'); //user
$uid = $facebook->getUser();
}
catch(FacebookApiException $e) {
echo error_log($e);
return;
}
}
// redirect user to facebook login page if empty data or fresh login requires
if (!$fbuser) {
$loginUrl = $facebook - getLoginUrl(array(
'redirect_uri' => $_SERVER["HTTP_REFERER"],
false
));
$logout = $facebook->getLoginUrl();
echo $loginUrl;
return;
}
// user details
$user->name = $me['name'];
$user->email = $me['email'];
$user->fbid = $uid;
// Check user id in your database
$user->selectbyfbid();
if ($user->database->rows > 0) {
// User exist, Show welcome back message
// User is now connected, log him in
}
else {
// User is new, Show connected message and store info in our Database
// Insert user into Database.
$user->insert_fb();
}
$_SESSION["access_token"] = $facebook->getAccessToken();
login_user($user);
}
In your HTML:
<a href="#" onclick="LoadingAnimate();">
<div class="fb-login-button"
onlogin="javascript:CallAfterLogin();"
data-width="600" data-max-rows="1"
data-show-faces="false"
scope="publish_stream,email,publish_actions,offline_access">
JavaScript code:
function CallAfterLogin(){
FB.login(function(response) {
if (response.status === "connected")
{
LoadingAnimate(); //show a waiting gif or whatever
FB.api('/me', function(data) {
if(data.email == null)
{
//Facbeook user email is empty, you can check something like this.
ResetAnimate();
}else{
AjaxResponse();
}
});
}
});
}
function AjaxResponse()
{
var myData = 'connect=1&action=fb_login';
jQuery.ajax({
type: "POST",
url: "/process_user.php",
dataType:"html",
data:myData,
cache: false,
success:function(response){
if(target.length > 1)
window.location.href = target;
else
location.reload();
},
error:function (xhr, ajaxOptions, thrownError){
//$("#results").html('<fieldset style="color:red;">'+thrownError+'</fieldset>'); //Error
}
});
}
I hope this helps you start!
I'm using Facebook Auth and I'm trying to add an automatic redirect from interior pages to the log in page if the user is not logged in or they haven't authorized my app, and that part works fine. The problem I'm having is that when you arrive on index.php, it redirects you to index.php again, and again, infinitely. I've tried numerous things, like if (location.href == "index.php") do nothing, else redirect, but nothing I try works.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
window.location = "index.php";
} else {
window.location = "index.php";
}
});
I have a javascript function that uses fb.login to retrieve the users info and checks to see if the user likes my fb page. fb.login causes a pop up where the user must click a login button. If the user likes my page i need to first create a cookie then redirect them to the main app:
function checkUser() {
var page_id = "my id goes here"; //
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + response.id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == response.id) {
//$("#container_like").show();/
//set cookie
document.cookie = "fbId=" + response.id;
window.location = "/kisses.aspx";
} else {
$("#likepageholder").show();
//$("#container_notlike").show();
//window.location = "/kisses.aspx";
//and here you could get the content for a non liker in ajax...
}
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
If there a way around using fb.login to do this?
Nope. Unfortunately, you need the user to log in (and grant your app basic permissions [based on the appId you use in FB.init) in order to query the user's likes.
That being said, it looks like your code should work.
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.