Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
USAGE:
$urlToSign = 'https://secure.vend-o.com/v/signup?site=123123&affiliate_id=0';//this is just an example
$vendoSigner = new VendoSignature('YOUR-SHARED-SECRET');
$signedUrl = $vendoSigner->sign($urlToSign);
//Output example: https://secure.vend-o.com/v/signup?site=123123&affiliate_id=0&signature=scKxBO5UlS1vQHxORr3xuBL4Fb8
*/
class VendoSignature
{
protected $_sharedSecret = null;
public function __construct($sharedSecret)
{
$this->_sharedSecret = $sharedSecret;
}
/**
* Signs the provided URL
*
* @param string $uri
* @return string
*/
public function sign($uri)
{
$u = null;
// If this is a full URL, take it apart
if (preg_match('/^https?:/', $uri)) {
$u = parse_url($uri);
$uri = $u['path'] . '?' . $u['query'];
}
$signature = $this->_hmacSha1($uri, $this->_sharedSecret);
$uri = $uri . '&signature=' . $signature;
if ($u) {
$uri = $u['scheme'] . '://' .
(isset($u['user']) ? $u['user'] . (isset($u['pass']) ? ':' . $u['pass'] : '') .
'@' : '') . $u['host'] . (isset($u['port']) ? ':' . $u['port'] :
'') . $uri;
}
return $uri;
}
/**
* Creates a HMAC-SHA1 signature of the request URI, signed with the shared
* secret and returns it as a base-64 encoded string with '=' characters
* removed.
*
* @param string $data
* @param string $key
* @return string
*/
protected function _hmacSha1($data, $key) {
if (strlen($key) > 64) {
$key = sha1($key, true);
} else {
$key = str_pad($key, 64, chr(0));
}
$ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
$opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));
$hash = sha1($opad . sha1($ipad . $data, true), true);
$hash = $this->_base64UrlEncode($hash);
return $hash;
}
/**
* Encodes the given data in a URL-compatible Base64 string. Compared to
* normal Base64, the URL version removes any = characters and replaces +
* with - and / with _.
*
* Based on description given in http://en.wikipedia.org/wiki/Base64
*
* @param string $data the data to encode
* @return string
*/
private function _base64UrlEncode($data) {
$data = base64_encode($data);
$data = str_replace('=', '', $data);
$data = str_replace('+', '-', $data);
$data = str_replace('/', '_', $data);
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment