微信App支付,最烦的问题应该是微信支付签名 一定要参考官网支付文档里字段要一一对应。
通过签名获取到预支付ID 然后通过预支付id请求统一下单地址会返回一个签名,最终生成支付签名
里面需要配置沙箱环境,至于沙箱环境大家可以自行百度。
基本实现代码如下
SortedMap<String, String> mp = new TreeMap<>();
mp.put("appid", AppWxConfig.appid);//应用ID
mp.put("mch_id", AppWxConfig.mch_id);//商户id
String str = AppPayUtil.create_nonce_str();//生成随机字符串
mp.put("nonce_str", str);// 随机字符串
mp.put("body", "AA");// 商品描述
mp.put("out_trade_no", orders.getOrderNo());//订单号
String s=orders.getPayMoney();
int s1=(int)(Double.valueOf(s)*100);
mp.put("total_fee", String.valueOf(s1));//价格
mp.put("spbill_create_ip", AppWxConfig.client_ip);// 终端IP
mp.put("notify_url", AppWxConfig.notify_url);// 异步通知地址
mp.put("trade_type", "APP");// 交易类型
String sign = " "; // 定义签名
sign = AppPayUtil.createSign("UTF-8", mp, AppWxConfig.wx_api_key);//创建签名
mp.put("sign", sign);//签名
System.out.println("----------sign"+sign);
System.out.println("----------------------sign=" + sign);
// 将数据转换为xml文件
String xml = AppPayUtil.getRequestXml(mp);
System.out.println("------------------------------xml"+xml);
String prepay_id = "";
SortedMap<String, String> signMap = new TreeMap<>();
//通过URL请求下单地址
URL url = new URL(AppWxConfig.UNIFIED_ORDER_URL);// 统一下单的地址
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Context-", "no-cache");
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
String xmlInfo = xml.toString();
System.out.println("----------------------xmlInfo:" + xmlInfo);
out.write(new String(xmlInfo.getBytes("UTF-8")));
out.flush();
out.close();
BufferedReader br1 = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String result1 = "";
String line1 = "";
for (line1 = br1.readLine(); line1 != null; line1 = br1.readLine()) {
result1 = result1 + line1;
}
System.out.println("------------------result:"+result1);
Map<String, Object> xmlMap = XmlConverUtil.xmltoMap(result1);
prepay_id = (String) xmlMap.get("prepay_id");
System.out.println("prepay_id:" + prepay_id);// 打印预支付ID
String xmlsign = (String) xmlMap.get("sign");
System.out.println("xmlsign:" + xmlsign);
// 生成支付 sign 的参数 signMap
signMap.put("appid", AppWxConfig.appid);// 应用ID
System.out.println("appid:" + AppWxConfig.appid);
signMap.put("partnerid", AppWxConfig.mch_id);//商户id
Long nowDate = new Date().getTime() / 1000;
signMap.put("timestamp", nowDate.toString());// 时间戳
System.out.println("timeStamp:" + nowDate.toString());
System.out.println("nonceStr:" + str);
signMap.put("noncestr", str);// 随机串
System.out.println("prepay_id:" + prepay_id);
signMap.put("prepayid",prepay_id);// 预支付ID
signMap.put("package", "Sign=WXPay");
// signMap.put("signtype", "MD5");// 加密方式 目前只支持MD5加密
// 生成支付sign
String paySign = AppPayUtil.createSign("UTF-8", signMap, AppWxConfig.wx_api_key);
System.out.println("paySign:" + paySign);
signMap.put("sign", paySign);