微信公众号-申请退款-Java

  • 接口地址
  1. 接口链接:https://api.mch.weixin.qq.com/secapi/pay/refund
  • 是否需要证书
  1. 请求需要双向证书,需要登录微信支付官网下载证书
  • 请求参数
  1. 详见微信支付官方文档(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4)
  • 说明
  1. 关于微信中的签名、将map 转 xml串或xml串转map 在微信Demo 中都可以找到
//组装退款需要的参数
Map<String, String> data = new HashMap<>();
data.put("appid", WxPayConstants.APPID);//公众账号ID
data.put("mch_id", WxPayConstants.MCH_ID);//商户号
data.put("sign_type", "MD5");//签名类型
data.put("nonce_str", "ABCDEFG001");//随机字符串
data.put("transaction_id", "3200000053200000000000000001");//微信订单号
data.put("out_refund_no", "T000000000001");//商户退款单号
data.put("total_fee", "100");//订单金额,单位为分
data.put("refund_fee", "100");//退款金额,单位为分
data.put("refund_fee_type", "CNY");//退款货币种类
data.put("notify_url", this.refundNotifyUrl);//退款结果通知url
//生成签名信息
data.put("sign", WxPayUtils.generateSignature(data, WxPayConstants.KEY));//KEY:签名密钥
//将map 转为xml串
String mapToXml = WxPayUtils.mapToXml(data);

KeyStore keyStore = KeyStore.getInstance("PKCS12");
//加载本地的证书进行https加密传输
FileInputStream instream = new FileInputStream(new File(this.certPath));//certPath:证书路径
try {
      keyStore.load(instream, WxPayConstants.MCH_ID.toCharArray());  //加载证书密码,默认为商户ID
} catch (Exception e) {
       //do nothing
}finally {
       instream.close();
}
// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, WxPayConstants.MCH_ID.toCharArray());

// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    new DefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()  
                    .setSSLSocketFactory(sslConnectionSocketFactory).build();
//退款请求地址
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
			
StringEntity reqEntity = new StringEntity(mapToXml);
			
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
	        
httpPost.addHeader("Content-Type", "text/xml");
//设置参数
httpPost.setEntity(reqEntity);
			
//发起请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取退款返回内容
String strResult = EntityUtils.toString(response.getEntity(), Charset.forName(encoding));
	        

猜你喜欢

转载自my.oschina.net/u/3694704/blog/1791883