H5支付以及场景介绍:https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1
H5支付是指商户在微信客户端外的移动端网页展示商品或服务,用户在前述页面确认使用微信支付时,商户发起本服务呼起微信客户端进行支付。
主要用于触屏版的手机浏览器请求微信支付的场景。可以方便的从外部浏览器唤起微信支付。
该案列用的是微信官方提供的sdk,首先去微信官方下载sdk,SDK配置可参考
https://www.cnblogs.com/lccsdncnblogs/p/wxpay.html
去商户平台配置支付授权域名:
H5支付
public String wxPayH5s(HttpServletRequest request) { String out_trade_no = System.currentTimeMillis( ) + ""; try { Map< String, String > maps = new HashMap<>( ); maps.put("out_trade_no", out_trade_no); maps.put("spbill_create_ip", getRealIp(request)); maps.put("total_fee", 1+""); maps.put("trade_type", "MWEB"); maps.put("notify_url", "http://xxxxxx/notifyUrl"); maps.put("body", "xxxxxxxx学费"); MyWxPayConfig myWxPayConfig = new MyWxPayConfig( ); WXPay wxPay = new WXPay(myWxPayConfig); Map< String, String > reqData = wxPay.fillRequestData(maps); Map< String, String > map = wxPay.unifiedOrder(reqData); String mWebUrl = map.get("mweb_url"); //把成功后的跳转页面进行urlencoding转码 https://www.sojson.com/encodeurl.html String redirectUrl = "http%3a%2f%2fpay.soochow-abroad.com%2ftuition%2f"; mWebUrl += "&redirect_url=" + redirectUrl; return mWebUrl; } catch (Exception e) { e.printStackTrace( ); } return ""; }
获取ip
public String getRealIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
支付回调函数
/** * 微信支付 回调函数 */ public void notifyUrl(HttpServletRequest request) throws Exception {//读取参数 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream( ))); String line; StringBuilder sb = new StringBuilder( ); while ((line = br.readLine( )) != null) { sb.append(line); } if (StringUtils.isBlank(sb)) { return; } //支付结果通知的xml格式数据 String notifyData = sb.toString( ); MyWxPayConfig myWxPayConfig = new MyWxPayConfig( ); WXPay wxpay = new WXPay(myWxPayConfig); Map< String, String > notifyMap = WXPayUtil.xmlToMap(notifyData); //验证签名是否正确 if (wxpay.isPayResultNotifySignatureValid(notifyMap)) { //支付成功 if ("SUCCESS".equals(notifyMap.get("result_code"))) { //商户订单号 String out_trade_no = notifyMap.get("out_trade_no"); Student order = Student.dao.findFirst("select * from student where wx_order_number = ? ", out_trade_no); order.setIspay(1); order.setPayMethod(2); order.setPayTime(new Date( )); order.update( ); //把订单状态改成已付款 } else { //log.info("微信支付回调函数:支付失败"); } } else { //log.info("微信支付回调函数:微信签名错误"); } }
常见问题 : https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
效果:在微信外部浏览器打开