java 微信H5支付
點擊支付在js中處理請求:
var callbackUrl = 'http://www.xxxxx.com/reader/charges.html?u&price="+price;
window.location.href = callbackUrl;
ajax提交請求:
<!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>微信充值中...</title> </head> <body> </body> <script src="javascripts/config.js" type="text/javascript"></script> <script src="javascripts/md5.min.js"></script> <script src="javascripts/jquery-3.2.1.min.js"></script> <script src="javascripts/util.js"></script> <script> var uid = getQueryString('uid'); var price = getQueryString('price'); $.ajax({ type: 'post', url: '/reader/wxpay/wxCharges.dom', data: {uid:uid,price:price}, success: function (data) {
//后臺返回調起微信支付的鏈接,直接跳轉過去即可 window.location.href=data; } }) function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; } </script> </html>
后臺處理請求:
public String wxCharges(String price,String uid) { try{ logger.info("before insert charge..."); Charge charge = new Charge(); charge.setId(IdGenerate.getId()); charge.setCdate(sdf.format(new Date())); charge.setCoin(price); charge.setStatus("0"); charge.setMoney(String.valueOf(Integer.valueOf(price)/100)); charge.setUid(uid); charge.setZhifutype("wx"); charge.setXstype("web"); chargeMapper.insertCharge(charge); logger.info("after insert charge..."); //訂單號 String tradeNo = charge.getId(); String payUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; String ip = SpringUtils.getRequestIP(); System.out.println("ip:"+ip); String stringA = "app + "mch_ + "http://www.xxxx.com/reader/wxpay/wxChargeCallback.dom&out_trade_no=" + tradeNo + "&scene_info={\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.xxxx.com/reader/home.html\",\"wap_name\": \"xxxx在線充值\"}}&spbill_create_ip=" + ip + "&total_fee=" + price +"&trade_type=MWEB&key=" + WxPayParam.API_KEY; System.out.println(stringA); String sign = DigestUtils.md5Hex(stringA).toUpperCase(); // String sign = MD5(stringA).toUpperCase(); String xml = "<xml>\n" + " <appid>"+WxPayParam.APPID+"</appid>\n" + " <attach>xxxx在線充值</attach>\n" + " <body>xxxx在線充值</body>\n" + " <mch_id>"+WxPayParam.PAY_MCH_ID+"</mch_id>\n" + " <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>\n" + " <notify_url>http://www.xxxx.com/reader/wxpay/wxChargeCallback.dom</notify_url>\n" + " <out_trade_no>" + tradeNo + "</out_trade_no>\n" + " <spbill_create_ip>" + ip + "</spbill_create_ip>\n" + " <total_fee>" + price + "</total_fee>\n" + " <trade_type>MWEB</trade_type>\n" + " <scene_info>{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.xxxx.com/reader/home.html\",\"wap_name\": \"xxxx在線充值\"}}</scene_info>\n" + " <sign>" + sign + "</sign>\n" + " </xml>"; System.out.println(xml); HttpClient client = new HttpClient(); client.getParams().setContentCharset("utf-8"); PostMethod post1 = new PostMethod(payUrl); post1.setRequestBody(xml); post1.addRequestHeader("accept", "application/xml"); // 視具體情況而定,可以從瀏覽器或postman查看下請求的header post1.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); //這里設置具體編碼,視具體接口而定 post1.setRequestHeader("Content-type", "text/xml; charset=UTF-8"); client.executeMethod(post1); String response1 = post1.getResponseBodyAsString(); logger.info("response1: " + response1); String str=response1.substring(response1.indexOf("<mweb_url><![CDATA[")+"<mweb_url><![CDATA[".length(),response1.indexOf("]]></mweb_url>"));
//redirect_url是支付成功之后你自己想要跳轉的頁面,默認是沒有的,需要自己添加,如果不添加,支付完之后還會回到支付頁面,一直循環
return (str +"&redirect_url=http://www.xxxxx.com/reader/home.html");
} catch (Exception e){
logger.error("error: ", e);
return null;
}
}
微信支付回調:
public String wxChargeCallback() { logger.info("wx charge call back..."); try { Map<String, String> map = getWxCallbackParams(); String result_code = map.get("result_code"); String out_trade_no = map.get("out_trade_no"); String total_fee = map.get("total_fee"); logger.info("result_code: " + result_code); logger.info("out_trade_no: " + out_trade_no); logger.info("total_fee: " + total_fee); //處理業務邏輯 if ("SUCCESS".equals(result_code)) { //微信支付成功,設置支付金額 Charge charge = new Charge(); charge.setId(out_trade_no); List<Charge> charges = chargeMapper.selectCharge(charge); if (charges.size() > 0) { Charge c = charges.get(0); logger.info(c); //實際支付金額(元) logger.info("before callback update charge"); c.setStatus("1"); chargeMapper.updateCharge(c); logger.info("after callback update charge"); //更新用戶幣量 logger.info("before callback update user"); User user = new User(); user.setId(c.getUid()); List<User> users = userMapper.selectUser(user); if (users.size() > 0) { User user1 = users.get(0); logger.info(user1); user1.setBalance("" + (Integer.parseInt(user1.getBalance()) + Integer.parseInt(c.getCoin()))); userMapper.updateUser(user1); } logger.info("after callback update user"); } return returnXML(result_code); } return returnXML("FAIL"); } catch (Exception e) { e.printStackTrace(); return returnXML("FAIL"); } }
/** * 獲取微信回調參數 */ private Map getWxCallbackParams() throws IOException, JDOMException { HttpServletRequest request = SpringUtils.getRequest(); BufferedReader reader; reader = request.getReader(); String line; String xmlString; StringBuffer inputString = new StringBuffer(); while ((line = reader.readLine()) != null) { inputString.append(line); } xmlString = inputString.toString(); request.getReader().close(); logger.info("微信回調數據:" + xmlString); return XmlUtils.doXMLParse(xmlString); }