1、问题
ERROR: api.mch.weixin.qq.com:443 failed to respond
此报错是因为调用微信退款请求需要双向证书
获取API证书
此路径下载即可
微信商户平台(pay.weixin.qq.com)–>账户中心–>账户设置–>API安全
一共三个文件,java开发者只需要 apiclient_cert.p12
文件即可
导入安装证书,证书密码默认为商户号
2、代码实现
public BaseResponse<RefundLog> wxpayRefund(PaymentLog paymentLog, BigDecimal refundAmount) throws Exception {
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put(APPID, 公众账号ID);
parameterMap.put(MCHID, 商户号);
parameterMap.put(NONCE_STR, 随机字符串);
parameterMap.put(OUT_TRADE_NO, 商户订单号);
parameterMap.put(OUT_REFUND_NO, 商户退款单号);
parameterMap.put(TOTAL_FEE, 订单金额);
parameterMap.put(REFUND_FEE, 退款金额);
parameterMap.put(SIGN_PARAMETER_NAME, 签名);
//微信退款信息要以xml格式传递
String postDataXML = XMLUtils.getRequestXml(parameterMap);
log.info("支付参数准备XML:{}", postDataXML);
//请求退款连接
String result = wxRefundLink(postDataXML, mch_id);
//返回这转为map
Map responseMap = XMLUtils.fromXML(result);
//退款状态业务处理
if (FAIL.equals(responseMap.get(RETURN_CODE))) {
return BaseResponse.successResponse("微信退款失败,"+responseMap.get(RETURN_MSG));
} else{
if (SUCCESS.equals(responseMap.get(RESULT_CODE))) {
return BaseResponse.successResponse("微信退款完成");
} else {
//出现业务错误
String errorCodeDes = String.valueOf(responseMap.get(ERR_CODE_DES));
log.error("err_code_des:" + errorCodeDes);
return BaseResponse.successResponse("退款失败"+errorCodeDes);
}
}
}
private String wxRefundLink(String postDataXML,String mch_id) throws Exception{
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try{
//获取微信退款证书
KeyStore keyStore = getCertificate(mch_id);
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
SSLConnectionSocketFactory sslf = new SSLConnectionSocketFactory(sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslf).build();
HttpPost httpPost = new HttpPost(WX_REFUND_URL);//退款接口
StringEntity reqEntity = new StringEntity(postDataXML);
// 设置类型
reqEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(reqEntity);
String result = null;
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (Validator.isNotNullOrEmpty(httpEntity)) {
result = EntityUtils.toString(httpEntity, UTF8);
EntityUtils.consume(httpEntity);
}
return result;
}finally {//关流
httpClient.close();
httpResponse.close();
}
}
/**
*
* @description: 获取微信退款证书
* @param mch_id
* @auther: sean.xu
* @date: 2019/8/13 15:11
*/
private KeyStore getCertificate(String mch_id){
//try-with-resources 关流
try (FileInputStream inputStream = new FileInputStream(new File("D:\\wx\\1248201701_20190812_cert\\apiclient_cert.p12"))) {
KeyStore keyStore = KeyStore.getInstance(PKCS12);
keyStore.load(inputStream, mch_id.toCharArray());
return keyStore;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
3、效果截图
四、友情链接
退款文档
https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_4&index=6
签名 证书
https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3