本以為申請退款應該就沒那么多坑了,沒想到...
申請退款這個環節需要商戶證書,那么好吧,我們按官方文檔給的地址下載一下:微信商戶平臺(pay.weixin.qq.com)-->賬戶中心-->賬戶設置-->API安全-->證書下載
解壓之后有四個文件:
F4AA095C-4C45-4720-B5E3-60664348E70B.png
經過一番百度,原來java web開發只需要使用apiclient_cert.p12這個文件。
我們需要把這個文件放到自己的項目中,我放到了這里:
BD85CFBE-AD83-4B42-BC8E-3AE760AAD107.png
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();
}
}
筆者能力有限,不足之處歡迎指出。