CheckSign.php 2.2 KB

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