微信小程序支付
1.定义支付商家参数
1 public class WXPay { 2 //小程序appid 3 public static final String appid = "wx52028f436ab96a6d"; 4 //微信支付的商户id 5 public static final String mch_id = "1564197831"; 6 //微信支付的商户密钥 7 public static final String key = "SDFDFSDF1SD23F13ASD2F1S32DF1A3S2"; 8 //支付成功后的服务器回调url,这里填PayController里的回调函数地址 9 public static final String notify_url = "https://signup.shengweiholdings.com/school/api/pay/wxNotify"; 10 //public static final String notify_url = "http://127.0.0.1:8082/api/pay/wxNotify";//测试 11 //签名方式,固定值 12 public static final String SIGNTYPE = "MD5"; 13 //交易类型,小程序支付的固定值为JSAPI 14 public static final String TRADETYPE = "JSAPI"; 15 //微信统一下单接口地址 16 public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; 17 }
2 .提示:支付前先生成订单
1 /** 2 * 3 * 向服务请求支付参数:通过小程序定义的 requestPayParam()发起 4 * 5 * 6 */ 7 requestPayParam() { 8 let that = this; 9 util.request(api.Orderpay, {ip: that.data.ip}).then(function (res) { 10 if (res.code === 0) { 11 let payParam = res.data; 12 wx.requestPayment({ 13 timeStamp: res.data.timeStamp, 14 nonceStr: res.data.nonceStr, 15 package: res.data.package, 16 //可以通过后台定义的商家参数返回也可以写死 17 signType: 'MD5', 18 paySign: res.data.paySign, 19 //支付成功 20 'success': function(res) { 21 wx.redirectTo({ 22 url: '/pages/Pre-registration/payResult/payResult?status=true', 23 }) 24 }, 25 //支付失败 26 'fail': function(res) { 27 wx.redirectTo({ 28 url: '/pages/Pre-registration/payResult/payResult?status=false', 29 }) 30 } 31 }) 32 } 33 }); 34 },
3 .后台请求接口 提示:这里有一个预支付
1 @RestController 2 public class WXPayApi { 3 @Autowired 4 private WxUserService wxUserService; 5 6 @Autowired 7 private WxOrderService wxOrderService; 8 9 @Autowired 10 private OrderRecordService orderRecordService; 11 12 /** 13 * 请求支付接口 14 * @param userId 15 * @param request 16 * @return 17 * @throws Exception 18 */ 19 @PostMapping("/api/pay/wxPay") 20 public R wxPay(@LoginUser Long userId,HttpServletRequest request) throws Exception { 21 WxUserEntity entity = wxUserService.get(userId); 22 String openId = entity.getUserOpenid(); 23 24 Map ordermap=wxOrderService.orderMessage(userId); 25 String goodsName = ordermap.get("goodsName").toString(); 26 String orderNum = ordermap.get("orderNum").toString(); 27 String total_fee = ordermap.get("total_fee")+ ""; 28 total_fee="1"; 29 Map<String, Object> response = new HashMap<>();//返回给小程序端需要的参数 30 response.put("success", true); 31 response.put("msg", ""); 32 try { 33 //生成的随机字符串 34 String nonce_str = getRandomStringByLength(32); 35 //商品名称 36 String body = goodsName; 37 //获取客户端的ip地址 38 String spbill_create_ip = getIpAddr(request); 39 40 //组装参数,用户生成统一下单接口的签名 41 Map<String, String> packageParams = new HashMap<>(); 42 packageParams.put("appid", WXPay.appid); 43 packageParams.put("mch_id", WXPay.mch_id); 44 packageParams.put("nonce_str", nonce_str); 45 packageParams.put("body", body); 46 packageParams.put("out_trade_no", orderNum);//商户订单号,自己的订单ID 47 packageParams.put("total_fee", total_fee);//支付金额,这边需要转成字符串类型,否则后面的签名会失败 48 packageParams.put("spbill_create_ip", spbill_create_ip); 49 packageParams.put("notify_url", WXPay.notify_url);//支付成功后的回调地址 50 packageParams.put("trade_type", WXPay.TRADETYPE);//支付方式 51 packageParams.put("openid", openId + "");//用户的openID,自己获取 52 53 String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 54 55 //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口 56 String mysign = PayUtil.sign(prestr, WXPay.key, "utf-8").toUpperCase(); 57 58 //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去 59 String xml = "<xml>" + "<appid>" + WXPay.appid + "</appid>" 60 + "<body><![CDATA[" + body + "]]></body>" 61 + "<mch_id>" + WXPay.mch_id + "</mch_id>" 62 + "<nonce_str>" + nonce_str + "</nonce_str>" 63 + "<notify_url>" + WXPay.notify_url + "</notify_url>" 64 + "<openid>" + openId + "</openid>" 65 + "<out_trade_no>" + orderNum + "</out_trade_no>" 66 + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 67 + "<total_fee>" + total_fee + "</total_fee>"//支付的金额,单位:分 68 + "<trade_type>" + WXPay.TRADETYPE + "</trade_type>" 69 + "<sign>" + mysign + "</sign>" 70 + "</xml>"; 71 72 //调用统一下单接口,并接受返回的结果 73 String result = PayUtil.httpRequest(WXPay.pay_url, "POST", xml); 74 75 // 将解析结果存储在HashMap中 76 Map map = PayUtil.doXMLParse(result); 77 78 String return_code = (String) map.get("return_code");//返回状态码 79 String result_code = (String) map.get("result_code");//返回状态码 80 String return_msg = (String) map.get("return_msg");//错误描述 81 System.out.println("++++++++return_code:" + return_code); 82 System.out.println("++++++++result_code:" + result_code); 83 System.out.println("--------return_msg:" + return_msg); 84 85 if ("SUCCESS".equals(return_code) && return_code.equals(result_code)) { 86 System.out.println("---------组装预付单信息数据"); 87 System.out.println("map信息:" + map); 88 String prepay_id = (String) map.get("prepay_id");//返回的预付单信息 89 response.put("nonceStr", nonce_str); 90 response.put("package", "prepay_id=" + prepay_id); 91 Long timeStamp = System.currentTimeMillis() / 1000; 92 response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误 93 //拼接签名需要的参数 94 String stringSignTemp = "appId=" + WXPay.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp; 95 //再次签名,这个签名用于小程序端调用wx.requesetPayment方法 96 String paySign = PayUtil.sign(stringSignTemp, WXPay.key, "utf-8").toUpperCase(); 97 response.put("paySign", paySign); 98 } 99 response.put("appid", WXPay.appid); 100 } catch (Exception e) { 101 e.printStackTrace(); 102 response.put("success", false); 103 response.put("msg", e.getMessage()); 104 } 105 return R.ok().put("data", response); 106 } 107 108 /** 109 * 微信支付回调 110 * @param request 111 * @param response 112 * @throws Exception 113 */ 114 @RequestMapping(value = "/api/pay/wxNotify", method = RequestMethod.POST) 115 public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception { 116 System.out.println("进入微信支付回调----------"); 117 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 118 String line = null; 119 StringBuilder sb = new StringBuilder(); 120 while ((line = br.readLine()) != null) { 121 sb.append(line); 122 } 123 br.close(); 124 //sb为微信返回的xml 125 String notityXml = sb.toString(); 126 String resXml = ""; 127 Map map = PayUtil.doXMLParse(notityXml); 128 String returnCode = (String) map.get("return_code"); 129 System.out.println("returnCodeL:" + returnCode); 130 if ("SUCCESS".equals(returnCode)) { 131 String result_code = (String) map.get("result_code"); 132 //验证签名是否正确 133 Map<String, String> validParams = PayUtil.paraFilter(map); //回调验签时需要去除sign和空值参数 134 String prestr = PayUtil.createLinkString(validParams); 135 System.out.println("回调参数======" + map); 136 //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等 137 if (PayUtil.verify(prestr, (String) map.get("sign"), WXPay.key, "utf-8")) { 138 System.out.println("签名正确======="); 139 /**此处添加自己的业务逻辑代码start**/ 140 String transactionId = (String) map.get("transaction_id");//微信支付单号 141 String orderNumber = (String) map.get("out_trade_no");//订单号 142 String timeEnd = (String) map.get("time_end");//支付完成时间 143 String totalFee = (String) map.get("total_fee");//订单金额 144 WxOrderEntity order = wxOrderService.findByOrderNumber(orderNumber); 145 if(order != null){ 146 System.out.println("订单不为空"); 147 //修改订单表状态---改为以报名 148 order.setState(WxOrderStateEnum.entry.getCode()); 149 wxOrderService.save(order); 150 //支付成功,添加订单记录信息 151 OrderRecordEntity orderRecord = new OrderRecordEntity(); 152 orderRecord.setOrderNumber(orderNumber); 153 orderRecord.setPrice((long) Integer.parseInt(totalFee)); 154 orderRecord.setTransactionId(transactionId); 155 orderRecord.setPaymentMethod("微信"); 156 orderRecord.setCreatedDt(TimeUtil.getDataTime()); 157 orderRecordService.save(orderRecord); 158 System.out.println("添加订单记录成功"); 159 //通知微信服务器已经支付成功 160 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" 161 + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; 162 System.out.println("通知微信服务器返回的信息"+resXml); 163 }else{ 164 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" 165 + "<return_msg><![CDATA[订单不存在]]></return_msg>" + "</xml> "; 166 System.out.println("通知微信服务器返回的信息"+resXml); 167 } 168 } else { 169 System.out.println("验签失败-------"); 170 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" 171 + "<return_msg><![CDATA[验签失败]]></return_msg>" + "</xml> "; 172 } 173 } else { 174 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" 175 + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> "; 176 } 177 178 BufferedOutputStream out = new BufferedOutputStream( 179 response.getOutputStream()); 180 out.write(resXml.getBytes()); 181 out.flush(); 182 out.close(); 183 } 184 185 //获取随机字符串 186 private String getRandomStringByLength(int length) { 187 String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 188 Random random = new Random(); 189 StringBuffer sb = new StringBuffer(); 190 for (int i = 0; i < length; i++) { 191 int number = random.nextInt(base.length()); 192 sb.append(base.charAt(number)); 193 } 194 return sb.toString(); 195 } 196 197 //获取IP 198 private String getIpAddr(HttpServletRequest request) { 199 String ip = request.getHeader("X-Forwarded-For"); 200 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { 201 //多次反向代理后会有多个ip值,第一个ip才是真实ip 202 int index = ip.indexOf(","); 203 if (index != -1) { 204 return ip.substring(0, index); 205 } else { 206 return ip; 207 } 208 } 209 ip = request.getHeader("X-Real-IP"); 210 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { 211 return ip; 212 } 213 return request.getRemoteAddr(); 214 } 215 216 public static void main(String[] args) throws Exception { 217 218 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 219 Date d = sdf.parse("20190919085723"); 220 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 221 System.out.println(sdf1.parse(sdf1.format(d))); 222 } 223 }

浙公网安备 33010602011771号