1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }

    /**
     * 产生随机字符串,不长于32位
     * @param int $length
     * @return string
     */
    public static function createNonceStr(int $length = 32): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 产生请求参数的排序后的字符串
     * @param array $requestParamArr
     * @return string
     */
    public static function createSortQueryString(array $requestParamArr): string
    {
        if (isset($requestParamArr['key'])) unset($requestParamArr['key']);
        if (isset($requestParamArr['signature'])) unset($requestParamArr['signature']);

        ksort($requestParamArr);
        return http_build_query($requestParamArr);
    }

    /**
     * 创建签名串
     * @param string $sortQueryString 排序字符串
     * @param string $signType 签名类型:MD5;HMAC-SHA256;
     * @param string $key
     * @return string
     * @throws \Exception
     */
    public static function createSignatureString(string $sortQueryString, string $signType, string $key): string
    {
        $returnStr = '';
        if ($signType == 'MD5') {
            $sortQueryString .= '&key=' . $key;
            $returnStr = md5($sortQueryString);
        } elseif ($signType == 'HMAC-SHA256') {
            $returnStr = hash_hmac('sha256', $sortQueryString, $key);
        } else {
            throw new \Exception('签名类型不支持');
        }
        return $returnStr;
    }

    /**
     * 验证外部请求
     * @param array $originRequestParamArr
     * @return array
     */
    public static function validateRequest(array $originRequestParamArr): array
    {
        try {
            $validate = self::validateQueryParam($originRequestParamArr, false);
            if (!$validate['status']) throw new \Exception($validate['message']);
            $now = time();
            if (($now - $originRequestParamArr['timestamp']) > 15) throw new \Exception('请求时间异常');

            $signType = $originRequestParamArr['sign_type'];
            $originKey = $originRequestParamArr['key'];
            $originSignature = $originRequestParamArr['signature'];
            unset($originRequestParamArr['key'], $originRequestParamArr['signature']);

            $newSignature = self::createSignatureString(self::createSortQueryString($originRequestParamArr), $signType, $originKey);
            if ($originSignature != $newSignature) throw new \Exception('签名错误');

            return ['status' => 1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }
}

使用

//生成签名
$request = [
                'a' => 1,
                'b' => 2,
                'c' => 3,

                'sign_type' => 'HMAC-SHA256',
                'timestamp' => time() + 600,
                'nonce_str' => SignatureService::createNonceStr(),
        ];

            SignatureService::init($request);

            $result = SignatureService::validateQueryParam();

            if (!$result['status']) exit($result['message']);

            $key = 'helloworld';
            $signature = SignatureService::createSignatureString(SignatureService::createSortQueryString($request), $request['sign_type'], $key);
            $request['key'] = $key;
            $request['signature'] = $signature;

            echo "
";
            print_r($request);

            //校验签名
            $validate = SignatureService::validateRequest($request, false);

必要参数:

  • 'sign_type' => 'HMAC-SHA256', //签名类型,当前支持SHA256、MD5
  • 'timestamp' => '1539255134', //时间戳
  • 'nonce_str' => 'n5ryqp0f9ur3u3u8lxfblxw9h03emyka',//随机数
  • 'key' => 'helloworld', //密钥
  • 'signature' => 'f0ca487612f15059c47aba5e8503c6400981fbed20d1af958003e3f798d1bbd2',//签名