Seamless way to check if user likes page
Solution 1:
Of course you can! As mentioned in the documentation, Facebook will send you some extra details in the signed_request
:
When a user navigates to the Facebook Page, they will see your Page Tab added in the next available tab position. Broadly, a Page Tab is loaded in exactly the same way as a Canvas Page. When a user selects your Page Tab, you will received the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.
The code taken from my tutorial should be something like:
<?php
if(empty($_REQUEST["signed_request"])) {
// no signed request where found which means
// 1- this page was not accessed through a Facebook page tab
// 2- a redirection was made, so the request is lost
echo "signed_request was not found!";
} else {
$app_secret = "APP_SECRET";
$data = parse_signed_request($_REQUEST["signed_request"], $app_secret);
if (empty($data["page"]["liked"])) {
echo "You are not a fan!";
} else {
echo "Welcome back fan!";
}
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
UPDATED CODE: While the previous code would work. I wasn't checking the validity of the request. This means someone could tamper the request and send you false information (like setting the admin
to true
!). Code has been updated, following the signed_request
documentation approach.