赞
踩
整理了自己在开发微信支付相关接口时,根据官方文档实现的签名算法供大家参考,欢迎提出改进优化建议!
- /**
- * Create the wechat pay sign with MD5
- * Document https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
- * @param $data
- * @param $mach_key
- * @return string
- */
- private function createWechatPaySignWithMd5 ($data, $mach_key) {
- ksort($data);
- $data = array_filter($data, function ($v, $k) {
- if ($k == "sign" && $v == '' && is_array($v)) {
- return false;
- }
- return true;
- }, ARRAY_FILTER_USE_BOTH);
- $str = http_build_query($data)."&key=".$mach_key;
- return strtoupper(md5($str));
- }
使用HMAC-SHA256与MD5的主要差别就在于编码这一步,其它步骤一致:
- /**
- * Create the wechat pay sign with hmac-sha256
- * Document https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
- * @param $data
- * @param $mach_key
- * @return string
- */
- private function createWechatPaySignWithHash ($data, $mach_key) {
- ksort($data);
- $data = array_filter($data, function ($v, $k) {
- if ($k == "sign" && $v == '' && is_array($v)) {
- return false;
- }
- return true;
- }, ARRAY_FILTER_USE_BOTH);
- $str = http_build_query($data)."&key=".$mach_key;
- return strtoupper(hash_hmac("sha256", $str, $mach_key));
- }
参考链接:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。