java如何對接企業微信

經典雞翅發表於2022-01-09

前言

最近實現社群對接企業微信,對接的過程遇到一些點,在此記錄。

企業微信介紹

企業微信具有和微信一樣的體驗,用於企業內部成員和外部客戶的管理,可以由此構建出社群生態。
企業微信提供了豐富的api進行呼叫獲取資料管理,也提供了各種回撥事件,當資料發生變化時,可以及時知道。
我們分為兩部分進行講解,第一部分呼叫企業微信api,第二部分,接收企業微信的回撥。

呼叫企業微信api


api的開發文件地址:https://work.weixin.qq.com/api/doc/90000/90135/90664
呼叫企業微信所必須的東西就是企業的accesstoken。獲取accesstoken則需要我們的corpid和corpsercret。
具體我們可以參照這裡https://work.weixin.qq.com/api/doc/90000/90135/91039
有了token之後,我們就可以通過http請求來呼叫各種api,獲取資料。舉一個例子,建立成員的api,如下,我們只要使用http工具呼叫即可。

這裡分享一個http呼叫工具。

@Slf4j
public class HttpUtils {
    static CloseableHttpClient httpClient;

    private HttpUtils() {
        throw new IllegalStateException("Utility class");
    }

    static {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(200);
        connectionManager.setDefaultSocketConfig(
                SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS)
                        .setTcpNoDelay(true).build()
        );
        connectionManager.setValidateAfterInactivity(TimeValue.ofSeconds(15));

        httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .disableAutomaticRetries()
                .build();
    }

    public static String get(String url, Map<String, Object> paramMap, Map<String, String> headerMap) {
        String param = paramMap.entrySet().stream().map(n -> n.getKey() + "=" + n.getValue()).collect(Collectors.joining("&"));
        String fullUrl = url + "?" + param;
        final HttpGet httpGet = new HttpGet(fullUrl);
        if (Objects.nonNull(headerMap) && headerMap.size() > 0) {
            headerMap.forEach((key, value) -> httpGet.addHeader(key, value));
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            String strResult = EntityUtils.toString(response.getEntity());
            if (200 != response.getCode()) {
                log.error("HTTP get 返回狀態非200[resp={}]", strResult);
            }
            return strResult;
        } catch (IOException | ParseException e) {
            log.error("HTTP get 異常", e);
            return "";
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String post(String url,Map<String, Object> paramMap, Map<String, String> headerMap, String data) {
        CloseableHttpResponse response = null;
        try {
            String param = paramMap.entrySet().stream().map(n -> n.getKey() + "=" + n.getValue()).collect(Collectors.joining("&"));
            String fullUrl = url + "?" + param;
            final HttpPost httpPost = new HttpPost(fullUrl);
            if (Objects.nonNull(headerMap) && headerMap.size() > 0) {
                headerMap.forEach((key, value) -> httpPost.addHeader(key, value));
            }
            StringEntity httpEntity = new StringEntity(data, StandardCharsets.UTF_8);
            httpPost.setEntity(httpEntity);
            response = httpClient.execute(httpPost);
            if (200 == response.getCode()) {
                String strResult = EntityUtils.toString(response.getEntity());
                return strResult;
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            return "";
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}

對接企業微信的回撥

回撥分為很多種,比如通訊錄的回撥如下:
https://work.weixin.qq.com/api/doc/90000/90135/90967

整體的回撥流程如下:
配置回撥服務,需要有三個配置項,分別是:URL, Token, EncodingAESKey。
首先,URL為回撥服務地址,由開發者搭建,用於接收通知訊息或者事件。

其次,Token用於計算簽名,由英文或數字組成且長度不超過32位的自定義字串。開發者提供的URL是公開可訪問的,這就意味著拿到這個URL,就可以往該連結推送訊息。那麼URL服務需要解決兩個問題:

如何分辨出是否為企業微信來源
如何分辨出推送訊息的內容是否被篡改
通過數字簽名就可以解決上述的問題。具體為:約定Token作為金鑰,僅開發者和企業微信知道,在傳輸中不可見,用於參與簽名計算。企業微信在推送訊息時,將訊息內容與Token計算出簽名。開發者接收到推送訊息時,也按相同演算法計算出簽名。如果為同一簽名,則可信任來源為企業微信,並且內容是完整的。

如果非企業微信來源,由於攻擊者沒有正確的Token,無法算出正確的簽名;
如果訊息內容被篡改,由於開發者會將接收的訊息內容與Token重算一次簽名,該值與引數的簽名不一致,則會拒絕該請求。

最後,EncodingAESKey用於訊息內容加密,由英文或數字組成且長度為43位的自定義字串。由於訊息是在公開的因特網上傳輸,訊息內容是可被截獲的,如果內容未加密,則截獲者可以直接閱讀訊息內容。若訊息內容包含一些敏感資訊,就非常危險了。EncodingAESKey就是在這個背景基礎上提出,將傳送的內容進行加密,並組裝成一定格式後再傳送。

對接回撥,我們就要實現上述的加密,篡改等程式碼。這裡分享java版本的實現。
AesException

public class AesException extends Exception {

	public final static int OK = 0;
	public final static int ValidateSignatureError = -40001;
	public final static int ParseXmlError = -40002;
	public final static int ComputeSignatureError = -40003;
	public final static int IllegalAesKey = -40004;
	public final static int ValidateCorpidError = -40005;
	public final static int EncryptAESError = -40006;
	public final static int DecryptAESError = -40007;
	public final static int IllegalBuffer = -40008;

	private int code;

	private static String getMessage(int code) {
		switch (code) {
			case ValidateSignatureError:
				return "簽名驗證錯誤";
			case ParseXmlError:
				return "xml解析失敗";
			case ComputeSignatureError:
				return "sha加密生成簽名失敗";
			case IllegalAesKey:
				return "SymmetricKey非法";
			case ValidateCorpidError:
				return "corpid校驗失敗";
			case EncryptAESError:
				return "aes加密失敗";
			case DecryptAESError:
				return "aes解密失敗";
			case IllegalBuffer:
				return "解密後得到的buffer非法";
			default:
				return null;
		}
	}

	public int getCode() {
		return code;
	}

	AesException(int code) {
		super(getMessage(code));
		this.code = code;
	}

}

MessageUtil

public class MessageUtil {

    /**
     * 解析微信發來的請求(XML).
     *
     * @param msg 訊息
     * @return map
     */
    public static Map<String, String> parseXml(final String msg) {
        // 將解析結果儲存在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 從request中取得輸入流
        try (InputStream inputStream = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8.name()))) {
            // 讀取輸入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子節點
            List<Element> elementList = root.elements();

            // 遍歷所有子節點
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

}
public enum QywechatEnum {

    TEST("測試", "123123123123", "123123123123", "12312312312");

    /**
     * 應用名
     */
    private String name;

    /**
     * 企業ID
     */
    private String corpid;

    /**
     * 回撥url配置的token
     */
    private String token;

    /**
     * 隨機加密串
     */
    private String encodingAESKey;


    QywechatEnum(final String name, final String corpid, final String token, final String encodingAESKey) {
        this.name = name;
        this.corpid = corpid;
        this.encodingAESKey = encodingAESKey;
        this.token = token;
    }

    public String getCorpid() {
        return corpid;
    }

    public String getName() {
        return name;
    }

    public String getToken() {
        return token;
    }

    public String getEncodingAESKey() {
        return encodingAESKey;
    }

}
public class QywechatInfo {

    /**
     * 簽名
     */
    private String msgSignature;

    /**
     * 隨機時間戳
     */
    private String timestamp;

    /**
     * 隨機值
     */
    private String nonce;

    /**
     * 加密的xml字串
     */
    private String sPostData;

    /**
     * 企業微信回撥配置
     */
    private QywechatEnum qywechatEnum;

}
public class SHA1Utils {

    /**
     * 用SHA1演算法生成安全簽名
     *
     * @param token     票據
     * @param timestamp 時間戳
     * @param nonce     隨機字串
     * @param encrypt   密文
     * @return 安全簽名
     * @throws AesException
     */
    public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
        try {
            String[] array = new String[]{token, timestamp, nonce, encrypt};
            StringBuffer sb = new StringBuffer();
            // 字串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1簽名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }

}
public class WXBizMsgCrypt {
    static Charset CHARSET = Charset.forName("utf-8");
    Base64 base64 = new Base64();
    byte[] aesKey;
    String token;
    String receiveid;

    /**
     * 建構函式
     *
     * @throws AesException 執行失敗,請檢視該異常的錯誤碼和具體的錯誤資訊
     */
    public WXBizMsgCrypt(final QywechatEnum qywechatEnum) throws AesException {
        this.token = qywechatEnum.getToken();
        this.receiveid = qywechatEnum.getCorpid();
        String encodingAesKey = qywechatEnum.getEncodingAESKey();
        if (encodingAesKey.length() != 43) {
            throw new AesException(AesException.IllegalAesKey);
        }
        aesKey = Base64.decodeBase64(encodingAesKey + "=");

    }

    // 生成4個位元組的網路位元組序
    byte[] getNetworkBytesOrder(int sourceNumber) {
        byte[] orderBytes = new byte[4];
        orderBytes[3] = (byte) (sourceNumber & 0xFF);
        orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
        orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
        orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
        return orderBytes;
    }

    // 還原4個位元組的網路位元組序
    int recoverNetworkBytesOrder(byte[] orderBytes) {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++) {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    // 隨機生成16位字串
    String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 對明文進行加密.
     *
     * @param text 需要加密的明文
     * @return 加密後base64編碼的字串
     * @throws AesException aes加密失敗
     */
    String encrypt(String randomStr, String text) throws AesException {
        ByteGroup byteCollector = new ByteGroup();
        byte[] randomStrBytes = randomStr.getBytes(CHARSET);
        byte[] textBytes = text.getBytes(CHARSET);
        byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
        byte[] receiveidBytes = receiveid.getBytes(CHARSET);

        // randomStr + networkBytesOrder + text + receiveid
        byteCollector.addBytes(randomStrBytes);
        byteCollector.addBytes(networkBytesOrder);
        byteCollector.addBytes(textBytes);
        byteCollector.addBytes(receiveidBytes);

        // ... + pad: 使用自定義的填充方式對明文進行補位填充
        byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
        byteCollector.addBytes(padBytes);

        // 獲得最終的位元組流, 未加密
        byte[] unencrypted = byteCollector.toBytes();

        try {
            // 設定加密模式為AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(unencrypted);

            // 使用BASE64對加密後的字串進行編碼
            String base64Encrypted = base64.encodeToString(encrypted);

            return base64Encrypted;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.EncryptAESError);
        }
    }

    /**
     * 對密文進行解密.
     *
     * @param text 需要解密的密文
     * @return 解密得到的明文
     * @throws AesException aes解密失敗
     */
    String decrypt(String text) throws AesException {
        byte[] original;
        try {
            // 設定解密模式為AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

            // 使用BASE64對密文進行解碼
            byte[] encrypted = Base64.decodeBase64(text);

            // 解密
            original = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.DecryptAESError);
        }

        String xmlContent, from_receiveid;
        try {
            // 去除補位字元
            byte[] bytes = PKCS7Encoder.decode(original);

            // 分離16位隨機字串,網路位元組序和receiveid
            byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

            int xmlLength = recoverNetworkBytesOrder(networkOrder);

            xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
            from_receiveid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
                    CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.IllegalBuffer);
        }

        // receiveid不相同的情況
        if (!from_receiveid.equals(receiveid)) {
            throw new AesException(AesException.ValidateCorpidError);
        }
        return xmlContent;

    }

    /**
     * 將企業微信回覆使用者的訊息加密打包.
     * <ol>
     * 	<li>對要傳送的訊息進行AES-CBC加密</li>
     * 	<li>生成安全簽名</li>
     * 	<li>將訊息密文和安全簽名打包成xml格式</li>
     * </ol>
     *
     * @param replyMsg 企業微信待回覆使用者的訊息,xml格式的字串
     * @param timeStamp 時間戳,可以自己生成,也可以用URL引數的timestamp
     * @param nonce 隨機串,可以自己生成,也可以用URL引數的nonce
     *
     * @return 加密後的可以直接回複使用者的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字串
     * @throws AesException 執行失敗,請檢視該異常的錯誤碼和具體的錯誤資訊
     */
    public String EncryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
        // 加密
        String encrypt = encrypt(getRandomStr(), replyMsg);

        // 生成安全簽名
        if (timeStamp == "") {
            timeStamp = Long.toString(System.currentTimeMillis());
        }

        String signature = SHA1Utils.getSHA1(token, timeStamp, nonce, encrypt);

        // System.out.println("傳送給平臺的簽名是: " + signature[1].toString());
        // 生成傳送的xml
        String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
        return result;
    }

    /**
     * 檢驗訊息的真實性,並且獲取解密後的明文.
     * <ol>
     * 	<li>利用收到的密文生成安全簽名,進行簽名驗證</li>
     * 	<li>若驗證通過,則提取xml中的加密訊息</li>
     * 	<li>對訊息進行解密</li>
     * </ol>
     *
     * @param qywechatInfo  bean
     * @return 解密後的原文
     * @throws AesException 執行失敗,請檢視該異常的錯誤碼和具體的錯誤資訊
     */
    public String decryptMsg(final QywechatInfo qywechatInfo)
            throws AesException {

        // 金鑰,公眾賬號的app secret
        // 提取密文
        Object[] encrypt = XMLParse.extract(qywechatInfo.getSPostData());
        /**
         * @param msgSignature 簽名串,對應URL引數的msg_signature
         * @param timeStamp 時間戳,對應URL引數的timestamp
         * @param nonce 隨機串,對應URL引數的nonce
         * @param postData 密文,對應POST請求的資料
         */
        // 驗證安全簽名
        String signature = SHA1Utils.getSHA1(token, qywechatInfo.getTimestamp(), qywechatInfo.getNonce(), encrypt[1].toString());

        // 和URL中的簽名比較是否相等
        // System.out.println("第三方收到URL中的簽名:" + msg_sign);
        // System.out.println("第三方校驗簽名:" + signature);
        if (!signature.equals(qywechatInfo.getMsgSignature())) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        // 解密
        String result = decrypt(encrypt[1].toString());
        return result;
    }

    /**
     * 驗證URL
     * @param msgSignature 簽名串,對應URL引數的msg_signature
     * @param timeStamp 時間戳,對應URL引數的timestamp
     * @param nonce 隨機串,對應URL引數的nonce
     * @param echoStr 隨機串,對應URL引數的echostr
     *
     * @return 解密之後的echostr
     * @throws AesException 執行失敗,請檢視該異常的錯誤碼和具體的錯誤資訊
     */
    public String verifyURL(String msgSignature, String timeStamp, String nonce, String echoStr)
            throws AesException {
        String signature = SHA1Utils.getSHA1(token, timeStamp, nonce, echoStr);

        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        String result = decrypt(echoStr);
        return result;
    }

    static class ByteGroup {
        ArrayList<Byte> byteContainer = new ArrayList<Byte>();

        public byte[] toBytes() {
            byte[] bytes = new byte[byteContainer.size()];
            for (int i = 0; i < byteContainer.size(); i++) {
                bytes[i] = byteContainer.get(i);
            }
            return bytes;
        }

        public ByteGroup addBytes(byte[] bytes) {
            for (byte b : bytes) {
                byteContainer.add(b);
            }
            return this;
        }

        public int size() {
            return byteContainer.size();
        }
    }

    static class PKCS7Encoder {
        static Charset CHARSET = Charset.forName("utf-8");
        static int BLOCK_SIZE = 32;

        /**
         * 獲得對明文進行補位填充的位元組.
         *
         * @param count 需要進行填充補位操作的明文位元組個數
         * @return 補齊用的位元組陣列
         */
        static byte[] encode(int count) {
            // 計算需要填充的位數
            int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
            if (amountToPad == 0) {
                amountToPad = BLOCK_SIZE;
            }
            // 獲得補位所用的字元
            char padChr = chr(amountToPad);
            String tmp = new String();
            for (int index = 0; index < amountToPad; index++) {
                tmp += padChr;
            }
            return tmp.getBytes(CHARSET);
        }

        /**
         * 刪除解密後明文的補位字元
         *
         * @param decrypted 解密後的明文
         * @return 刪除補位字元後的明文
         */
        static byte[] decode(byte[] decrypted) {
            int pad = (int) decrypted[decrypted.length - 1];
            if (pad < 1 || pad > 32) {
                pad = 0;
            }
            return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
        }

        /**
         * 將數字轉化成ASCII碼對應的字元,用於對明文進行補碼
         *
         * @param a 需要轉化的數字
         * @return 轉化得到的字元
         */
        static char chr(int a) {
            byte target = (byte) (a & 0xFF);
            return (char) target;
        }

    }

}
public class XMLParse {

    /**
     * 提取出xml資料包中的加密訊息
     *
     * @param xmltext 待提取的xml字串
     * @return 提取出的加密訊息字串
     * @throws AesException
     */
    public static Object[] extract(String xmltext) throws AesException {
        Object[] result = new Object[3];
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            String FEATURE = null;
            // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
            // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
            FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
            dbf.setFeature(FEATURE, true);

            // If you can't completely disable DTDs, then at least do the following:
            // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
            // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
            // JDK7+ - http://xml.org/sax/features/external-general-entities
            FEATURE = "http://xml.org/sax/features/external-general-entities";
            dbf.setFeature(FEATURE, false);

            // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
            // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
            // JDK7+ - http://xml.org/sax/features/external-parameter-entities
            FEATURE = "http://xml.org/sax/features/external-parameter-entities";
            dbf.setFeature(FEATURE, false);

            // Disable external DTDs as well
            FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
            dbf.setFeature(FEATURE, false);

            // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
            dbf.setXIncludeAware(false);
            dbf.setExpandEntityReferences(false);

            // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
            // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
            // (http://cwe.mitre.org/data/definitions/918.html) and denial
            // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."

            // remaining parser logic
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xmltext);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            NodeList nodelist2 = root.getElementsByTagName("ToUserName");
            result[0] = 0;
            result[1] = nodelist1.item(0).getTextContent();
            result[2] = nodelist2.item(0).getTextContent();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ParseXmlError);
        }
    }

    /**
     * 生成xml訊息
     *
     * @param encrypt   加密後的訊息密文
     * @param signature 安全簽名
     * @param timestamp 時間戳
     * @param nonce     隨機字串
     * @return 生成的xml字串
     */
    public static String generate(String encrypt, String signature, String timestamp, String nonce) {

        String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
                + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
                + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
        return String.format(format, encrypt, signature, timestamp, nonce);

    }
}
public class CallbackController {

    @Resource
    private CallbackProducer callbackProducer;

    /**
     * get請求用於驗籤
     */
    @GetMapping(value = "/callback")
    public void receiveMsg(@RequestParam(name = "msg_signature") final String msgSignature,
                           @RequestParam(name = "timestamp") final String timestamp,
                           @RequestParam(name = "nonce") final String nonce,
                           @RequestParam(name = "echostr") final String echostr,
                           final HttpServletResponse response) throws Exception {
        QywechatEnum qywechatEnum = QywechatEnum.JXPP;
        log.info("get驗籤請求引數 msg_signature {}, timestamp {}, nonce {} , echostr {}", msgSignature, timestamp, nonce, echostr);
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(qywechatEnum);
        String sEchoStr = wxBizMsgCrypt.verifyURL(msgSignature, timestamp, nonce, echostr);
        PrintWriter out = response.getWriter();
        try {
            //必須要返回解密之後的明文
            if (StringUtils.isBlank(sEchoStr)) {
                log.info("get驗籤URL驗證失敗");
            } else {
                log.info("get驗籤驗證成功!");
            }
        } catch (Exception e) {
            log.error("get驗簽報錯!", e);
        }
        log.info("get驗籤的echo是{}", sEchoStr);
        out.write(sEchoStr);
        out.flush();
    }

    /**
     * 企業微信客戶聯絡回撥
     */
    @ResponseBody
    @PostMapping(value = "/callback")
    public String acceptMessage(final HttpServletRequest request,
                                @RequestParam(name = "msg_signature") final String sMsgSignature,
                                @RequestParam(name = "timestamp") final String sTimestamp,
                                @RequestParam(name = "nonce") final String sNonce) {
        QywechatEnum qywechatEnum = QywechatEnum.TEST;
        try {
            InputStream inputStream = request.getInputStream();
            String sPostData = IOUtils.toString(inputStream, "UTF-8");
            QywechatInfo qywechatInfo = new QywechatInfo();
            qywechatInfo.setMsgSignature(sMsgSignature);
            qywechatInfo.setNonce(sNonce);
            qywechatInfo.setQywechatEnum(qywechatEnum);
            qywechatInfo.setTimestamp(sTimestamp);
            qywechatInfo.setSPostData(sPostData);
            WXBizMsgCrypt msgCrypt = new WXBizMsgCrypt(qywechatInfo.getQywechatEnum());
            String sMsg = msgCrypt.decryptMsg(qywechatInfo);
            Map<String, String> dataMap = MessageUtil.parseXml(sMsg);
            log.info("回撥的xml資料轉為map的資料{}", JsonHelper.toJSONString(dataMap));
        } catch (Exception e) {
            log.info("回撥報錯", e);
        }
        return "success";
    }


}

如上程式碼拷貝好後,我們便可以在企業微信的回撥事件配置介面,增加回撥的連線地址。

實現方案過程中遇到的點

1、回撥配置的地址只支援一個,所以要把回撥服務抽取出來,申請公網域名。要注意將接收到的回撥訊息放到訊息佇列,供其他所有服務接收處理。
2、處理回撥要注意逆序問題,假如更新操作先來了,新增操作還沒有開始。
3、可以採用訊息補償,定時任務重新整理機制,手動同步機制,保證資料的一致性。
4、要實現重試機制,因為可能觸發微信的併發呼叫限制。

相關文章