Check if logged in user has liked my Facebook Page
Here are the steps to do so:
1) You need to use this step by step guide to connect user to your facebook page in order to fetch user basic information
https://developers.facebook.com/docs/facebook-login/getting-started-web/
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
}
2) After knowing that user is connected using facebook you need to issue the graph GET request to find out about this user that he liked your page or not
FB.api('/me/likes/YOUR_APP_ID', function(response) {
console.log(response.data);
}
3) And then run your business logic (whether to take user to download page or other page)
Code from the tutorial above is given below too
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//www.example.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
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
$("#btnFB").show();
FB.login();
} else {
$("#btnFB").show();
FB.login();
}
});
};
// 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 testAPI() {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
FB.api('/me/likes/PAGE_ID', function(response) {
console.log(response.data);
});
}
How to get PAGE_ID?
Goto http://developers.facebook.com/tools/explorer/?method=GET&path=me%2Flikes%2F
This worked for me! :)
Check if user already likes fanpage
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.
How to check if a user likes my Facebook Page or URL using Facebook's API
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!";
}
}
Facebook how to check if user has liked page and show content?
UPDATE 21/11/2012
@ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here
Hi So as promised here is my answer using only javascript :
The content of the BODY of the page :
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true,
cookie : true,
xfbml : true
});
</script>
<div id="container_notlike">
YOU DONT LIKE
</div>
<div id="container_like">
YOU LIKE
</div>
The CSS :
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
#container_notlike, #container_like {
display:none
}
And finally the javascript :
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
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) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
So what what does it do ?
First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid
with YOUR_USER_ID (from your rails app for example)
After that it makes a FQL query on the page_fan
table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.
Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/
It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...
Finally some related docs :
FQL page_fan table
FBJS FB.Data.query
Don't hesitate if you have any question ..
Cheers
UPDATE 2
As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).
For the document.ready, you could wrap your code in a function and use body onload="your_function"
or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.
And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block"
and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm
But jQuery is so easy :)
UPDATE
Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.
In your action controller :
decoded_request = Canvas.parse_signed_request(params[:signed_request])
And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)
decoded_request['page']['liked']
And here is the related Canvas Class (from fbgraph ruby library) :
class Canvas
class << self
def parse_signed_request(secret_id,request)
encoded_sig, payload = request.split('.', 2)
sig = ""
urldecode64(encoded_sig).each_byte { |b|
sig << "%02x" % b
}
data = JSON.parse(urldecode64(payload))
if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
raise "Bad signature algorithm: %s" % data['algorithm']
end
expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
if expected_sig != sig
raise "Bad signature"
end
data
end
private
def urldecode64(str)
encoded_str = str.gsub('-','+').gsub('_','/')
encoded_str += '=' while !(encoded_str.size % 4).zero?
Base64.decode64(encoded_str)
end
end
end
Related Topics
How to JSON_Encode PHP Array But the Keys Without Quotes
PHP - Find If an Array Contains an Element
Key of Null Variable Equals Null Not Error
PHP File_Get_Contents() Behaves Differently to Browser
How to Use Facebook Graph API to Retrieve Fan Photos Uploaded to Wall of Fan Page
PHP String Comparasion to 0 Integer Returns True
Get Values Stdclass Object PHP
Woocommerce New Order Action - Get Order Information
Upload Images Through PHP Using Unique File Names
PHP Associative Array Key Order (Not Sort)
Hightest Value of an Associative Array
How to Safely Store a Password Inside PHP Code
JavaScript String Length Differs from PHP Mb_Strlen
How to Access the Google Spreadsheets API in PHP
Set Value of Single Object in Multidimensional Array in Twig Template