本地開發環境支付回調調試方法可以參考:https://www.cnblogs.com/pxblog/p/11623053.html
需要自行引入相關依賴
官方文檔地址:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
用於企業向微信用戶個人付款,目前支持向指定微信用戶的openid付款。
官方提示
ClientCustomSSL.java
package com.weixinpay; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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 javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; /** * This example demonstrates how to create secure connections with a custom SSL * context. */ public class ClientCustomSSL { public static String getInSsl(String url,File pkcFile,String storeId, String params,String contentType) throws Exception { String text = ""; // 指定讀取證書格式為PKCS12 KeyStore keyStore = KeyStore.getInstance("PKCS12"); // 讀取本機存放的PKCS12證書文件 FileInputStream instream = new FileInputStream(pkcFile); try { // 指定PKCS12的密碼(商戶ID) keyStore.load(instream, storeId.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build(); // Allow TLSv1 protocol only // 指定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 { HttpPost post = new HttpPost(url); StringEntity s = new StringEntity(params,"utf-8"); if(StringUtils.isBlank(contentType)){ s.setContentType("application/xml"); } s.setContentType(contentType); post.setEntity(s); HttpResponse res = httpclient.execute(post); HttpEntity entity = res.getEntity(); text= EntityUtils.toString(entity, "utf-8"); } finally { httpclient.close(); } return text; } }
Num62.java
package com.weixinpay; /** * 62進制數字 */ public class Num62 { /** * 62個字母和數字,含大小寫 */ public static final char[] N62_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; }
PaymentConfig.java
package com.weixinpay; public class PaymentConfig { /*******微信支付參數*********/ //公眾賬號ID public static final String appid="wxd3e"; //密鑰 key設置路徑:微信商戶平台(pay.weixin.qq.com)-->賬戶設置-->API安全-->密鑰設置 public static final String appKey="abcde"; //商戶號 public static final String mch_id="15849"; //轉賬請求接口地址 public static final String pay_url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; }
PayUtil.java
package com.weixinpay; import org.apache.commons.lang.StringUtils; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.util.*; public class PayUtil { /** * UTF-8編碼 */ public static final String UTF8 = "UTF-8"; /** * 將需要傳遞給微信的參數轉成xml格式 * @param parameters * @return */ public static String assembParamToXml(Map<String,String> parameters){ StringBuffer sb = new StringBuffer(); sb.append("<xml>"); Set<String> es = parameters.keySet(); List<Object> list=new ArrayList<Object>(es); Object[] ary =list.toArray(); Arrays.sort(ary); list=Arrays.asList(ary); Iterator<Object> it = list.iterator(); while(it.hasNext()) { String key = (String) it.next(); String val=(String) parameters.get(key); if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) { sb.append("<"+key+">"+"<![CDATA["+val+"]]></"+key+">"); }else { sb.append("<"+key+">"+val+"</"+key+">"); } } sb.append("</xml>"); return sb.toString(); } /** * 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml數據。 * @param strxml * @return * @throws JDOMException * @throws IOException */ public static Map parseXMLToMap(String strxml) throws JDOMException, IOException { strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\""+UTF8+"\""); if(null == strxml || "".equals(strxml)) { return null; } Map m = new HashMap(); InputStream in = new ByteArrayInputStream(strxml.getBytes(UTF8)); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(in); Element root = doc.getRootElement(); List list = root.getChildren(); Iterator it = list.iterator(); while(it.hasNext()) { Element e = (Element) it.next(); String k = e.getName(); String v = ""; List children = e.getChildren(); if(children.isEmpty()) { v = e.getTextNormalize(); } else { v =PayUtil.getChildrenText(children); } m.put(k, v); } //關閉流 in.close(); return m; } /** * 獲取子結點的xml * @param children * @return String */ public static String getChildrenText(List children) { StringBuffer sb = new StringBuffer(); if(!children.isEmpty()) { Iterator it = children.iterator(); while(it.hasNext()) { Element e = (Element) it.next(); String name = e.getName(); String value = e.getTextNormalize(); List list = e.getChildren(); sb.append("<" + name + ">"); if(!list.isEmpty()) { sb.append(getChildrenText(list)); } sb.append(value); sb.append("</" + name + ">"); } } return sb.toString(); } /** * 微信支付簽名sign * @param param * @param key * @return */ public static String createSign(Map<String, String> param,String key){ //簽名步驟一:按字典排序參數 List list=new ArrayList(param.keySet()); Object[] ary =list.toArray(); Arrays.sort(ary); list=Arrays.asList(ary); String str=""; for(int i=0;i<list.size();i++){ str+=list.get(i)+"="+param.get(list.get(i)+"")+"&"; } //簽名步驟二:加上key str+="key="+key; //步驟三:加密並大寫 str=PayUtil.MD5Encode(str,"utf-8").toUpperCase(); return str; } public static String MD5Encode(String origin,String charsetName){ String resultString=null; try{ resultString=new String(origin); MessageDigest md=MessageDigest.getInstance("MD5"); if(StringUtils.isBlank(charsetName)){ resultString=byteArrayToHexString(md.digest(resultString.getBytes())); }else{ resultString=byteArrayToHexString(md.digest(resultString.getBytes(charsetName))); } }catch(Exception e){ } return resultString; } public static String byteArrayToHexString(byte b[]){ StringBuffer resultSb=new StringBuffer(); for(int i=0;i<b.length;i++){ resultSb.append(PayUtil.byteToHexString(b[i])); } return resultSb.toString(); } public static String byteToHexString(byte b){ int n=b; if(n<0){ n+=256; } int d1=n/16; int d2=n%16; return PayUtil.hexDigits[d1]+PayUtil.hexDigits[d2]; } public static final String hexDigits[]={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; /** * 元轉換為分 * @param amount */ public static String changeY2F(Double amount){ String currency = amount.toString(); int index = currency.indexOf("."); int length = currency.length(); Long amLong = 0l; if(index == -1){ amLong = Long.valueOf(currency+"00"); }else if(length - index >= 3){ amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", "")); }else if(length - index == 2){ amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0); }else{ amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00"); } return amLong.toString(); } }
WeixinPay.java
package com.weixinpay; import org.apache.commons.lang.RandomStringUtils; import java.io.File; import java.util.HashMap; import java.util.Map; public class WeixinPay { /** * 企業付款接口 用於企業向微信用戶個人付款 * 目前支持向指定微信用戶的openid付款。 * @param pkcFile 商戶證書文件 * @param orderNo 訂單編號 * @param weixinOpenId 要付款的用戶openid * @param realname 收款用戶姓名 * @param payAmount 轉賬金額 * @param desc 企業付款備注 * @param ip ip地址 * @return */ public static Object[] payToUser(File pkcFile, String orderNo, String weixinOpenId, String realname , Double payAmount, String desc, String ip) { Map<String, String> paramMap = new HashMap<String, String>(); // 公眾賬號appid[必填] paramMap.put("mch_appid", PaymentConfig.appid); // 微信支付分配的商戶號 [必填] paramMap.put("mchid", PaymentConfig.mch_id); // 終端設備號(門店號或收銀設備ID),注意:PC網頁或公眾號內支付請傳"WEB" [非必填] paramMap.put("device_info", "WEB"); // 隨機字符串,不長於32位。 [必填] paramMap.put("nonce_str", RandomStringUtils.random(16, Num62.N62_CHARS)); // 商戶訂單號,需保持唯一性[必填] paramMap.put("partner_trade_no", orderNo); // 商戶appid下,某用戶的openid[必填] paramMap.put("openid", weixinOpenId); //校驗用戶姓名選項 NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名 paramMap.put("check_name", "OPTION_CHECK"); //收款用戶姓名,如果check_name設置為FORCE_CHECK,則必填用戶真實姓名 paramMap.put("re_user_name", realname); // 企業付款金額,金額必須為整數 單位為分 [必填] paramMap.put("amount", PayUtil.changeY2F(payAmount)); // 企業付款描述信息 [必填] paramMap.put("desc", desc); // 調用接口的機器Ip地址[必填] paramMap.put("spbill_create_ip", ip); // 根據微信簽名規則,生成簽名 paramMap.put("sign", PayUtil.createSign(paramMap, PaymentConfig.appKey)); // 把參數轉換成XML數據格式 String xmlWeChat = PayUtil.assembParamToXml(paramMap); String resXml = ""; boolean postError = false; try { resXml = ClientCustomSSL.getInSsl(PaymentConfig.pay_url, pkcFile, PaymentConfig.mch_id , xmlWeChat, "application/xml"); } catch (Exception e1) { postError = true; e1.printStackTrace(); } Object[] result = new Object[2]; result[0] = postError; result[1] = resXml; return result; } }
商戶證書說明:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
控制器調用類
PayContoller.java
package com.weixinpay; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.io.File; import java.util.HashMap; import java.util.Map; @Controller public class PayContoller { /** * 企業付款到用戶個人微信 * 簡單demo 需要自行完善邏輯 * @return */ @RequestMapping(value = "/transfers") public String transfers() { File pkcFile = new File("商戶證書路徑"); String orderNo = "訂單編號 可以參考:https://www.cnblogs.com/pxblog/p/12818067.html"; String weixinOpenId = "用戶的openid 可以參考:https://www.cnblogs.com/pxblog/p/10542698.html"; String realname = "用戶的真實姓名"; //轉賬的金額 金額格式轉換可以參考 https://www.cnblogs.com/pxblog/p/13186037.html Double payAmount = 0.01; String desc = "企業付款備注"; String ip = "ip地址 可以參考:https://www.cnblogs.com/pxblog/p/13360768.html"; Object result[] = WeixinPay.payToUser(pkcFile, orderNo, weixinOpenId, realname, payAmount, desc, ip); String resXml = (String) result[1]; boolean postError = (Boolean) result[0]; if (!postError) { Map<String, String> map = new HashMap<String, String>(); try { map = PayUtil.parseXMLToMap(resXml); } catch (Exception e) { e.printStackTrace(); } String returnCode = map.get("return_code"); if (returnCode.equalsIgnoreCase("FAIL")) { //支付失敗 return map.get("return_msg"); } else if (returnCode.equalsIgnoreCase("SUCCESS")) { if (map.get("err_code") != null) { //支付失敗 return map.get("err_code_des"); } else if (map.get("result_code").equalsIgnoreCase( "SUCCESS")) { //支付成功 paymentNo:微信付款單號 payment_time:付款成功時間 String paymentNo = map.get("payment_no"); String payment_time = map.get("payment_time"); try { //如果是體現操作,在這里處理體現訂單的狀態,把狀態轉為提現成功 } catch (Exception e) { e.printStackTrace(); } return "返回到成功的頁面"; } } } return "返回通信失敗的錯誤頁面"; } }