这篇文章给大家介绍java对接企业微信的实现步骤是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
前言
最近实现社群对接企业微信,对接的过程遇到一些点,在此记录。
企业微信介绍
企业微信具有和微信一样的体验,用于企业内部成员和外部客户的管理,可以由此构建出社群生态。
企业微信提供了丰富的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调用工具。
@Slf4jpublic 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 { 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; private String corpid; 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; private String sPostData; private QywechatEnum qywechatEnum;}
public class SHA1Utils { 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; 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(); } 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); } } 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; } 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; } public String decryptMsg(final QywechatInfo qywechatInfo) throws AesException { // 密钥,公众账号的app secret // 提取密文 Object[] encrypt = XMLParse.extract(qywechatInfo.getSPostData()); // 验证安全签名 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; } 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; 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); } 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); } static char chr(int a) { byte target = (byte) (a & 0xFF); return (char) target; } }}
如上代码拷贝好后,我们便可以在企业微信的回调事件配置界面,增加回调的连接地址。
实现方案过程中遇到的点
回调配置的地址只支持一个,所以要把回调服务抽取出来,申请公网域名。要注意将接收到的回调消息放到消息队列,供其他所有服务接收处理。
2、处理回调要注意逆序问题,假如更新操作先来了,新增操作还没有开始。
3、可以采用消息补偿,定时任务刷新机制,手动同步机制,保证数据的一致性。
4、要实现重试机制,因为可能触发微信的并发调用限制。
关于java对接企业微信的实现步骤是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。