后端代码
以下代码放在接口公共文件中
$apiAuth = new ApiAuth();
$signResult = $apiAuth->verifySign();
if (!$signResult['code']) {
$this->error($signResult['msg']);
}
ApiAuth类文件
<?php
class ApiAuth
{
public function __construct(){
$this->params = input();
$this->header = $this->app->request->header();
$this->appid = 'sdasdsfafjidfjfjbdfbxbfuixbfiudsbf';
$this->appsecret = 'ibnuigyugyuvdaskbhjbhbdhasdjhs';
}
public function verifySign()
{
$params = $this->params;
$header = $this->header;
if(!isset($header['api-sign']) && !$header['api-sign']){
return ['code' => 0, 'msg' => '签名不存在'];
}
if(!isset($params['timestamp']) || empty($params['timestamp'])){
return ['code' => 0, 'msg' => '缺少必填参数'];
}
$expiration = 600;
if(time() - $params['timestamp'] > $expiration){
return ['code' => 0, 'msg' => '验证超时,请重新发送请求'];
}
$oldSign = $header['api-sign'];
$newSign = $this->makesign();
if($newSign == $oldSign){
return ['code' => 1, 'msg' => ''];
}else{
return ['code' => 0, 'msg' => '请求不合法'];
}
}
protected function makesign()
{
$params = $this->params;
$sign = MD5(sha1($this->appid . $this->appsecret) . MD5($params['timestamp']) . sha1($this->appsecret . $this->appid));
return $sign;
}
}
请求接口方(前端/小程序/第三方)
请求头部header必须带参数
header:{
'api-sign' => $this->sign,
}
$this->sign 计算方式按生成验签的规则一样,由接口方提供
$this->sign = MD5(sha1($this->appid . $this->appsecret) . MD5($params['timestamp']) . sha1($this->appsecret . $this->appid));
appid和appsecret也是由接口方提供
每个接口请求都必须带上timestamp 时间戳参数
|