SignHelper.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace common\components\delivery\helpers;
  3. class SignHelper
  4. {
  5. /**
  6. * 通用签名算法入口
  7. * @param array $params 待签名参数
  8. * @param string $secret 密钥
  9. * @param string $method 签名算法:md5 / hmac_sha256
  10. * @param bool $sort 是否需要按 key 排序
  11. */
  12. public static function makeSign(array $params, string $secret, string $method = 'md5', bool $sort = true)
  13. {
  14. if ($sort) {
  15. ksort($params);
  16. }
  17. // 拼接 query 字符串(过滤空值)
  18. $str = '';
  19. foreach ($params as $k => $v) {
  20. if ($v === '' || $v === null) continue;
  21. if (is_array($v)) $v = json_encode($v, JSON_UNESCAPED_UNICODE);
  22. $str .= "{$k}={$v}&";
  23. }
  24. $str = rtrim($str, '&');
  25. switch (strtolower($method)) {
  26. case 'hmac_sha256':
  27. $sign = hash_hmac('sha256', $str, $secret);
  28. break;
  29. case 'md5':
  30. default:
  31. $sign = md5($str . $secret);
  32. break;
  33. }
  34. return strtoupper($sign);
  35. }
  36. /**
  37. * 验证签名(用于第三方回调)
  38. */
  39. public static function verify(array $params, string $secret, string $signKey = 'sign', string $method = 'md5')
  40. {
  41. if (!isset($params[$signKey])) return false;
  42. $sign = $params[$signKey];
  43. unset($params[$signKey]);
  44. $expect = self::makeSign($params, $secret, $method);
  45. return strtoupper($sign) === strtoupper($expect);
  46. }
  47. }