out_trade_no:退款订单号;
money:退款金额;
appid:商户appid
mchid :商户 mchid; apikey:商户apikey; couponid:优惠券id(之前的逻辑涉及到优惠券)
private void refund(String out_trade_no, BigDecimal money, String appid, String mchid, String apikey, Integer couponid) {
HashMap map =new HashMap<>();
//nonce_str随机字符串
String SYMBOLS ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random RANDOM =new SecureRandom();
char[] nonceChars =new char[32];
for (int index =0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
String nonce_str =new String(nonceChars);
//out_refund_no 商品
String number1 = String.valueOf((int) (Math.random() *8998) +1000 +1);
Date time =new Date();
String str1 = String.valueOf(time.getTime() /1000);
String out_refund_no = str1 + number1;
//传入参数
map.put("appid", appid);
map.put("mch_id", mchid);
map.put("nonce_str", nonce_str);
// 注意订单号
map.put("out_trade_no", out_trade_no);
// 注意退款单号
map.put("out_refund_no", out_refund_no);
// map.put("transaction_id", "42000015262022191230"); 这个是微信单号,退款单号和微信单号二选一*
//设置退款金额 total_fee该订单的总金额 refund_fee 需要退款的金额
BigDecimal refundmoney = money.multiply(new BigDecimal("100")); //转为分
// 实际退款金额 (一般是原价),如果有业务逻辑要求的话,可以自行处理
BigDecimal rmoney = refundmoney.multiply(BigDecimal.valueOf(intall.getI_room_pro()));
map.put("total_fee", refundmoney.setScale(0, BigDecimal.ROUND_DOWN).toPlainString());
map.put("refund_fee", rmoney.setScale(0, BigDecimal.ROUND_DOWN).toPlainString());
try {
//将map参数生成一个签名
String sign = WXPayUtil.generateSignedXml(map, apikey);
String payRefundURL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
// 认证退款证书
String resultXml =clientCustomSSL.doRefund(payRefundURL, sign);
Map post = WXPayUtil.xmlToMap(resultXml);
if (post.get("result_code").equals("SUCCESS") && post.get("return_code").equals("SUCCESS")) {
// 修改详情表中退款
****************************************************************
此处是退款逻辑业务修改
****************************************************************
}else {
throw new BusinessException(BusinessStatus.FAIL, "退款失败");
}
}catch (Exception e) {
System.out.println(e.getMessage());
log.info(e.getMessage());
e.printStackTrace();
throw new BusinessException(BusinessStatus.FAIL, "退款错误");
}
}
使用到的doRefund方法
public class ClientCustomSSL {
@Value("${wx.mchcertpath}")
private String SSLpath;
SSLpath:退款证书的存放路径
@Value("${wx.mchid}")
private String mchid;
public String doRefund(String url, String data)throws Exception {
//指定读取证书格式为PKCS12(注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的)
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// 指定证书路径
String path =SSLpath;
//读取本机存放的PKCS12证书文件
FileInputStream instream =new FileInputStream(new File(path));
try {
//指定PKCS12的密码(商户ID)
keyStore.load(instream,mchid.toCharArray());
}finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
//指定TLS版本
SSLConnectionSocketFactory sslsf =new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//设置httpclient的SSLSocketFactory
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpost =new HttpPost(url);// 设置响应头信息
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
}finally {
response.close();
}
}finally {
httpclient.close();
}
}
}