企业付款到银行卡API~~

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaozhegaa/article/details/79115388

近日,在开发“微信企业付款到银行卡”的功能。第一次接触“付款到银行卡“这一块的业务,查询了很多的博客资料以及走了很多的弯路。也发现“企业付款到银行卡”分享的博客并不多。特地写了该博客,希望对你们有帮助。个人浅薄的见解
资料下载:目前资料已经删除了,之前有网友吐槽说:资料不全;也有很多网友加了我qq拿资,咨询怎么做,目前已经解答了有50多位网友的问题了,本人的精力有限,没办法顾及所有网友的问题,所以源码将不再开源。如果有需要加我qq:924155240。发个15~20块吃饭钱,可以把源码发给你+稍稍解答问题
在这里插入图片描述

在这里插入图片描述

一、企业付款到银行卡API
https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_2
二、开发准备
(1)证书的准备:java开发需要用到:apiclient_cert.p12证书的,在微信商户平台(pay.weixin.qq.com)–>账户设置–>API安全–>证书中下载的 。
这里写图片描述
【何时用到证书?】与支付不一样,企业支付功能在发送post请求的时候,需要加载自己的一个证书之后,带着证书去请求退款才可以。这里使用到证书–很多人不知道证书在哪里使用
(2)了解好数字签名 — 简单来解释,就是对自己要发送的数据进行加密处理、换句话说假如说你要传递A/B/C,就对这三者进行加密。初开发者的误区:不知道该加密什么数据、观看网上的博客胡乱进行签名,导致签名错误
【温馨提示:】数字签名是一般开发人员容易遇到的错误,记住“你没遇到数字签名错误,都不好意思说自己做过微信退款支付订单查询等功能”。
耐心解决就行

三、API截图解释
~ 接口说明 + 是否需要证书
这里写图片描述
~ 数字签名说明 – 记住一句话:对要传递的数据进行加密,你要传递什么就要签名什么

~ 证书说明
这里写图片描述
~ RSA加密公钥API
这里写图片描述
四、开发步骤如下
这里写图片描述
1、拼凑所需要传递的参数 map集合
2、对“收款方银行卡号”、“收款方用户名”进行“采用标准RSA算法”【付款到银行卡,这点最难】
3、根据要传递的参数生成自己的签名
4、把签名放到map集合中【因为签名也要传递过去,看API】
5、将当前的map结合转化成xml格式
6、发送请求到企业付款到银行的Api。发送请求是一个方法来的POST
7、解析返回的xml数据===》map集合
8、根据map中的result_code AND return_code来判断是否成功与失败
【注意:】这里有个很难很难的点就是RSA加密,在这里花费了很长的时间。特地贴出来跟大家讲一下
五、分步解决问题
第一个难点:获取公钥,并且转化成PSCK#8格式,详细过程参考下面这篇文章
http://blog.csdn.net/xiaozhegaa/article/details/79125430

第二个难点就是:RSA的加密、base的 加密。一般常见的加密有DEC加密、RSA加密、MD5加密、盐值加密等、有时间会写几篇加密的算法。这里给大家介绍贴出来两个工具类~~以下两个很长,可以不看。直接贴过去

package com.fh.util.weixin;

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;

import com.fh.util.weixin.Base64;
import com.fh.util.weixin.RSASignature;

public class RSAUtil 
{

   
    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(InputStream inputStream, 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(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;    
        }    
  
}

package com.fh.util.weixin;
public final class Base64 {  
	  
    static private final int     BASELENGTH           = 128;  
    static private final int     LOOKUPLENGTH         = 64;  
    static private final int     TWENTYFOURBITGROUP   = 24;  
    static private final int     EIGHTBIT             = 8;  
    static private final int     SIXTEENBIT           = 16;  
    static private final int     FOURBYTE             = 4;  
    static private final int     SIGN                 = -128;  
    static private final char    PAD                  = '=';  
    static private final boolean fDebug               = false;  
    static final private byte[]  base64Alphabet       = new byte[BASELENGTH];  
    static final private char[]  lookUpBase64Alphabet = new char[LOOKUPLENGTH];  
  
    static {  
        for (int i = 0; i < BASELENGTH; ++i) {  
            base64Alphabet[i] = -1;  
        }  
        for (int i = 'Z'; i >= 'A'; i--) {  
            base64Alphabet[i] = (byte) (i - 'A');  
        }  
        for (int i = 'z'; i >= 'a'; i--) {  
            base64Alphabet[i] = (byte) (i - 'a' + 26);  
        }  
  
        for (int i = '9'; i >= '0'; i--) {  
            base64Alphabet[i] = (byte) (i - '0' + 52);  
        }  
  
        base64Alphabet['+'] = 62;  
        base64Alphabet['/'] = 63;  
  
        for (int i = 0; i <= 25; i++) {  
            lookUpBase64Alphabet[i] = (char) ('A' + i);  
        }  
  
        for (int i = 26, j = 0; i <= 51; i++, j++) {  
            lookUpBase64Alphabet[i] = (char) ('a' + j);  
        }  
  
        for (int i = 52, j = 0; i <= 61; i++, j++) {  
            lookUpBase64Alphabet[i] = (char) ('0' + j);  
        }  
        lookUpBase64Alphabet[62] = (char) '+';  
        lookUpBase64Alphabet[63] = (char) '/';  
  
    }  
  
    private static boolean isWhiteSpace(char octect) {  
        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);  
    }  
  
    private static boolean isPad(char octect) {  
        return (octect == PAD);  
    }  
  
    private static boolean isData(char octect) {  
        return (octect < BASELENGTH && base64Alphabet[octect] != -1);  
    }  
  
    /** 
     * Encodes hex octects into Base64 
     * 
     * @param binaryData Array containing binaryData 
     * @return Encoded Base64 array 
     */  
    public static String encode(byte[] binaryData) {  
  
        if (binaryData == null) {  
            return null;  
        }  
  
        int lengthDataBits = binaryData.length * EIGHTBIT;  
        if (lengthDataBits == 0) {  
            return "";  
        }  
  
        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;  
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;  
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;  
        char encodedData[] = null;  
  
        encodedData = new char[numberQuartet * 4];  
  
        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;  
  
        int encodedIndex = 0;  
        int dataIndex = 0;  
        if (fDebug) {  
            System.out.println("number of triplets = " + numberTriplets);  
        }  
  
        for (int i = 0; i < numberTriplets; i++) {  
            b1 = binaryData[dataIndex++];  
            b2 = binaryData[dataIndex++];  
            b3 = binaryData[dataIndex++];  
  
            if (fDebug) {  
                System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);  
            }  
  
            l = (byte) (b2 & 0x0f);  
            k = (byte) (b1 & 0x03);  
  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);  
  
            if (fDebug) {  
                System.out.println("val2 = " + val2);  
                System.out.println("k4   = " + (k << 4));  
                System.out.println("vak  = " + (val2 | (k << 4)));  
            }  
  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];  
        }  
  
        // form integral number of 6-bit groups  
        if (fewerThan24bits == EIGHTBIT) {  
            b1 = binaryData[dataIndex];  
            k = (byte) (b1 & 0x03);  
            if (fDebug) {  
                System.out.println("b1=" + b1);  
                System.out.println("b1<<2 = " + (b1 >> 2));  
            }  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];  
            encodedData[encodedIndex++] = PAD;  
            encodedData[encodedIndex++] = PAD;  
        } else if (fewerThan24bits == SIXTEENBIT) {  
            b1 = binaryData[dataIndex];  
            b2 = binaryData[dataIndex + 1];  
            l = (byte) (b2 & 0x0f);  
            k = (byte) (b1 & 0x03);  
  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];  
            encodedData[encodedIndex++] = PAD;  
        }  
  
        return new String(encodedData);  
    }  
  
    /** 
     * Decodes Base64 data into octects 
     * 
     * @param encoded string containing Base64 data 
     * @return Array containind decoded data. 
     */  
    public static byte[] decode(String encoded) {  
  
        if (encoded == null) {  
            return null;  
        }  
  
        char[] base64Data = encoded.toCharArray();  
        // remove white spaces  
        int len = removeWhiteSpace(base64Data);  
  
        if (len % FOURBYTE != 0) {  
            return null;//should be divisible by four  
        }  
  
        int numberQuadruple = (len / FOURBYTE);  
  
        if (numberQuadruple == 0) {  
            return new byte[0];  
        }  
  
        byte decodedData[] = null;  
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;  
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;  
  
        int i = 0;  
        int encodedIndex = 0;  
        int dataIndex = 0;  
        decodedData = new byte[(numberQuadruple) * 3];  
  
        for (; i < numberQuadruple - 1; i++) {  
  
            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))  
                || !isData((d3 = base64Data[dataIndex++]))  
                || !isData((d4 = base64Data[dataIndex++]))) {  
                return null;  
            }//if found "no data" just return null  
  
            b1 = base64Alphabet[d1];  
            b2 = base64Alphabet[d2];  
            b3 = base64Alphabet[d3];  
            b4 = base64Alphabet[d4];  
  
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
        }  
  
        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {  
            return null;//if found "no data" just return null  
        }  
  
        b1 = base64Alphabet[d1];  
        b2 = base64Alphabet[d2];  
  
        d3 = base64Data[dataIndex++];  
        d4 = base64Data[dataIndex++];  
        if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters  
            if (isPad(d3) && isPad(d4)) {  
                if ((b2 & 0xf) != 0)//last 4 bits should be zero  
                {  
                    return null;  
                }  
                byte[] tmp = new byte[i * 3 + 1];  
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);  
                return tmp;  
            } else if (!isPad(d3) && isPad(d4)) {  
                b3 = base64Alphabet[d3];  
                if ((b3 & 0x3) != 0)//last 2 bits should be zero  
                {  
                    return null;  
                }  
                byte[] tmp = new byte[i * 3 + 2];  
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
                return tmp;  
            } else {  
                return null;  
            }  
        } else { //No PAD e.g 3cQl  
            b3 = base64Alphabet[d3];  
            b4 = base64Alphabet[d4];  
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
  
        }  
  
        return decodedData;  
    }  
  
    /** 
     * remove WhiteSpace from MIME containing encoded Base64 data. 
     * 
     * @param data  the byte array of base64 data (with WS) 
     * @return      the new length 
     */  
    private static int removeWhiteSpace(char[] data) {  
        if (data == null) {  
            return 0;  
        }  
  
        // count characters that's not whitespace  
        int newSize = 0;  
        int len = data.length;  
        for (int i = 0; i < len; i++) {  
            if (!isWhiteSpace(data[i])) {  
                data[newSize++] = data[i];  
            }  
        }  
        return newSize;  
    }  
}  

然后就可以了,测试案例如下:

package com.fh.controller.weixin.junit;

import java.security.PublicKey;

import com.fh.util.weixin.Base64;
import com.fh.util.weixin.RSAUtil;

public class DemoTest {
	public static void main(String[] args) throws Exception {
		//需要被加密的字符串
		String encBankAcctName = "小郑"; //加密的银行账户名
		//定义自己公钥的路径
		String keyfile = "C:/book/pksc8_public.pem"; //
		//RSA工具类提供了,根据加载PKCS8密钥文件的方法
		PublicKey pub=RSAUtil.getPubKey(keyfile,"RSA"); 
		//rsa是微信付款到银行卡要求我们填充的字符串
		String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
		// 进行加密
		byte[] estr=RSAUtil.encrypt(encBankAcctName.getBytes(),pub,2048, 11,rsa);   //对银行账号进行base加密
		encBankAcctName =Base64.encode(estr);//并转为base64格式
		//测试输出
		System.out.println(encBankAcctName);
	}
}	

这里写图片描述
你能够正确的输出一串字符,说明你加密算法是没有问题的,如果有问题,会报错。输出不了
第三个难点:涉及到xml转化map,map转化成xml、签名、POST+证书发送。这个的话,详细可以查看这篇文件。里面的工具类都贴出来了,就是方便大家开发
http://blog.csdn.net/xiaozhegaa/article/details/79127283

六、正式的代码~ ~按照上述的8个步骤分别贴出来,很简单的

1、拼凑所需要传递的参数 map集合
2、对“收款方银行卡号”、“收款方用户名”进行“采用标准RSA算法”【付款到银行卡,这点最难】
3、根据要传递的参数生成自己的签名
4、把签名放到map集合中【因为签名也要传递过去,看API】
5、将当前的map结合转化成xml格式
6、发送请求到企业付款到银行的Api。发送请求是一个方法来的POST
7、解析返回的xml数据===》map集合
8、根据map中的result_code AND return_code来判断是否成功与失败

【注意第二步骤假设我们已经得到了公钥。至于如何获得,看第一个难点推荐的文章~自己去获取呗】

@Test
public void test1(){
//1~拼凑所需要传递的参数 map集合 ->查看API,传入参数哪些是必须的
String encBankAcctNo = "621226201001876****"; //加密的银行账号
String encBankAcctName = "小郑"; //加密的银行账户名
String bank_code = "1002"; //银行卡的编号~
String desc ="测试提现到账通知";//转账描述
String partner_trade_no = RandomStringGenerator.getRandomStringByLength(32);//生成随机号,
//这里大家没有该方法的,建议使用UUID。随便输出不超过32位的字符串即可
String nonce_str1 =  RandomStringGenerator.getRandomStringByLength(32);//同上
String mch_id = wxconfig.mch_id;//获取商务号的id
String amount = "100"; //付款金额,单位是分

//2.0 对“收款方银行卡号”、“收款方用户名”进行“采用标准RSA算法”【付款到银行卡,这点最难】		
//定义自己公钥的路径
String keyfile = "C:/book/pksc8_public.pem"; //读取PKCS8密钥文件
//RSA工具类提供了,根据加载PKCS8密钥文件的方法
PublicKey pub=RSAUtil.getPubKey(keyfile,"RSA");  
//rsa是微信付款到银行卡要求我们填充的字符串			 
String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
		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) {
			// TODO Auto-generated catch block
		e1.printStackTrace();		
	} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();	
	}  
				
//3.0 	根据要传递的参数生成自己的签名			
				
SortedMap<Object,Object> parameters1 = new TreeMap<Object,Object>();
	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);

//4.0 把签名放到map集合中【因为签名也要传递过去,看API】
parameters1.put("sign", sign);
				
//5.0 将当前的map结合转化成xml格式 ~~ 在上述第三个难点推荐的文章有该方法
String reuqestXml = WXPayUtil.getRequestXml(parameters1);
				
//6.0 发送请求到企业付款到银行的Api。发送请求是一个方法来的POST
String wxUrl = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank"; //获取退款的api接口
	try {
//调用方法发送了 -- 在上述第三个难点推荐的文章有该方法
String weixinPost = ClientCustomSSL.doRefund(wxUrl, reuqestXml).toString();
//7.0 解析返回的xml数据-- 在上述第三个难点推荐的文章有该方法
EnterpriceToCustomerByCard enterpriceToCustomerByCard = EnterpricePayByBankXmlToBeanUtils.parseXmlToMap(weixinPost);

//8.0根据map中的result_code AND return_code来判断是否成功与失败~~写自己的逻辑					

if("SUCCESS".equalsIgnoreCase(enterpriceToCustomerByCard.getResult_code()) 
&& 
"SUCCESS".equalsIgnoreCase(enterpriceToCustomerByCard.getReturn_code())){
		//8表示退款成功
		//TODO写自己的逻辑
		//TODO 更改自己的申请单状态,生成记录等等
}else{
		//9 表示退款失败
		//TODO 调用service的方法 ,存储失败提现的记录咯
					
					
	}
				
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	 }
}

至此就可以实现了企业付款到银行卡的功能了。至于说银行卡编号之类的,去写一个switch判断,得到就可以了~~希望对大家有帮助
这里写图片描述

展开阅读全文

没有更多推荐了,返回首页