12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- namespace App\Http\Middleware;
- use App\Cache\UserCache;
- use App\Consts\ErrorConst;
- use App\Libs\Utils;
- use App\Models\Channel\Channel;
- use Closure;
- use App\Exceptions\ApiException;
- use Illuminate\Support\Facades\Log;
- class CheckSign
- {
- /**
- * @param $request
- * @param Closure $next
- * @return mixed
- * @throws ApiException
- */
- public function handle($request, Closure $next)
- {
- $params = $request->all();
- $token = $request->header('d-token', '');
- if (!$token) Utils::throwError(ErrorConst::NOT_LOGIN);
- $referer_url = '';
- if (isset($params['_url'])) {
- $referer_url = $params['_url'];
- unset($params['_url']);
- }
- // 先验签(非本地模式需要验签)
- if (env('CHECK_SIGN') && $params) {
- $param_sign = getProp($params, 'sign');
- $timestamp = getProp($params, 'timestamp');
- $check_params = [
- 'd-token' => $token,
- 'nonce_str' => getProp($params, 'nonce_str'),
- 'timestamp' => $timestamp,
- ];
- if (!getProp($params, 'nonce_str') || !$timestamp) {
- Log::info('验签失败, 请求参数不正确;传参: '.json_encode($params, 256));
- Utils::throwError('1002:数据异常,请求参数不正确');
- }
- if (time() - $timestamp > 300) {
- Log::info('验签失败, 签名5分钟内有效;传参: '.json_encode($params, 256));
- Utils::throwError('1002:数据异常,签名5分钟内有效');
- }
- foreach ($params as $k=>$v) {
- if (!$v) unset($params[$k]);
- }
- ksort($check_params);
- $str = strtoupper(http_build_query($check_params));
- $sign = md5($str.'&key='.env('SIGN_SALT'));
- if ($param_sign != $sign) {
- $params['_url'] = $referer_url;
- $params['sign'] = $param_sign;
- $params['check_sign'] = $sign;
- $params['check_str'] = $str.'&key='.env('SIGN_SALT');
- Log::info('验签失败, 签名不正确;传参: '.json_encode($params, 256));
- Utils::throwError('1002:数据异常,签名不正确');
- }
- }
- return $next($request);
- }
- }
|