简介:
微信商户转账到个人银行卡需要单独申请该功能,
满足条件:商户开通90天,商户流水1个月。
备注:如果在开发这之前有开发过微信支付,则不需要配置任何东西,如果没有开发过微信支付,则需要在微信商户端配置私钥,下载ca证书等。(没有开发过支付,则百度搜索支付配置一系列。)
难点:
1:获取公钥(pkcs1)
2:转换pkcs8(java)
3:公钥加密
4:所有请求到微信都是https,如果http请求,则会抛出443 无响应
备注:商户转账银行卡,需要将银行卡卡号和真实姓名加密
我用的是ssm框架。该功能已测试成功,并上线到真实环境(阿里云服务器)。转账功能是T+1。
以下是Java代码:
WXPayUtil:该类是之前做微信支付时微信提供的demo类。可以去拷贝进来。如果没有,则可以看我之前的文档,里面有提供微信支付damo链接
/**
* 微信支付常量
* @author think
*/
public class WXPayCommonPath {
public static final String WXUNIFIEDORDER_HTTPURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";// 微信统一下单接口
public static final String APP_ID = "";// 微信appid
public static final String MCH_ID = "";// 商户号
public static final String API_KEY = "";// apikey应用私钥 api密钥
public static final String SPBILL_CREATE_IP = "";//服务器ip
/**微信商户转个人银行卡公钥*/
public static final String PUB_KEY = "";
/**微信商户转个人银行卡公钥 PKCS8*/
public static final String PRI_KEY = "";
}
1:先获取公钥(pkcs1)
@RequestMapping(value="createResSign",method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public Map<String, Object> createResSign(HttpServletRequest req,
HttpServletResponse res){
res.setCharacterEncoding("UTF-8");
try {
GetPublicKey getPublicKey = new GetPublicKey();
System.out.println(getPublicKey.getPublicKey());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return JsonMethod.setJsonMethod(PathKeyEnum.ERROR.getKey(), PathKeyEnum.ERROR.getValue(), PathCommonEnum.ERROR.getValue());
}
/**
* 获取商户公钥
* @author think
*/
public class GetPublicKey {
public String getPublicKey() throws Exception {
TreeMap<String, String> tmap = new TreeMap<String, String>();
tmap.put("mch_id", WXPayCommonPath.MCH_ID);
tmap.put("nonce_str", WXPayUtil.generateNonceStr());
tmap.put("sign_type", "MD5");
String sign = WXPayUtil.generateSignature(tmap, WXPayCommonPath.API_KEY);
tmap.put("sign", sign);
String xml = XMLUtils.getRequestXml(tmap);//将请求参数转换为请求报文
//带证书请求
String xml1 = HttpClientCustomSSL.httpClientResultGetPublicKey(xml);//发送http的post请求获取公钥报文
String publicKey = XMLUtils.Progress_resultParseXml(xml1);//解析腾迅返回的公钥xml并获取公钥元素
return publicKey;
}
}
/**
* 将请求参数转换为请求报文和解析腾迅返回的公钥xml并获取公钥元素
*
* @author think
*/
public class XMLUtils {
@SuppressWarnings("rawtypes") // 去除警告
public static String getRequestXml(Map<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();
}
/**
* 解析腾迅返回的公钥xml并获取公钥元素
* @param xml
* @return
*/
@SuppressWarnings("unchecked")
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();
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) {
if ("pub_key".equals(element.getName())) {
publicKey = element.getText();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return publicKey;
}
}
/**
* ssl请求
* @author think
*/
public class HttpClientCustomSSL {
/**
* httpClient 请求获取公钥
*
* @param parms
* @return @throws Exception
*/
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;
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();
}
/**
* httpClient 请求企业支付到银行卡
*
* @param parms
* @return @throws Exception
*/
public static String httpClientResultPANK(String xml) throws Exception {
StringBuffer reultBuffer = new StringBuffer();
SSLConnectionSocketFactory sslsf = ReadSSL.getInstance().readCustomSSL();
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank");
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;
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();
}
}
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("d:\\xx\\xx\\xx\\apiclient_cert.p12"));//这是ca证书,需要你自己到商户端下载,并保存在本地,(如果功能部署到服务器,则需要配置服务器路径)
try {
keyStore.load(instream, WXPayCommonPath.MCH_ID.toCharArray());
} catch(Exception e){
e.printStackTrace();
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WXPayCommonPath.MCH_ID.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
return sslsf;
}
}
以上功能获取到了公钥(pkcs1) 需要转成(pkcs8)
/**
* 用工具转成
* PKCS#1 转 PKCS#8:
* 工具:http://www.ssleye.com/web/pkcs
* 注意格式:
* -----BEGIN RSA PUBLIC KEY-----
* xxxx
* -----END RSA PUBLIC KEY-----
*/
注意转换时,begin end 这些一定要存在,否则会告诉你公钥错误。
获得pccs8公钥时保存到常量中。PRI_KEY
以上方法可以本地用浏览器去请求,则会打印出来,然后保存起来 在去 转换。
2:微信商户转账到银行卡
/**
* 微信提现到银行卡
* @param req
* @param res
* @return
*/
@OperLog(logDescription="微信提现到银行卡")
@RequestMapping(value="wxWithdrawal",method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public Map<String, Object> wxWithdrawal(HttpServletRequest req,
HttpServletResponse res){
res.setCharacterEncoding("UTF-8");
String codeNum = req.getParameter("codeNum");
String userName = req.getParameter("userName");
String price = req.getParameter("price");
if(StringUtils.isNullString(codeNum) ||
StringUtils.isNullString(userName) ||
StringUtils.isNullString(price))
return JsonMethod.setJsonMethod(PathKeyEnum.PARAMERROR.getKey(), PathKeyEnum.PARAMERROR.getValue(), PathCommonEnum.ERROR.getValue());
try {
WxPayUtilConfig config = new WxPayUtilConfig();
Map<String, String> param = new HashMap<String, String>();
param.put("mch_id", config.getMchID());
//创建订单编号
param.put("partner_trade_no", CommonUtils.createNum());
param.put("nonce_str", WXPayUtil.generateNonceStr());
//银行卡号
param.put("enc_bank_no", GetRSA.getRSA(codeNum, WXPayCommonPath.PRI_KEY));
//收款方真实姓名
param.put("enc_true_name", GetRSA.getRSA(userName, WXPayCommonPath.PRI_KEY));
//这边要根据微信提供的银行卡名称更换成code码
param.put("bank_code", "1001");
//付款金额(即用户申请转账金额)
param.put("amount", String.valueOf((int)CommonUtils.mul(Double.parseDouble(price), 100.00)));
//签名
String sign = WXPayUtil.generateSignature(param,WXPayCommonPath.API_KEY);
param.put("sign", sign);
String xml = WXPayUtil.mapToXml(param);
String resultXml = HttpClientCustomSSL.httpClientResultPANK(xml);//发送请求
Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
if("SUCCESS" == resultMap.get("result_code")){
//执行成功之后,应该往数据库里插入一条提现转账数据。
return JsonMethod.setJsonMethod(PathKeyEnum.SUCCESS.getKey(), PathKeyEnum.SUCCESS.getValue(), PathCommonEnum.SUCCESS.getValue());
}
} catch (Exception e) {
// TODO: handle exception
LogComm.setLog("微信商户转个人银行卡抛出异常:" + e.getMessage());
}
return JsonMethod.setJsonMethod(PathKeyEnum.ERROR.getKey(), PathKeyEnum.ERROR.getValue(), PathCommonEnum.ERROR.getValue());
}
WxPayUtilConfig :这是写微信支付时,demo提供的conf
/**
* 对银行卡卡号,真实姓名加密
* @author think
*/
public class GetRSA {
public static String getRSA(String str,String publicKeyPKCS8) throws Exception {
byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(publicKeyPKCS8),str.getBytes("UTF-8"));
String cipher = Base64Util.encode(cipherData);
return cipher;
}
}
/**
* Base64 工具类
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
private static final char[] encodeTable = new char[]{'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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}
public class RSAEncrypt {
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
try {
byte[] buffer = Base64.decodeBase64(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
throw new Exception("出错了");
}
}
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) {
throw new Exception("");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return output;
} catch (Exception e) {
throw new Exception("出错了");
}
}
public static void main(String[] args) {
try {
//System.out.println(encrypt(WXPayCommonPath.PUB_KEY),"");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
代码功能已经全部完成
备注:如果微信商户配置的ip是服务器的,则本地执行该方法微信会返回失败,因为ip不一致,可以将功能部署到服务器上,然后在执行,则ok
以上所有功能,百度+微信文档开发出来,如各位测试有问题,可以底部留言。互相学习。