1. 程式人生 > >Java專案呼叫微信支付到指定銀行卡

Java專案呼叫微信支付到指定銀行卡

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();

}
}