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
效果:在微信外部瀏覽器打開