接着上一篇微信H5支付后来。
@ResponseBody
@GetMapping("refund")
public String Refund(@RequestParam("orderId")String orderId,@RequestParam("refundId")String refundId) throws Exception {
Integer total_fee = 1; //付款金额
Integer refund_fee = 1; //退款的金额
SortedMap<String,String> map = new TreeMap<>();
String appid = weChatConfig.appid;
String mch_id = weChatConfig.merId;
String nonce_str =CommonUtils.generateUUID();
String out_refund_no = refundId;//UtilUuId.get18UUID();
map.put("appid", appid);
map.put("mch_id", mch_id);
map.put("nonce_str", nonce_str);
map.put("sign_type", "MD5");
// map.put("transaction_id", ""); //微信支付单号 和 商家订单号 2选一
map.put("out_trade_no",orderId );
map.put("out_refund_no",out_refund_no);
map.put("total_fee", total_fee.toString());
map.put("refund_fee", refund_fee.toString());
String sign = WXPayUtil.createSign(map, weChatConfig.key);
map.put("sign",sign);
String xml = WXPayUtil.mapToXml(map);
log.info("payXml: "+xml);
String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";//微信统一下单接口
try {
//预下单 获取接口地址
Map map1 = weChatPayService.doRefund(mch_id,createOrderURL, xml);//注意了退款.p12证书在这里面配置,官方文档没有怎么详细说明,所以很多同学很头大。
String return_code = (String) map1.get("return_code");
String return_msg = (String) map1.get("return_msg");
System.out.println(return_msg);
if ("SUCCESS".equals(return_code) && "OK".equals(return_msg)) {
return "ok";//JsonResult.ok("success").put("out_refund_no", out_refund_no);
} else {
return "---------统一退单接口出错";//JsonResult.error("统一退单接口出错");
}
} catch (Exception e) {
e.printStackTrace();
return "统一退单接口出错";//JsonResult.error("统一退单接口出错");
}
}
/**
*
* @param mchId 商户ID
* @param url 请求URL
* @param data 退款参数
* @return
* @throws Exception
*/
public Map doRefund(String mchId, String url, String data) throws Exception {
/**
* 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的
*/
KeyStore keyStore = KeyStore.getInstance("PKCS12");//证书格式
//这里自行实现我是使用数据库配置将证书上传到了服务器可以使用 FileInputStream读取本地文件
FileInputStream fis=new FileInputStream("E:\\WXCertUtil\\cert\\apiclient_cert.p12");
try {
//这里写密码..默认是你的MCHID
keyStore.load(fis, mchId.toCharArray());
} finally {
fis.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, mchId.toCharArray())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpPost httpost = new HttpPost(url);
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
System.out.println("---------------------------------------------------");
try {
HttpEntity entity = response.getEntity();
//接受到返回信息
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
System.out.println(jsonStr);
Map<String, String> map = WXPayUtil.xmlToMap(jsonStr);
return map;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}