CheckSign.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. $params = $request->all();
  21. $token = $request->header('d-token', '');
  22. if (!$token) Utils::throwError(ErrorConst::NOT_LOGIN);
  23. $referer_url = '';
  24. if (isset($params['_url'])) {
  25. $referer_url = $params['_url'];
  26. unset($params['_url']);
  27. }
  28. // 先验签(非本地模式需要验签)
  29. if (env('CHECK_SIGN') && $params) {
  30. $param_sign = getProp($params, 'sign');
  31. $timestamp = getProp($params, 'timestamp');
  32. $check_params = [
  33. 'd-token' => $token,
  34. 'nonce_str' => getProp($params, 'nonce_str'),
  35. 'timestamp' => $timestamp,
  36. ];
  37. if (!getProp($params, 'nonce_str') || !$timestamp) {
  38. Log::info('验签失败, 请求参数不正确;传参: '.json_encode($params, 256));
  39. Utils::throwError('1002:数据异常,请求参数不正确');
  40. }
  41. if (time() - $timestamp > 300) {
  42. Log::info('验签失败, 签名5分钟内有效;传参: '.json_encode($params, 256));
  43. Utils::throwError('1002:数据异常,签名5分钟内有效');
  44. }
  45. foreach ($params as $k=>$v) {
  46. if (!$v) unset($params[$k]);
  47. }
  48. ksort($check_params);
  49. $str = strtoupper(http_build_query($check_params));
  50. $sign = md5($str.'&key='.env('SIGN_SALT'));
  51. if ($param_sign != $sign) {
  52. $params['_url'] = $referer_url;
  53. $params['sign'] = $param_sign;
  54. $params['check_sign'] = $sign;
  55. $params['check_str'] = $str.'&key='.env('SIGN_SALT');
  56. Log::info('验签失败, 签名不正确;传参: '.json_encode($params, 256));
  57. Utils::throwError('1002:数据异常,签名不正确');
  58. }
  59. }
  60. return $next($request);
  61. }
  62. }