| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <?php
- namespace common\components\delivery\helpers;
- class SignHelper
- {
- /**
- * 通用签名算法入口
- * @param array $params 待签名参数
- * @param string $secret 密钥
- * @param string $method 签名算法:md5 / hmac_sha256
- * @param bool $sort 是否需要按 key 排序
- */
- public static function makeSign(array $params, string $secret, string $method = 'md5', bool $sort = true)
- {
- if ($sort) {
- ksort($params);
- }
- // 拼接 query 字符串(过滤空值)
- $str = '';
- foreach ($params as $k => $v) {
- if ($v === '' || $v === null) continue;
- if (is_array($v)) $v = json_encode($v, JSON_UNESCAPED_UNICODE);
- $str .= "{$k}={$v}&";
- }
- $str = rtrim($str, '&');
- switch (strtolower($method)) {
- case 'hmac_sha256':
- $sign = hash_hmac('sha256', $str, $secret);
- break;
- case 'md5':
- default:
- $sign = md5($str . $secret);
- break;
- }
- return strtoupper($sign);
- }
- /**
- * 验证签名(用于第三方回调)
- */
- public static function verify(array $params, string $secret, string $signKey = 'sign', string $method = 'md5')
- {
- if (!isset($params[$signKey])) return false;
- $sign = $params[$signKey];
- unset($params[$signKey]);
- $expect = self::makeSign($params, $secret, $method);
- return strtoupper($sign) === strtoupper($expect);
- }
- }
|