本以为申请退款应该就没那么多坑了,没想到...
申请退款这个环节需要商户证书,那么好吧,我们按官方文档给的地址下载一下:微信商户平台(pay.weixin.qq.com)-->账户中心-->账户设置-->API安全-->证书下载
解压之后有四个文件:
经过一番百度,原来java web开发只需要使用apiclient_cert.p12这个文件。
我们需要把这个文件放到自己的项目中,我放到了这里:
ok,废话说完了,接下来上代码:
public static String payHttps(String data,String id) throws Exception {
//指定读取证书格式为PKCS12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
//读取本机存放的PKCS12证书文件
FileInputStream instream = new FileInputStream(new File("doc/apiclient_cert.p12"));
try {
//指定PKCS12的密码, 商户ID
keyStore.load(instream, id.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, id.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 {
/**
* wx 头信息设置
*/
//因为牵扯到证书, 所以不使用HttpURLConnection, 改用HttpClient
HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund"); // 设置响应头信息
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);
System.out.println("jsonStr" + jsonStr);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
笔者能力有限,不足之处欢迎指出。