public static WxPayEntity weixinPayByH5(WxPayEntity entity){ WxPayEntity returnPar = new WxPayEntity(); try { if(StringUtils.isNotBlank(entity.getCommodityName()) && StringUtils.isNotBlank(entity.getNotifyUrl()) && StringUtils.isNotBlank(entity.getOrderCode()) && StringUtils.isNotBlank(entity.getIp()) && StringUtils.isNotBlank(entity.getMoney()) ){ entity.setMoney(String.valueOf((int)(Double.valueOf(entity.getMoney())*100))); returnPar.setNonceStr(RandomStringUtils.randomAlphanumeric(32));//随机字符串 StringBuffer appid = new StringBuffer();//签名 appid.append("appid="+entity.getAppID()+"&body="+entity.getCommodityName()+"&mch_id=" +entity.getMchId()+"&nonce_str="+returnPar.getNonceStr()+"¬ify_url="+ entity.getNotifyUrl()+"&out_trade_no="+entity.getOrderCode()+"&spbill_create_ip="+entity.getIp()); appid.append("&total_fee="+entity.getMoney()+"&trade_type=MWEB&key="+entity.getKey()); System.out.println(appid.toString()); String sige= MD5Util.MD5Encode(appid.toString(),"utf-8" ).toUpperCase(); //发送请求 StringBuffer weixin = new StringBuffer(); weixin.append("<xml><appid>"+entity.getAppID()+"</appid>"+ "<body>"+entity.getCommodityName()+"</body>"+ //商品标题 "<mch_id>"+entity.getMchId()+"</mch_id>"+ //商户id "<nonce_str>"+returnPar.getNonceStr()+"</nonce_str>"+ //随机字符 "<notify_url>"+entity.getNotifyUrl()+"</notify_url>"+ //异步回调地址 "<out_trade_no>"+entity.getOrderCode()+"</out_trade_no>"+ //订单号 "<spbill_create_ip>"+entity.getIp()+"</spbill_create_ip>"); //发起设备ip weixin.append("<total_fee>"+entity.getMoney()+"</total_fee>"+ //支付金额 "<trade_type>MWEB</trade_type>"+ //交易类型 "<sign>"+sige+"</sign></xml>"); //签名 try { log.debug(weixin.toString()); JSONObject aString = HttpsUtil.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", weixin.toString()); log.debug(aString.toString()); } catch (Exception e) { e.printStackTrace(); } //发送请求得到xml字符串 Document document=HttpsUtil.httpRequestXml("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", weixin.toString()); // 得到xml根元素 Element root = document.getRootElement(); log.debug(root.toString()); // count表示对应xml节点的值 String count = root.element("prepay_id").getText(); returnPar.setPrepayId(count); String mwebUrl = root.element("mweb_url").getText(); returnPar.setCodeUrl(mwebUrl); //生成支付签名 returnPar.setTime((new BigDecimal((System.currentTimeMillis())/1000).setScale(0, BigDecimal.ROUND_HALF_UP)).toString()); //时间戳 String paySign = "appId="+entity.getAppID()+"&nonceStr="+ returnPar.getNonceStr() +"&package=prepay_id="+returnPar.getPrepayId()+"&signType=MD5&timeStamp=" + returnPar.getTime() + "&key="+entity.getKey(); returnPar.setSign(MD5Util.MD5Encode(paySign,"utf-8" ).toUpperCase()); //支付签名 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnPar; }
微信H5支付
该代码段展示了如何使用Java实现微信支付H5接口的调用过程。首先检查必要的参数是否为空,然后计算签名并构造XML请求,通过HTTPS发送到微信支付API,获取预支付id和H5支付url,最后生成支付所需的参数并返回。
摘要由CSDN通过智能技术生成