Skip to content

Instantly share code, notes, and snippets.

@OndraM
Created March 27, 2013 00:20
Show Gist options
  • Save OndraM/5250537 to your computer and use it in GitHub Desktop.
Save OndraM/5250537 to your computer and use it in GitHub Desktop.
Parse signed data from Facebook in Zend Framework Action Helper (original spaghetti source: https://developers.facebook.com/docs/plugins/registration/)
<?php
class O_Controller_Action_Helper_FacebookRequestParse extends Zend_Controller_Action_Helper_Abstract
{
/**
* Parse and check Facebook signed request and return given data.
*
* Source: https://developers.facebook.com/docs/plugins/registration/
*
* @param string $signedRequest Signed request body given from FB, e.g. $this->getRequest()->getPost('signed_request') or $_REQUEST['signed_request']
* @param type $appSecret Your APP secret key
* @return array Data send in Facebook request - checked against siganture, so they can be trusted.
* @throws Zend_Controller_Action_Exception
*/
public function direct($signedRequest, $appSecret) {
list($encodedSignature, $payload) = explode('.', $signedRequest, 2);
// decode the data
$signature = $this->_base64UrlDecode($encodedSignature);
$data = json_decode($this->_base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
throw new Zend_Controller_Action_Exception('Unknown algorithm. Expected HMAC-SHA256');
}
// check signature
$expectedSignature = hash_hmac('sha256', $payload, $appSecret, $raw = true);
if ($signature !== $expectedSignature) {
throw new Zend_Controller_Action_Exception('Bad Signed JSON signature!');
}
return $data;
}
protected function _base64UrlDecode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment