微信小程序开发之微信支付(四)组合签名(时间戳,随机串) 用户确认支付

我使用了这个SDK进行开发
签名算法需要5个参数
微信小程序开发之微信支付(四)组合签名(时间戳,随机串) 用户确认支付
文章图片


时间戳算法:

/** * 获取时间戳 * 时间戳从1970年1月1日00:00:00至今的秒数 */ public static long getTimeStamp() { Date d = new Date(); long timeStamp = d.getTime() / 1000; //getTime()得到的是微秒, 需要换算成秒 return timeStamp; }


随机串算法:
/** * 获取32位随机串 */ public static String getNonceStr() { String s = UUID.randomUUID().toString().replace("-",""); return s; }


签名算法:
com.github.binarywang.wxpay.util
/** * 微信支付签名算法(详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3). * * @param params参数信息 * @param signType签名类型,如果为空,则默认为MD5 * @param signKey签名Key * @param ignoreSignType 签名时,是否忽略signType * @return 签名字符串 */ public static String createSign(Map params, String signType, String signKey, boolean ignoreSignType) { SortedMap sortedMap = new TreeMap<>(params); StringBuilder toSign = new StringBuilder(); for (String key : sortedMap.keySet()) { String value = https://www.it610.com/article/params.get(key); boolean shouldSign = false; if (ignoreSignType &&"sign_type".equals(key)) { shouldSign = false; } else if (StringUtils.isNotEmpty(value) && !Lists.newArrayList("sign", "key", "xmlString", "xmlDoc", "couponList").contains(key)) { shouldSign = true; }if (shouldSign) { toSign.append(key).append("=").append(value).append("&"); } }toSign.append("key=").append(signKey); if (SignType.HMAC_SHA256.equals(signType)) { return createHmacSha256Sign(toSign.toString(), signKey); } else { return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); } }


前端需要wx.requestPayment{}发起支付。
怎样自动填写参数呢?
我们使用freemarker进行参数的动态注入
在依赖文件中添加
org.springframework.boot spring-boot-starter-freemarker

【微信小程序开发之微信支付(四)组合签名(时间戳,随机串) 用户确认支付】以调用统一接口为例
/** * 发起与支付 * 调用统一下单接口,获取“预支付交易会话标识” */ @PostMapping("/unifiedOrder") public ModelAndView unifiedOrder(@RequestBody String orderId, @RequestBody HttpServletRequest request, Mapmap) throws WxPayException { OrderDTO orderDTO = orderService.findOne(orderId); WxPayUnifiedOrderRequest orderRequest = payService.create(orderDTO, request); WxPayUnifiedOrderResult orderResult = wxPayService.unifiedOrder(orderRequest); map.put("orderRequest", orderRequest); map.put("orderResult", orderResult); map.put("timeStamp", payUtil.getTimeStamp()); map.put("nonceStr", payUtil.getNonceStr()); return new ModelAndView("pay/unifiedOrder", map); }

wx.requestPayment( { 'timeStamp': '${timeStamp}', 'nonceStr': '${nonceStr}', 'package': '${orderResult.prepayId}', 'signType': 'MD5', 'paySign': '', 'success':function(res){}, 'fail':function(res){}, 'complete':function(res){} })

创建unifiedOrder.ftl文件。使用${}进行参数注入
讲的不太详细 ModelAndView可以参考这里学习

    推荐阅读