<?php
class SomeClass
{
CONST API_PUBLIC_KEY = "asdadasdaxxxx";
CONST URL = 'http://example.com/api/';
public function signature(array $param,
$timeOut = 60)
{
$param['expire'] = time() + $timeOut;
$param['sig'] = hash_hmac('sha256',
join('', $param), self::API_PUBLIC_KEY);
$this->param = $param;
return $this;
}
public function getRequestUrl()
{
return self::URL . '?' . http_build_query($this->param);
}
public function validateSignature($param, $sig)
{
return hash_hmac('sha256', join('', $param), self::API_PUBLIC_KEY)
== $sig;
}
}
$obj = new SomeClass();
$param = array('useranme' => 'zhangsan');
echo $obj->signature($param, 300)->getRequestUrl();
$sig = isset($_GET['sig']) ? $_GET['sig'] : '';
$expire = isset($_GET['expire']) ? $_GET['expire'] : '';
if(!$obj->validateSignature($param, $sig)){
echo "签名验证错误";
exit;
}
if($expire < time()) {
echo "请求超时";
exit;
}
echo "processing";
?>