Check if user already likes fanpage
Asked Answered
G

5

9

Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?

EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first

Gothart answered 26/7, 2011 at 13:10 Comment(0)
R
12

The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.

Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:

$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
    if( $page['id'] === $our_page_id ) {
        $user_is_fan = true;
        break;
    }
}

Now, you can further work with the $user_is_fan variable.

In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api (again, assuming you have taken of the authentication):

FB.api('/me/likes?fields=id', function(response) {
    var our_page_id = '22476490672';
    var user_is_fan = false;
    var likes_count = response.data.length;
    for(i = 0; i < likes_count; i++) {
        if(response.data[i].id === our_page_id) {
            user_is_fan = true;
            break;
        }
    }
});

Note that here we're using an asynchronous request and callback, so the code using the user_is_fan variable must be inside the function.

Retrieval answered 26/7, 2011 at 15:57 Comment(5)
Do the user need to allow some permissions for this can work?Gothart
Yes, the user needs to log in with the user_likes permission.Vice
Do you know if it's possible to check if the user is fan without any permissions allowed by the user? So i don't need to show the permissions box to the user (I need to use this, so i can show a text like "You need to be fan" if the user isn't fan of our facebook fanpage. Hope you / someone can help me finding a smart solution :-)Gothart
I'm afraid that's impossible without the user's ID.Vice
If i have the users ID? Because i can get the users id, but i don't know how to check if the user is a fan of the fanpageGothart
S
13
<?php
require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId' => 'APP_ID',
  'secret' => 'APP_SECRET',
));

$user = $facebook->getUser();
$page_id = "123456789";
$page_name = $facebook->api("/".$page_id)['name'];
$page_link = $facebook->api("/".$page_id)['link'];



if ($user) {
  try {
    $likes = $facebook->api("/me/likes/".$page_id);
    if( !empty($likes['data']) )
        echo "I like!";
    else
        echo "not a fan!";
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array(
    'scope' => 'user_likes'
  ));
}

// rest of code here
?>
Screen answered 8/10, 2012 at 0:38 Comment(2)
this answer is far better because there is no for loop, and if user didn't accept user_likes permission, it tries again.Rosenkranz
I have to do a $likes = $response->getDecodedBody(); firstSheltonshelty
R
12

The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.

Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:

$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
    if( $page['id'] === $our_page_id ) {
        $user_is_fan = true;
        break;
    }
}

Now, you can further work with the $user_is_fan variable.

In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api (again, assuming you have taken of the authentication):

FB.api('/me/likes?fields=id', function(response) {
    var our_page_id = '22476490672';
    var user_is_fan = false;
    var likes_count = response.data.length;
    for(i = 0; i < likes_count; i++) {
        if(response.data[i].id === our_page_id) {
            user_is_fan = true;
            break;
        }
    }
});

Note that here we're using an asynchronous request and callback, so the code using the user_is_fan variable must be inside the function.

Retrieval answered 26/7, 2011 at 15:57 Comment(5)
Do the user need to allow some permissions for this can work?Gothart
Yes, the user needs to log in with the user_likes permission.Vice
Do you know if it's possible to check if the user is fan without any permissions allowed by the user? So i don't need to show the permissions box to the user (I need to use this, so i can show a text like "You need to be fan" if the user isn't fan of our facebook fanpage. Hope you / someone can help me finding a smart solution :-)Gothart
I'm afraid that's impossible without the user's ID.Vice
If i have the users ID? Because i can get the users id, but i don't know how to check if the user is a fan of the fanpageGothart
E
2

In case you are OK with user giving the permissions, for a PHP based website it can be done this way easily:

1- Create a new Facebook app here.

2 - Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given below!

3 - Get your Facebook Page ID using this tool.

4 - Generate Facebook like box code for your page from here.

After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:

<?php
    require('facebook.php');
    $config = array(
         'appId' => 'your facebook app id',
         'secret' => 'your facebook app secret code',

        'allowSignedRequest' => false
    );
    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();
    if (isset($user_id)) {
        try {           
            $likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');             

            if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
            {
                echo 'Thank you for liking our fan page!';                   

            }
            else {
                echo 'You have not liked our fan page! Like it now:';
                ?>                   
                <iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fchillopedia&amp;width&amp;height=290&amp;colorscheme=light&amp;show_faces=true&amp;header=true&amp;stream=false&amp;show_border=true&amp;appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowTransparency="true"></iframe> //replace this with your own Facebook like box code
                <?php
            }
        } catch (FacebookApiException $e) {
            $login_url = $facebook->getLoginUrl();
            echo '<a href="' . $login_url . '">Please click here to login into your Facebook account.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
        }
    } else {
        $login_url = $facebook->getLoginUrl();
        echo '<a href="' . $login_url . '">Please lick here to login into your Facebook account</a>';
    }
    ?>

The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display the likebox if user hasn't liked your fan page.

Ectoplasm answered 24/3, 2014 at 11:28 Comment(0)
G
0
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID_WITHIN_QUOTES', //Change this to your app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>



$signed_request = $_REQUEST["signed_request"];

list($encoded_sig, $payload) = explode('.', $signed_request, 2);

$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$has_liked = $data["page"]["liked"];

now check the $has_liked param to see if user likes ur page or not!

Gratia answered 26/7, 2011 at 13:17 Comment(6)
Is this inside an app on facebook or directly from a website?Gothart
it is on a website which is not part of facebook ;)Canterbury
I get this error: Undefined index: signed_request And if i print out $_REQUEST, signet_request doesn't exist in the array list :-(Gothart
signed_request is present on apps loaded on Facebook.com in iframes on page tabs or on apps.facebook.com/appnameCarsoncarstensz
this is inside an app embedded on page... it does not require any permission.Gratia
Allright, but signet_request doesn't exist / I can get the request. Do you know why?Gothart
Q
0

seems like "/me/likes/[page_id]" doesn't always return the record even there is one. recently I request by "/me/likes/[page_id]", it will return 0, but if I request without page_id, but grab a bunch of record by "/me/likes/", and you will see the page_id is actually there, can't figure why.

when checking with graph.facebook.com/[page_id], only suspicious thing is its "can_post" is false, and others which "/me/likes/[page_id]" do works, is true.

but looping is not good in this situation, especially some crazy people has millions of likes. is there any kinda privacy setting related to the page_id owner account would cause the problem?

Quixotism answered 5/6, 2013 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.