Skip to content

Instantly share code, notes, and snippets.

@mmhan
Created April 25, 2011 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmhan/940083 to your computer and use it in GitHub Desktop.
Save mmhan/940083 to your computer and use it in GitHub Desktop.
A useful class to retrieve SignedRequest from a Facebook App embedded as tab in a Facebook Page. Particularly useful in finding out visiting user's ID and whether the user like the page or not.
<?php
/*************************************
* Class with methods to decode a signed request easily, for App embedded as Tab on a profile page.
*
* @ModifiedBy Mike - @mmhan - mmhan.net
* @author Nathron
* @url http://nathrondevblog.blogspot.com/2010/09/how-to-get-user-id-in-profile-tab.html
*
* @usage:
* //In facebook tab page.
$aData = FbDecode::parse_signed_request($_REQUEST['signed_request'],YOUR_APP_SECRET);
echo '<pre>'; print_r($aData); echo '</pre>'; //contains page info, user's info and many other stuff
if($aData['page']['liked']) :
echo "You like this page"
else:
echo "You don't like this page."
endif;
**************************************/
class FbDecode{
public function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = FbDecode::base64_url_decode($encoded_sig);
$data = json_decode(FbDecode::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;
}
public function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment