public static EnterpriceToCustomer WXPayToBC(String encBankAcctNo, String encBankAcctName, String bank_code, String desc,
String amount) throws Exception {
String partner_trade_no = RandomStringUtils.randomAlphanumeric(32);// 生成随机号
String nonce_str1 = RandomStringUtils.randomAlphanumeric(32);
String mch_id = “商户id”;// 商务号的id
// 定义自己公钥的路径
PublicKey pub = RSAUtil.getPublicKey(“RSA”);
String rsa = “RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING”;// rsa是微信付款到银行卡要求我们填充的字符串(Java)
try {
byte[] estr = RSAUtil.encrypt(encBankAcctNo.getBytes(), pub, 2048, 11, rsa);
// 对银行账号进行加密
encBankAcctNo = Base64.encode(estr);// 并转为base64格式
estr = RSAUtil.encrypt(encBankAcctName.getBytes(“UTF-8”), pub, 2048, 11, rsa);
encBankAcctName = Base64.encode(estr); // 对银行账户名加密并转为base64
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
//根据要传递的参数生成自己的签名
TreeMap<String, String> parameters1 = new TreeMap<String, String>();
parameters1.put(“mch_id”, mch_id);// 商户号
parameters1.put(“partner_trade_no”, partner_trade_no);// 商户企业付款单号
parameters1.put(“nonce_str”, nonce_str1);// 随机字符串
parameters1.put(“enc_bank_no”, encBankAcctNo);// 收款方银行卡号
parameters1.put(“enc_true_name”, encBankAcctName);// 收款方用户名
parameters1.put(“bank_code”, bank_code);// 收款方开户行
parameters1.put(“amount”, amount);// 付款金额
parameters1.put(“desc”, desc);// 付款说明
// 调用签名方法
String sign = SignUtils.creatSign(“utf-8”, parameters1);
// 把签名放到map集合中
parameters1.put(“sign”, sign);// 签名
// 将当前的map结合转化成xml格式
String reuqestXml = XMLParser.getRequestXml(parameters1);
// 发送请求到企业付款到银行的Api。发送请求是一个方法来的POST
String wxUrl = “https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank”; // 获取退款的api接口
EnterpriceToCustomer enterpriceToCustomer = null;
try {
// 调用方法发送了
String weixinPost = ClientCustomSSL.doRefund(wxUrl, reuqestXml).toString();
System.out.println(weixinPost);
// 解析返回的xml数据
enterpriceToCustomer = EnterpriceToCustomer
.parseXmlToMapEnterpriceToCustomer(weixinPost);
System.out.println(enterpriceToCustomer);
// 根据map中的result_code AND return_code来判断是否成功与失败
if (“SUCCESS”.equalsIgnoreCase(enterpriceToCustomer.getResult_code())
&& “SUCCESS”.equalsIgnoreCase(enterpriceToCustomer.getReturn_code())) {
System.out.println(“退款成功!”);
} else {
//退款失败
System.err.println(enterpriceToCustomer.getErr_code_des());
}
} catch (Exception e) {
e.printStackTrace();
}
return enterpriceToCustomer;
}
// 生成RSA公钥,格式PKCS#1,需要转成PKCS#8格式 在线转换工具:http://www.ssleye.com/web/pkcs
public void getPublicKey() throws Exception {
TreeMap<String, String> parameters = new TreeMap<String, String>();
String nonce_str = RandomStringUtils.randomAlphanumeric(28);
parameters.put(“mch_id”, “商户id”);
parameters.put(“nonce_str”, nonce_str);
parameters.put(“sign_type”, “MD5”);
String sign = SignUtils.creatSign(“utf-8”, parameters); // 签名
/* String sign = SignUtils.creatSign(WxSDKConfig.getAppSecret(), parameters); */
System.out.println(sign);
parameters.put(“sign”, sign); // 5.0将当前的map结合转化成xml格式
String reuqestXml = XMLParser.getRequestXml(parameters);
// 带证书请求
String xml1 = HttpClientCustomSSL.httpClientResultGetPublicKey(reuqestXml); //
String publicKey = XMLParser.Progress_resultParseXml(xml1);
System.out.println(publicKey);
}
public static void main(String[] args) {
// 1~拼凑所需要传递的参数 map集合 ->查看API,传入参数哪些是必须的
String encBankAcctNo = “银行账号”; // 加密的银行账号
String encBankAcctName = “姓名”; // 加密的银行账户名
String bank_code = “1002”; // 银行卡的编号~
String desc = “测试提现到账通知”;// 转账描述
String amount = “1”; // 付款金额,单位是分
try {
WXPayToBC(encBankAcctNo, encBankAcctName, bank_code, desc, amount);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class RSAUtil
{
private static final String PKSC8_PUBLIC = “生成的公钥”;
public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {
int keyByteSize = keyLength / 8;
int decryptBlockSize = keyByteSize - reserveSize;
int nBlock = encryptedBytes.length / keyByteSize;
ByteArrayOutputStream outbuf = null;
try {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
outbuf = new ByteArrayOutputStream(nBlock * decryptBlockSize);
for (int offset = 0; offset < encryptedBytes.length; offset += keyByteSize) {
int inputLen = encryptedBytes.length - offset;
if (inputLen > keyByteSize) {
inputLen = keyByteSize;
}
byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, inputLen);
outbuf.write(decryptedBlock);
}
outbuf.flush();
return outbuf.toByteArray();
} catch (Exception e) {
throw new Exception("DEENCRYPT ERROR:", e);
} finally {
try{
if(outbuf != null){
outbuf.close();
}
}catch (Exception e){
outbuf = null;
throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);
}
}
}
public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {
int keyByteSize = keyLength / 8;
int encryptBlockSize = keyByteSize - reserveSize;
int nBlock = plainBytes.length / encryptBlockSize;
if ((plainBytes.length % encryptBlockSize) != 0) {
nBlock += 1;
}
ByteArrayOutputStream outbuf = null;
try {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
outbuf = new ByteArrayOutputStream(nBlock * keyByteSize);
for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {
int inputLen = plainBytes.length - offset;
if (inputLen > encryptBlockSize) {
inputLen = encryptBlockSize;
}
byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);
outbuf.write(encryptedBlock);
}
outbuf.flush();
return outbuf.toByteArray();
} catch (Exception e) {
throw new Exception("ENCRYPT ERROR:", e);
} finally {
try{
if(outbuf != null){
outbuf.close();
}
}catch (Exception e){
outbuf = null;
throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);
}
}
}
public static PrivateKey getPriKey(String privateKeyPath,String keyAlgorithm){
PrivateKey privateKey = null;
InputStream inputStream = null;
try {
if(inputStream==null){
System.out.println("hahhah1!");
}
inputStream = new FileInputStream(privateKeyPath);
System.out.println("hahhah2!");
privateKey = getPrivateKey(inputStream,keyAlgorithm);
System.out.println("hahhah3!");
} catch (Exception e) {
System.out.println("加载私钥出错!");
} finally {
if (inputStream != null){
try {
inputStream.close();
}catch (Exception e){
System.out.println("加载私钥,关闭流时出错!");
}
}
}
return privateKey;
}
/*public static PublicKey getPubKey(String publicKeyPath,String keyAlgorithm){
PublicKey publicKey = null;
InputStream inputStream = null;
try
{
System.out.println("getPubkey 1......");
inputStream = new FileInputStream(publicKeyPath);
System.out.println("getPubkey 2......");
publicKey = getPublicKey(inputStream,keyAlgorithm);
System.out.println("getPubkey 3......");
} catch (Exception e) {
e.printStackTrace();//EAD PUBLIC KEY ERROR
System.out.println("加载公钥出错!");
} finally {
if (inputStream != null){
try {
inputStream.close();
}catch (Exception e){
System.out.println("加载公钥,关闭流时出错!");
}
}
}
return publicKey;
} */
public static PublicKey getPublicKey(String keyAlgorithm) throws Exception {
try
{
/*System.out.println("b1.........");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("b2.........");
StringBuilder sb = new StringBuilder();
String readLine = null;
System.out.println("b3.........");
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
System.out.println("b4.........");*/
//加载公钥
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(decodeBase64(PKSC8_PUBLIC));
/*//读取公钥
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(decodeBase64(sb.toString())); */
System.out.println("b5.........");
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
System.out.println("b6.........");
//下行出错 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=127, too big.
PublicKey publicKey = keyFactory.generatePublic(pubX509);
System.out.println("b7.........");
return publicKey;
} catch (Exception e) {
e.printStackTrace();
System.out.println("b8.........");
throw new Exception("READ PUBLIC KEY ERROR:", e);
} /*finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
inputStream = null;
throw new Exception("INPUT STREAM CLOSE ERROR:", e);
}
} */
}
public static PrivateKey getPrivateKey(InputStream inputStream, String keyAlgorithm) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
System.out.println("hahhah4!"+decodeBase64(sb.toString()));
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decodeBase64(sb.toString()));
System.out.println("hahhah5!");
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
System.out.println("hahhah6!");
PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
System.out.println("hahhah7!");
return privateKey;
} catch (Exception e) {
throw new Exception("READ PRIVATE KEY ERROR:" ,e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
inputStream = null;
throw new Exception("INPUT STREAM CLOSE ERROR:", e);
}
}
}
//一下面是base64的编码和解码
public static String encodeBase64(byte[]input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, new Object[]{input});
return (String)retObj;
}
/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, input);
return (byte[])retObj;
}
}
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.shineyoo.manager.util.common.pay.MD5Util;
import com.shineyoo.manager.util.common.pay.WxSDKConfig;
/**
-
签名工具类
-
@author
-
@date 2018年09月3日
-
*/
public class SignUtils {/**
- @param characterEncoding 编码格式 utf-8
- */
public static String creatSign(String characterEncoding,
TreeMap<String, String> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !“sign”.equals(k) && !“key”.equals(k)) {
sb.append(k + “=” + v + “&”);
}
}
sb.append(“key=” + WxSDKConfig.getApiKey());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
System.out.println(sign);
return sign;
}
}
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
public class XMLParser {
/**
* 日志
* @return
*/
public static Logger getLogger() {
Logger logger = LoggerFactory.getLogger("wxpay java sdk");
return logger;
}
public static String getRequestXml(TreeMap<String, String> parameters)
throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("mch_id".equalsIgnoreCase(k) || "nonce_str".equalsIgnoreCase(k)
|| "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
public static String Progress_resultParseXml(String xml) {
String publicKey = null;
try {
StringReader read = new StringReader(xml);
InputSource source = new InputSource(read);
SAXBuilder sb = new SAXBuilder();
org.jdom.Document doc;
doc = (org.jdom.Document) sb.build(source);
org.jdom.Element root = doc.getRootElement();
List<org.jdom.Element> list = root.getChildren();
if (list != null && list.size() > 0) {
for (org.jdom.Element element : list) {
if("pub_key".equals(element.getName())){
publicKey=element.getText();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return publicKey;
}
}
import java.security.MessageDigest;
public class MD5Util {
public static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance(“MD5”);
if (charsetname == null || “”.equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { “0”, “1”, “2”, “3”, “4”, “5”,
“6”, “7”, “8”, “9”, “a”, “b”, “c”, “d”, “e”, “f” };
}
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.common.io.Resources;
//import codeGenerate.util.ConfProperties;
/**
-
This example demonstrates how to create secure connections with a custom SSL
-
context.
*/
public class ClientCustomSSL {public static String doRefund(String url,String data) throws Exception {
/**
* 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的
*/KeyStore keyStore = KeyStore.getInstance("PKCS12"); // FileInputStream instream = new FileInputStream(new File(WxSDKConfig.getRefundSSLFile()));//P12文件目录 BufferedInputStream instream = (BufferedInputStream) Resources.getResource(WxSDKConfig.getRefundSSLFile()).getContent(); try { /** * 此处要改 * */ keyStore.load(instream, WxSDKConfig.getMchId().toCharArray());//这里写密码..默认是你的MCHID } finally { instream.close(); } // Trust own CA and all self-signed certs /** * 此处要改 * */ SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(keyStore, WxSDKConfig.getMchId().toCharArray())//这里也是写密码的 .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); 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(); }
}
}
//不通用的、返回Bean格式
//以企业付款到零钱为例子~~根据Api会返回的参数,书写一个Bean类型
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
/**
*
- 企业 付款到 客户 的 实体类
- @version 1.0
- @description: 收集企业 支付给客户成功后的返回信息
- @time : 2018-01-16 16:00:00
/
public class EnterpriceToCustomer {
/
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[]]></return_msg>
<![CDATA[1488323162]]>
<nonce_str><![CDATA[o9fcpfvqow1aks48a2omvayu1ne7c709]]></nonce_str>
<result_code><![CDATA[SUCCESS]]></result_code>
<partner_trade_no><![CDATA[xvuct0087w4t1dpr87iqj98w5f71ljae]]></partner_trade_no>
<payment_no><![CDATA[1000018301201801163213961289]]></payment_no>
<payment_time><![CDATA[2018-01-16 14:52:16]]></payment_time>
*/
private String return_code;
private String return_msg;
private String mch_id;
private String nonce_str;
private String result_code;
private String partner_trade_no;
private String payment_no;
private String payment_time;
/*
- 支付错误时,返回的代码
- key是:return_code,值是:SUCCESS
key是:return_msg,值是:支付失败
key是:mch_appid,值是:wx49c22ad731b679c3
key是:mchid,值是:1488323162
key是:result_code,值是:FAIL
key是:err_code,值是:AMOUNT_LIMIT
key是:err_code_des,值是:付款金额超出限制。低于最小金额1.00元或累计超过20000.00元。
*/
private String err_code;
private String err_code_des;
public String getErr_code() {
return err_code;
}
public void setErr_code(String errCode) {
err_code = errCode;
}
public String getErr_code_des() {
return err_code_des;
}
public void setErr_code_des(String errCodeDes) {
err_code_des = errCodeDes;
}
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String returnCode) {
return_code = returnCode;
}
public String getReturn_msg() {
return return_msg;
}
public void setReturn_msg(String returnMsg) {
return_msg = returnMsg;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonceStr) {
nonce_str = nonceStr;
}
public String getResult_code() {
return result_code;
}
public void setResult_code(String resultCode) {
result_code = resultCode;
}
public String getPartner_trade_no() {
return partner_trade_no;
}
public void setPartner_trade_no(String partnerTradeNo) {
partner_trade_no = partnerTradeNo;
}
public String getPayment_no() {
return payment_no;
}
public void setPayment_no(String paymentNo) {
payment_no = paymentNo;
}
public String getPayment_time() {
return payment_time;
}
public void setPayment_time(String paymentTime) {
payment_time = paymentTime;
}
@Override
public String toString() {
return “EnterpriceToCustomer [err_code=” + err_code + “, err_code_des=”
+ err_code_des + “, mch_id=” + mch_id + “, nonce_str=”
+ nonce_str + “, partner_trade_no=” + partner_trade_no
+ “, payment_no=” + payment_no + “, payment_time=”
+ payment_time + “, result_code=” + result_code
+ “, return_code=” + return_code + “, return_msg=” + return_msg
+ “]”;
}
/**
下面是需要通过跟节点,找找到对应的类属性,手动把它set进去。因此API返回的参数不一样。需要写每个返回的Bean。看个人的习惯呗~~我喜欢用bean存储数据的方式
* 解析企业支付申请
* 解析的时候自动去掉CDMA
* @param xml
*/
@SuppressWarnings(“unchecked”)
public static EnterpriceToCustomer parseXmlToMapEnterpriceToCustomer(String xml){
EnterpriceToCustomer enterpriceToCustomer = new EnterpriceToCustomer();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc;
doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
List<Element> list = root.getChildren();
if(list!=null&&list.size()>0){
for (Element element : list) {
System.out.println("key是:"+element.getName()+",值是:"+element.getText());
if("return_code".equals(element.getName())){
enterpriceToCustomer.setReturn_code(element.getText());
}
if("return_msg".equals(element.getName())){
enterpriceToCustomer.setReturn_msg(element.getText());
}
if("mch_id".equals(element.getName())){
enterpriceToCustomer.setMch_id(element.getText());
}
if("nonce_str".equals(element.getName())){
enterpriceToCustomer.setNonce_str(element.getText());
}
if("result_code".equals(element.getName())){
enterpriceToCustomer.setResult_code(element.getText());
}
if("partner_trade_no".equals(element.getName())){
enterpriceToCustomer.setPartner_trade_no(element.getText());
}
if("payment_no".equals(element.getName())){
enterpriceToCustomer.setPayment_no(element.getText());
}
if("payment_time".equals(element.getName())){
enterpriceToCustomer.setPayment_time(element.getText());
}
//错误的编码
/*
private String err_code;
private String err_code_des;
* */
if("err_code".equals(element.getName())){
enterpriceToCustomer.setErr_code(element.getText());
}
if("err_code_des".equals(element.getName())){
enterpriceToCustomer.setErr_code_des(element.getText());
}
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return enterpriceToCustomer;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import com.shineyoo.manager.util.common.pay.WxSDKConfig;
/**
- 读取证书
*/
@SuppressWarnings(“deprecation”)
public class ReadSSl {
private static ReadSSl readSSL = null;
private ReadSSl(){
}
public static ReadSSl getInstance(){
if(readSSL == null){
readSSL = new ReadSSl();
}
return readSSL;
}
/**
-
读取 apiclient_cert.p12 证书
-
@return
-
@throws Exception
*/
public SSLConnectionSocketFactory readCustomSSL() throws Exception{
KeyStore keyStore = KeyStore.getInstance(“PKCS12”);
FileInputStream instream = new FileInputStream(new File(WxSDKConfig.getRefundSSLFile()));//P12文件目录
try {
keyStore.load(instream, WxSDKConfig.getMchId().toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxSDKConfig.getMchId().toCharArray()).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); return sslsf;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClientCustomSSL {
/**
* 发送公钥的http请求以及企业支付到银行卡的http请求
*
*/
public static String httpClientResultGetPublicKey(String xml) throws Exception {
StringBuffer reultBuffer = new StringBuffer();
SSLConnectionSocketFactory sslsf = ReadSSl.getInstance().readCustomSSL();
HttpPost httpPost = new HttpPost("https://fraud.mch.weixin.qq.com/risk/getpublickey");
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
StringEntity myEntity = new org.apache.http.entity.StringEntity(xml, "UTF-8");
myEntity.setContentType("text/xml;charset=UTF-8");
myEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
httpPost.setEntity(myEntity);
CloseableHttpResponse response = null;
java.io.InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
reultBuffer.append(str);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.close();
response.close();
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
}
return reultBuffer.toString();
}
}