shop-php/app/common/middleware/SignMiddleware.php

84 lines
2.6 KiB
PHP
Raw Normal View History

2023-12-04 14:59:19 +08:00
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\common\middleware;
use app\Request;
use crmeb\exceptions\AuthException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
class SignMiddleware extends BaseMiddleware
{
/**
* @param Request $request
* @throws Throwable
* @author xaboy
* @day 2020-04-10
*/
public function before(Request $request)
{
try {
$appid = $request->header('appid');
$timestamp = $request->header('timestamp');
$sign = $request->header('sign');
// 中台系统secret
$appSecret = 'St@tF!8r@fgjCu88fJB9eo4PTRHxsntC';
$this->verifySign(['appid'=>$appid,'timestamp'=>$timestamp,'sign'=>$sign], $appSecret);
} catch (AuthException $e) {
$eArray = ($e->getResponse())->getData();
throw new AuthException($eArray['message'] ?? '非法签名');
return;
} catch (Throwable $e) {
throw new AuthException('非法请求');
return;
}
}
public function after(Response $response)
{
}
private function makeSign($data, $appSecret)
{
ksort($data);
$string = "";
foreach ($data as $k => $v) {
if ($k == "sign" || is_array($v)) {
continue;
}
$string .= $k . "=" . $v . "&";
}
$string = trim($string, "&");
$string = $string . "&key=" . $appSecret;
$string = md5(md5($string));
return strtolower($string);
}
private function verifySign($data, $appSecret)
{
// 验证请求, 10秒钟失效
if (time() - ($data['timestamp'] ?? 0) > 10) {
throw new AuthException('签名已失效');
}
// 比对签名
$clientSign = $data['sign'] ?? '';
$serverSign = $this->makeSign($data, $appSecret);
if ($clientSign != $serverSign) {
throw new AuthException('签名校验失败');
}
}
}