How to check if a user likes my Facebook Page or URL using Facebook's API
Asked Answered
K

5

103

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?!

Kaiserism answered 23/2, 2011 at 16:1 Comment(1)
possible duplicate of What's method for checking user fan of a page in GRAPH API?Earthshaker
F
100

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!";
    }
  }
Fuselage answered 24/2, 2011 at 4:16 Comment(16)
Aha, I've tried signed_request but I never got it to work so I went over to javascript which was, for some reason, easier and it worked. (but that was another project). Thanks!Kaiserism
Just curious, but how did you do it with JavaScript. I started there but ended up with this approach in php.Fuselage
I have tried the code. But it works only when i choose page type as fbml. If i choose iframe it does not work. Also if i choose fbml, i dnt get the page parameter, which tells whether the page is liked or not. I think i am missing something.Lupus
Warning: Read the Facebook Promotional Guidelines before trying to "abuse" this e.g. like page for competition entry. "#3 You must not use Facebook features or functionality as a promotion’s registration or entry mechanism. For example, the act of liking a Page or checking in to a Place cannot automatically register or enter a promotion participant." - facebook.com/promotions_guidelines.phpCalvados
developers.facebook.com/docs/authentication/signed_request complimentary documentation, if you're using PHP SDK is quite easy!Travertine
@Jason -- worked like a charm. I'd +10 if I could so you get a +1 for now :)Ethereal
I'm actually not getting the pages property from the object that's returned is this method no longer possible?Sheley
I haven't tried recently, but it's possible. As you know, Facebook likes to change their API every month or so. :)Fuselage
@Andrea, same here. this seemed to be working for me just a few days ago. i wonder if the new https lockdown has altered this functionality?Sapor
Just to add on to Jason Siffring's answer, when setting the "Page Tab URL" or "Canvas URL", you need to have a trailing slash. If there is not, Facebook will not send the signed request parameter.Cheri
@Chris - just wanted to clarify, you can condition entry on a liking the page first. The act of liking can't be the entry mechanism, but you can enforce liking before entering.Felafel
@Felafel - your clarification is correct. Facebook allow apps to "Like Gate" access to content. For example - this is ALLOWED: "Like Us to see the competition entry form". And this is NOT ALLOWED: "Like Us and you will be automatically entered into our competition".Calvados
You are not checking the validity of the signed_request. This is a dangerous approach. You should check it against your application secret. Check this answer for more informationEarthshaker
Works perfectly! Was banging my head on this one to. I almost thought I was going to ask each user permission to authorize my app before displaying any info's about liking the page and receiving content..Deal
This is defo the best answer. I wrote a blog post on this a while back including a PHP class which not only detects whether a page is liked without the user having to connect to the page/app it also allows retrieving queries from the app_data query string used by Facebook. Its very usefull for anyone wanting a base to write Facebook apps from. It can be found here if anyone is interested -> fryed.co.uk/blog/…Lunette
This code no longer works for new apps, beware: developers.facebook.com/docs/reference/login/signed-requestWillodeanwilloughby
T
19

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'];
}
Travertine answered 4/6, 2011 at 15:21 Comment(0)
P
17

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.

Puritanism answered 28/12, 2011 at 22:26 Comment(3)
javascript 2.7 sdk it is deprectedAttempt
Hi @DINJAS Thanks for your answer the above code is working fine for facebook. is there any link to instagram, twitter and linkdnKandace
@shivashankarm I honestly have no idea. I haven't had to do anything like this since I posted this answer.Puritanism
R
16

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' });
Rarefy answered 29/5, 2012 at 12:47 Comment(0)
B
3

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.

Bookkeeping answered 27/2, 2011 at 23:26 Comment(1)
this is the only way if they haven't connected with your applicationColenecoleopteran

© 2022 - 2024 — McMap. All rights reserved.