CheckSign.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Cache\UserCache;
  4. use App\Consts\ErrorConst;
  5. use App\Libs\Utils;
  6. use App\Models\Channel\Channel;
  7. use Closure;
  8. use App\Exceptions\ApiException;
  9. use Illuminate\Support\Facades\Log;
  10. class CheckSign
  11. {
  12. /**
  13. * @param $request
  14. * @param Closure $next
  15. * @return mixed
  16. * @throws ApiException
  17. */
  18. public function handle($request, Closure $next)
  19. {
  20. $token = $request->header('d-token', '');
  21. $param_sign = $request->header('sign', '');
  22. $nonce = $request->header('nonce', '');
  23. $timestamp = $request->header('timestamp', '');
  24. if (!$token) Utils::throwError(ErrorConst::NOT_LOGIN);
  25. $referer_url = $request->input('_url', '');
  26. // 先验签(非本地模式需要验签)
  27. if (env('CHECK_SIGN')) {
  28. $check_params = [
  29. 'd-token' => $token,
  30. 'nonce' => $nonce,
  31. 'timestamp' => $timestamp,
  32. ];
  33. $params = $check_params;
  34. $params['_url'] = $referer_url;
  35. if (!$nonce || !$timestamp) {
  36. dLog('checkSign')->info('验签失败, 请求参数不正确;传参: '.json_encode($params, 256));
  37. Utils::throwError('1002:签名异常');
  38. }
  39. if (time() - $timestamp > 300) {
  40. dLog('checkSign')->info('验签失败, 签名5分钟内有效;传参: '.json_encode($params, 256));
  41. Utils::throwError('1002:签名异常');
  42. }
  43. ksort($check_params);
  44. $str = strtoupper(http_build_query($check_params));
  45. $sign = md5($str.'&key='.env('SIGN_SALT'));
  46. if ($param_sign != $sign) {
  47. $params['_url'] = $referer_url;
  48. $params['sign'] = $param_sign;
  49. $params['check_sign'] = $sign;
  50. $params['check_str'] = $str.'&key='.env('SIGN_SALT');
  51. dLog('checkSign')->info('验签失败, 签名不正确;传参: '.json_encode($params, 256));
  52. Utils::throwError('1002:签名异常');
  53. }
  54. }
  55. return $next($request);
  56. }
  57. }