编程语言   发布时间:2022-06-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java如何对接企业微信大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

最近实现社群对接企业微信,对接的过程遇到一些点,在此记录。

企业微信介绍

企业微信具有和微信一样的体验,用于企业内部成员和外部客户的管理,可以由此构建出社群生态。 企业微信提供了丰富的api进行调用获取数据管理,也提供了各种回调事件,当数据发生变化时,可以及时知道。 我们分为两部分进行讲解,第一部分调用企业微信api,第二部分,接收企业微信的回调。

调用企业微信api

java如何对接企业微信

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工具调用即可。

java如何对接企业微信

这里分享一个http调用工具。

@H_674_18@@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.setMax@R_949_10586@l(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, @R_673_7548@ -> httpGet.addHeader(key, @R_673_7548@); } 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, @R_673_7548@ -> httpPost.addHeader(key, @R_673_7548@); } 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为回调服务地址,由开发者搭建,用于接收通知消息或者事件。

java如何对接企业微信

其次,Token用于计算签名,由英文或数字组成且长度不超过32位的自定义字符串。开发者提供的URL是公开可访问的,这就意味着拿到这个URL,就可以往该链接推送消息。那么URL服务需要解决两个问题:

如何分辨出是否为企业微信来源 如何分辨出推送消息的内容是否被篡改 通过数字签名就可以解决上述的问题。具体为:约定Token作为密钥,仅开发者和企业微信知道,在传输中不可见,用于参与签名计算。企业微信在推送消息时,将消息内容与Token计算出签名。开发者接收到推送消息时,也按相同算法计算出签名。如果为同一签名,则可信任来源为企业微信,并且内容是完整的。

如果非企业微信来源,由于攻击者没有正确的Token,无法算出正确的签名; 如果消息内容被篡改,由于开发者会将接收的消息内容与Token重算一次签名,该值与参数的签名不一致,则会拒绝该请求。

java如何对接企业微信

最后,EncodingAESKey用于消息内容加密,由英文或数字组成且长度为43位的自定义字符串。由于消息是在公开的因特网上传输,消息内容是可被截获的,如果内容未加密,则截获者可以直接阅读消息内容。若消息内容包含一些敏感信息,就非常危险了。EncodingAESKey就是在这个背景基础上提出,将发送的内容进行加密,并组装成一定格式后再发送。

java如何对接企业微信

对接回调,我们就要实现上述的加密,篡改等代码。这里分享java版本的实现。 AesException

@H_674_18@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

@H_674_18@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; } } @H_674_18@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; } } @H_674_18@public class QywechaTinfo { /** * 签名 */ private String msgSignature; /** * 随机时间戳 */ private String timestamp; /** * 随机值 */ private String nonce; /** * 加密的xml字符串 */ private String sPostData; /** * 企业微信回调配置 */ private QywechatEnum qywechatEnum; } @H_674_18@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); } } } @H_674_18@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 = @R_618_10932@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 @R_618_10932@int a) { byte target = (bytE) (a & 0xFF); return (char) target; } } } @H_674_18@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 scheR_704_11845@a, 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); } } @H_674_18@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"; } }

如上代码拷贝好后,我们便可以在企业微信的回调事件配置界面,增加回调的连接地址。

java如何对接企业微信

实现方案过程中遇到的点

1、回调配置的地址只支持一个,所以要把回调服务抽取出来,申请公网域名。要注意将接收到的回调消息放到消息队列,供其他所有服务接收处理。 2、处理回调要注意逆序问题,假如更新操作先来了,新增操作还没有开始。 3、可以采用消息补偿,定时任务刷新机制,手动同步机制,保证数据的一致性。 4、要实现重试机制,因为可能触发微信的并发调用限制。

大佬总结

以上是大佬教程为你收集整理的java如何对接企业微信全部内容,希望文章能够帮你解决java如何对接企业微信所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。