微信支付h5

1:引导用户点击点击下一步,然后向后台发送请求

    1.1:先贴出业务层的代码。

            基本上逻辑都是在后台处理

            //调用统一下单接口

 //1:构建请求参数,参数详情看微信支付文档https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1

            Map param =new HashMap<>();

            param.put("appid",wxAppid);

           param.put("mch_id",mchid);

             param.put("nonce_str",WXPayUtil.generateNonceStr());

           param.put("body","充值");

             param.put("out_trade_no", “订单号”);

param.put("total_fee",“金额”);

param.put("spbill_create_ip",IpUtil.getIpAddr(request));

param.put("notify_url","填回调地址");

param.put("trade_type","MWEB");

param.put("scene_info","");

try {

//将map转换成xml

        String xml = WXPayUtil.generateSignedXml(param,apikey);

//发送请求调用统一下单接口

        HttpClient client =new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

client.setXmlParam(xml);

client.setHttps(true);

client.post();

//返回结果

        String xmlResult  = client.getContent();

//将xml字符串转换成map集合

        Map result = WXPayUtil.xmlToMap(xmlResult);

Map map =new HashMap<>();

if (!result.get("return_msg").equals("OK")) {

map.put("file","系统错误");

return map;

}

if(memberPaymentMapper.insertSelective(memberPayment) ==0)

{

throw new RuntimeException("插入充值记录失败");

}

String url="支付成功需要返回的页面";

String url_encode = java.net.URLEncoder.encode(url,"utf-8");

//这里是调用成功之后,会给你返回一个url,直接到前端跳转就可以了,就可以唤起微信了。

map.put("mweb_url", result.get("mweb_url")+"&redirect_url="+url_encode);

return map;

}catch (Exception e) {

e.printStackTrace();

return new HashMap<>();

}

}




//回调地址通知

@RequestMapping("/callback")

@ResponseBody

public String callBack(HttpServletRequest request){

String inputLine;

String notityXml ="";


try {

while ((inputLine = request.getReader().readLine()) !=null) {

notityXml += inputLine;

logger.info(notityXml);

}

request.getReader().close();

}catch (Exception e) {

}

Map notifyMap;

PaymentConfig config;

try {

config =new PaymentConfig();

WXPay wxpay =new WXPay(config);

notifyMap = WXPayUtil.xmlToMap(notityXml);

//支付成功告诉微信

 if (wxpay.isPayResultNotifySignatureValid(notifyMap)  {

return "";//这里主要是告诉微信支付成功了,让微信闭嘴,不然会一直给你后台发送消息。

}

else {

// 签名错误,如果数据里没有sign字段,也认为是签名错误

        }

}catch (Exception e) {

e.printStackTrace();

}

return "";

}

你可能感兴趣的:(微信支付h5)