Seamless way to check if user likes page
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.
How to check whether user has liked the page or not using php/javascript
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['signed_request'] = 'Unknown algorithm. Expected HMAC-SHA256';
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if($sig !== $expected_sig) {
$error['bad_signed_json'] = 'Bad Signed JSON signature!';
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
$signed_request_data = parse_signed_request($_REQUEST['signed_request'],$fb_app_secret);
if($signed_request_data['page']['liked']) {
print "Content for Useres who have liked your page...";
}
What's method for checking user fan of a page in GRAPH API?
UPDATE 2:
To check if the current user is a fan of the Facebook page on landing at your tab check this answer.
UPDATE:
You can use the likes
connection to check if a user is a fan of a page:
https://graph.facebook.com/me/likes/PAGE_ID
&access_token=ACCESS_TOKEN
This would return either an empty data array:
Array
(
[data] => Array
(
)
)
Or if fan:
Array
(
[data] => Array
(
[0] => Array
(
[name] => Real Madrid C.F.
[category] => Professional sports team
[id] => 19034719952
[created_time] => 2011-05-03T20:53:26+0000
)
)
)
So this is how we check using the PHP-SDK:
<?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();
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
?>
Similar script usingJS-SDK:
FB.api('/me/likes/PAGE_ID',function(response) {
if( response.data ) {
if( !isEmpty(response.data) )
alert('You are a fan!');
else
alert('Not a fan!');
} else {
alert('ERROR!');
}
});
// function to check for an empty object
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
Code taken from my tutorial.
While pages.isFan
is still working for me, you can use the FQL page_fan
table with the new PHP-SDK:
$result = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT uid FROM page_fan WHERE uid=$user_id AND page_id=$page_id"
));
if(!empty($result)) // array is not empty, so the user is a fan!
echo "$user_id is a fan!";
From the documentation:
To read the page_fan table you need:
- any valid
access_token
if it is public (visible to anyone on Facebook).user_likes
permissions if querying the current user.friends_likes
permissions if querying a user's friend.
How to implement Facebook app Like before use ?
FBML pages have been deprecated and you can now only create iframe fan pages. When the user navigates to your page, Facebook sends a signed_request parameter that you will need to decode. This article has a walkthrough on how to do it.
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!";
}
}
Related Topics
How to Send Emails via Cron Job Usng PHP MySQL
Get Youtube Video Id from HTML Code with PHP
How to Type Hint More Than One Type
The Advantage/Disadvantage Between Global Variables and Function Parameters in PHP
How to Run the PHP Code Asynchronous
What Does This Mean in Documentation: Square Bracket Followed by Comma ( [, )
Using Password_Hash and Password_Verify
Fix Malformed Xml in PHP Before Processing Using Domdocument Functions
Populate Another Select Dropdown from Database Based on Dropdown Selection
How to Create Codeigniter Batch Insert Array
Unexpected Character in Input: '\' (Ascii=92) State=1
Hiding True Database Object Id in Url'S