微信企業付款到零錢(微信提現)
阿新 • • 發佈:2019-01-04
由於專案中要用到微信提現,參考網上程式碼和官方文件寫了提現的工具類
用到的相關類庫
dom4j
commons-lang3
httpclient-4.4.1
具體相關流程可以看微信企業付款到零錢的開發文件
MD5工具類
package com.kk.wechatextract;
import java.security.MessageDigest;
public class MD5Utils {
private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' , 'a', 'b', 'c', 'd', 'e', 'f'};
/*
* 先轉為utf-8
* */
public static String MD5Encoding(String s) {
byte[] btInput = null;
try {
btInput = s.getBytes("UTF-8");
}catch (Exception e){
}
return MD5(btInput, 32);
}
public static String MD5 (String s) {
byte[] btInput = s.getBytes();
return MD5(btInput, 32);
}
public static String MD5_16(String str) {
byte[] btInput = str.getBytes();
return MD5(btInput, 16);
}
private static String MD5(byte[] btInput, int length) {
try {
// 獲得MD5摘要演算法的 MessageDigest 物件
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// MessageDigest mdInst = MessageDigest.getInstance("SHA-1");
// 使用指定的位元組更新摘要
mdInst.update(btInput);
// 獲得密文
byte[] md = mdInst.digest();
// 把密文轉換成十六進位制的字串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
String result = new String(str);
return length == 16 ? result.substring(8, 24) : result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
url排序,隨機字串的操作
package com.kk.wechatextract;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OtherUtils {
/*
* 生成32位隨機字串
* */
public static String getNonceStr() {
UUID uuid = UUID.randomUUID();
return uuid.toString().replace("-", "");
}
/**
* 方法用途: 對所有傳入引數按照欄位名的Unicode碼從小到大排序(字典序),並且生成url引數串<br>
* 實現步驟: <br>
*
* @param paraMap 要排序的Map物件
* @param urlEncode 是否需要URLENCODE
* @param keyToLower 是否需要將Key轉換為全小寫
* true:key轉化成小寫,false:不轉化
* @return
*/
public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
String buff = "";
Map<String, String> tmpMap = paraMap;
try {
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
// 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序)
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
// 構造URL 鍵值對的格式
StringBuilder buf = new StringBuilder();
for (Map.Entry<String, String> item : infoIds) {
if (StringUtils.isNotBlank(item.getKey())) {
String key = item.getKey();
String val = item.getValue();
if (urlEncode) {
val = URLEncoder.encode(val, "utf-8");
}
if (keyToLower) {
buf.append(key.toLowerCase() + "=" + val);
} else {
buf.append(key + "=" + val);
}
buf.append("&");
}
}
buff = buf.toString();
if (buff.isEmpty() == false) {
buff = buff.substring(0, buff.length() - 1);
}
} catch (Exception e) {
return null;
}
return buff;
}
/**
* 功能描述: 判斷值是否為double
*/
public static boolean isToDouble(Object o){
try {
Double.valueOf(o.toString());
return true;
}catch (Exception e){
return false;
}
}
/**
* @param xml
* @return Map
* @description 將xml字串轉換成map
*/
public static Map<String, String> readStringXmlOut(String xml) {
Map<String, String> map = new HashMap<String, String>();
Document doc = null;
try {
doc = DocumentHelper.parseText(xml); // 將字串轉為XML
Element rootElt = doc.getRootElement(); // 獲取根節點
@SuppressWarnings("unchecked")
List<Element> list = rootElt.elements();// 獲取根節點下所有節點
for (Element element : list) { // 遍歷節點
map.put(element.getName(), element.getText()); // 節點的name為map的key,text為map的value
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
微信提現主方法
package com.kk.wechatextract;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author Zhou Zhong Qing
* @Title: ${file_name}
* @Package ${package_name}
* @Description: 微信提現
*/
@Component
public class WeChatWithdrawUtils {
private static final Logger log = LoggerFactory.getLogger(WeChatWithdrawUtils.class.getName());
private byte[] certData;
/**
* 載入證書
*/
public InputStream getCertStream() {
ByteArrayInputStream certBis;
certBis = new ByteArrayInputStream(this.certData);
return certBis;
}
/**
*讀取證書
*/
public WeChatWithdrawUtils() throws Exception{
String certPath = Constant.SSLCERT_PATH;
File file = new File(certPath);
InputStream certStream = new FileInputStream(file);
this.certData = new byte[(int) file.length()];
certStream.read(this.certData);
certStream.close();
}
/**
*
* 提現
* 請求,只請求一次,不做重試
* @param connectTimeoutMs
* @param readTimeoutMs
* @return
* @throws Exception
*/
public static String withdrawRequestOnce(Map<String,String> params, int connectTimeoutMs, int readTimeoutMs,boolean useCert) throws Exception {
/**1.拼湊企業支付需要的引數**/
Map<String, String> paraMap = new HashMap<>();
paraMap.putAll(params);
//微信公眾號的appid
paraMap.put("mch_appid", Constant.APPID);
//商戶號
paraMap.put("mchid",Constant.MERCHANTID);
//隨機字串
//paraMap.put("nonce_str", OtherUtils.getNonceStr());
paraMap.get("nonce_str");
//訂單號
//paraMap.put("partner_trade_no","qianchen"+System.currentTimeMillis());
paraMap.get("partner_trade_no");
//openid
//paraMap.put("openid",params.getOrDefault("openId","oelSW0uBU233H5YM3dweIZ08kauk"));//"o5mZ40yBjIqco2NzKc19k9oIBI9o");
paraMap.get("openid");
// 校驗使用者姓名選項 NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名
paraMap.put("check_name","NO_CHECK");
//paraMap.put("amount",params.getOrDefault("money","0"));//"100");
paraMap.get("amount");
//企業付款操作說明資訊。必填。
//paraMap.put("desc",params.getOrDefault("clientId","")+"使用者提現");
paraMap.get("desc");
//ip地址,地址可以不是真實地址
paraMap.put("spbill_create_ip",params.getOrDefault("spbillCreateIp","127.0.01"));
/**2.Unicode碼從小到大排序**/
String url = OtherUtils.formatUrlMap(paraMap, false, false);
url = url + "&key=" + Constant.MERCHANTKEY;
/**3.用MD5加密生成簽名**/
String sign = MD5Utils.MD5Encoding(url).toUpperCase();
/**4.將map拼接成xml格式**/
StringBuffer xml = new StringBuffer();
xml.append("<xml>");
for (Map.Entry<String, String> entry : paraMap.entrySet()) {
xml.append("<" + entry.getKey() + ">");
xml.append(entry.getValue());
xml.append("</" + entry.getKey() + ">" + "\n");
}
xml.append("<sign>");
xml.append(sign);
xml.append("</sign>");
xml.append("</xml>");
log.info("xml {} ", xml.toString());
BasicHttpClientConnectionManager connManager;
/**5.操作證書**/
if (useCert) {
// 證書
char[] password = Constant.MERCHANTID.toCharArray();
InputStream certStream = new WeChatWithdrawUtils().getCertStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, password);
// 例項化金鑰庫 & 初始化金鑰工廠
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password);
// 建立 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1"},
null,
new org.apache.http.conn.ssl.DefaultHostnameVerifier());
connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build(),
null,
null,
null
);
}
else {
connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
}
org.apache.http.client.HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager)
.build();
/**傳送資訊到微信伺服器**/
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
/**設定超時時間**/
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEntity postEntity = new StringEntity(xml.toString(), "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + Constant.MERCHANTID); // TODO: 很重要,用來檢測 sdk 的使用情況,要不要加上商戶資訊?
httpPost.setEntity(postEntity);
/**傳送後返回支付結果,xml格式**/
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
}
微信提現測試
package com.kk.wechatextract;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* @author kk
* 微信提現
*/
public class WechatExtract {
public static void main(String[] args) throws Exception {
//提現金額(單位:元)
String result = "2";
Map<String, String> map = Maps.newHashMap();
//元轉換為分,微信支付已分為單位
BigDecimal sumAmount = new BigDecimal(result);
//乘以100,轉換為分
BigDecimal transAmt = sumAmount.multiply(new BigDecimal(100));
//訂單號
String Order = "F"+LocalDate.now().toString().replace("-", "")+LocalTime.now().toString().replace("-", "").replace(":","").replace(".", "");
//隨機字串
map.put("nonce_str",OtherUtils.getNonceStr().toString());
//openid("c從資料庫中查詢")
//map.put("openid",openid.get(0).getUserlevel());
map.put("openid","ocYeu0V9WccmTP9axyCp_tDscUN0");
//金額
map.put("amount",transAmt.toString());
////企業付款操作說明資訊
map.put("desc","提現測試");
//呼叫支付
String returnInfo = WeChatWithdrawUtils.withdrawRequestOnce(map,3000,3000,true);
Map<String,String> resultMap = OtherUtils.readStringXmlOut(returnInfo);
if(resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code",""))){
System.out.println("提現成功");
System.out.println("返回結果:"+returnInfo);
}else{
System.out.println("提現成功");
System.out.println("返回結果:"+returnInfo);
}
}
}
常量類
package com.kk.wechatextract;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class Constant {
//微信appid
public static final String APPID= "**********";
//微信商戶id
public static final String MERCHANTID = "**********";
//微信商戶祕鑰
public static final String MERCHANTKEY = "*****************";
public static final String APPSECRET = "*********************";
//證書路徑
public static final String SSLCERT_PATH = "***********";
}