去微信社区里面查了下,有些人是自己代码错的,但是我拿的微信sdk的demo代码做的改造,然后检查几遍也没看出来问题,我用的是小程序支付,code获取openid没问题,证明我的appid,appsecret没问题,看到有人说是商户密钥问题,其实商户密钥也没问题,可能是微信设置完没生效吧,多重置几遍之后好了,
统一下单关键代码
public Map<String, String> wxPay(String openId, String ipAddress) throws Exception {
Map<String, String> paraMap = new HashMap<>();
paraMap.put("body","123");
paraMap.put("openid",openId);
// 订单号
paraMap.put("out_trade_no", UUID.randomUUID().toString().replaceAll("-",""));
paraMap.put("spbill_create_ip",ipAddress);
paraMap.put("total_fee","1");
paraMap.put("trade_type","JSAPI");
log.info("paraMap为:{}",paraMap.toString());
MyWXPayConfig myWXPayConfig = new MyWXPayConfig();
WXPay wxPay = new WXPay(myWXPayConfig, AppletConfig.NOTIFY_URL, false, false);
Map<String, String> reqData = wxPay.fillRequestData(paraMap);
String s = WXPayUtil.mapToXml(reqData);
log.info("请求时发出的xml字符串:{}",s);
Map<String, String> map = wxPay.unifiedOrder(reqData, 15000, 15000);
String prepayId = map.get("prepay_id");
log.info("微信下单返回xmlStr为:{}",map.toString());
Map<String, String> payMap = new HashMap<>();
payMap.put("appId",AppletConfig.APP_ID);
payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
payMap.put("nonceStr",WXPayUtil.generateNonceStr());
payMap.put("signType", WXPayConstants.HMACSHA256);
payMap.put("package","prepay_id="+prepayId);
String paySign= WXPayUtil.generateSignature(payMap,AppletConfig.KEY,WXPayConstants.SignType.HMACSHA256);
payMap.put("paySign",paySign);
log.info("返回给前端payMap:{}",payMap.toString());
return payMap;
}
这里一定要注意字段名,一个大小写都不能错,我是把timestamp的s写小写了,实际需要验证签名的是timeStamp,这里可查了好久
小程序的支付,这里接受的是字段名,后端需要严格按照这个大小写进行生成签名
wx.requestPayment({
nonceStr: res.data.data.nonceStr,
package: res.data.data.package,
paySign: res.data.data.paySign,
timeStamp: res.data.data.timeStamp,
signType: res.data.data.signType,
success(payRes){
console.log("支付成功",payRes)
},
fail(payRes){
console.log("支付失败",payRes)
}