• 企业微信第三方服务商应用开发及上架教程


    之前一直没有写这篇文章,是觉得企微的服务商应用相对简单。第二个原因是最近在弄钉钉的ISV上架,所以时间不是很充足。正题开始……

    第一章 服务商入驻

    1、使用管理员登录服务商管理后台

    企业微信-服务商后台-登录地址https://open.work.weixin.qq.com/wwopen/login2、输入基本信息及认证

    第二章 应用配置

    1、登录后,直接创建创建网页应用,如下图。

     2、应用详情-使用配置-参照下面的教程。主页地址是固定的,只需要写入自己的appid和redirect_uri的地址就行。这里需要注意,可信域名必须配置一下,需要注意的是这个一级域名一旦使用的服务商应用,那么自建应用是无法在使用这个域名的,即便是不同的二级域名也不可以。这个还是比较坑,导致我们重新申请了一个一级域名来服务自建应用。

     3、可信域名配置,使用配置-点击【编辑】,然后点击【校验可信域名归属】,然后下载这个文件到nginx配置的域名文件夹下,只要通过步骤2的地址可以访问到就算验证通过。nginx的配置参照下面的这个文章。

    nginx配置websocket或https的转发教程_renkai721的博客-CSDN博客_nginx websocket转发nginx配置http,https,ssl,websocket转发https://blog.csdn.net/renkai721/article/details/125991270

     4、数据回调的配置

    第三章 应用开发

    1、pom.xml中添加解析XML格式内容

    1. <dependency>
    2. <groupId>org.jdomgroupId>
    3. <artifactId>jdom2artifactId>
    4. <version>2.0.6version>
    5. dependency>
    6. <dependency>
    7. <groupId>commons-codecgroupId>
    8. <artifactId>commons-codecartifactId>
    9. <version>1.15version>
    10. dependency>

    2、properties文件,不需要那么多,命名更具自己的喜好,这一看就是参照了gitee的binarywang/weixin-java-cp-demo,这个demo如果初学者可以看看,然后自己封装。

     3、核心解密controller.java

    1. package cn.renkai721.controller;
    2. import cn.renkai721.bean.*;
    3. import cn.renkai721.configuration.QywxProperties;
    4. import cn.renkai721.service.*;
    5. import cn.renkai721.util.HttpUtil;
    6. import cn.renkai721.util.MsgUtil;
    7. import cn.renkai721.util.WxUtil;
    8. import cn.renkai721.wechataes.WXBizMsgCrypt;
    9. import com.alibaba.druid.util.StringUtils;
    10. import com.alibaba.fastjson.JSON;
    11. import lombok.extern.slf4j.Slf4j;
    12. import org.redisson.api.RBucket;
    13. import org.redisson.api.RedissonClient;
    14. import org.springframework.beans.factory.annotation.Autowired;
    15. import org.springframework.http.ResponseEntity;
    16. import org.springframework.scheduling.annotation.EnableAsync;
    17. import org.springframework.web.bind.annotation.*;
    18. import org.springframework.web.client.RestTemplate;
    19. import javax.annotation.Resource;
    20. import javax.servlet.ServletInputStream;
    21. import javax.servlet.http.HttpServletRequest;
    22. import javax.servlet.http.HttpServletResponse;
    23. import java.io.BufferedReader;
    24. import java.io.InputStreamReader;
    25. import java.util.Map;
    26. @EnableAsync
    27. @RestController
    28. @RequestMapping("/d3f")
    29. @Slf4j
    30. public class D3f2Controller {
    31. @Resource
    32. private RedissonClient redissonClient;
    33. @Autowired
    34. private RestTemplate restTemplate;
    35. @Autowired
    36. private D3fService d3fService;
    37. @GetMapping(produces = "text/plain;charset=utf-8")
    38. public void d3fGet(@RequestParam(name = "msg_signature", required = false) String signature,
    39. @RequestParam(name = "timestamp", required = false) String timestamp,
    40. @RequestParam(name = "nonce", required = false) String nonce,
    41. @RequestParam(name = "echostr", required = false) String echostr,
    42. HttpServletResponse response) throws Exception {
    43. response.setContentType("text/html;charset=utf-8");
    44. response.setStatus(HttpServletResponse.SC_OK);
    45. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(
    46. MsgUtil.val("wechat.cp.appConfigs[0].token"),
    47. MsgUtil.val("wechat.cp.appConfigs[0].aesKey"),
    48. MsgUtil.val("wechat.cp.corpId"));
    49. // 需要返回的明文
    50. String sEchoStr = "";
    51. try {
    52. sEchoStr = wxcpt.VerifyURL(signature, timestamp, nonce, echostr);
    53. log.info("resp sEchoStr={}",sEchoStr);
    54. response.getWriter().print(sEchoStr);
    55. return;
    56. } catch (Exception e) {
    57. // 验证URL失败,错误原因请查看异常
    58. e.printStackTrace();
    59. }
    60. response.getWriter().print("非法请求");
    61. return;
    62. }
    63. @PostMapping(produces = "application/xml; charset=UTF-8")
    64. public void d3fPost(@RequestParam("msg_signature") String signature,
    65. @RequestParam("timestamp") String timestamp,
    66. @RequestParam("nonce") String nonce,
    67. HttpServletResponse response,
    68. HttpServletRequest request) throws Exception {
    69. String success = "success";
    70. String type = request.getParameter("type");
    71. String corpid = request.getParameter("corpid");
    72. log.info("接收d3f post请求:[signature=[{}], timestamp=[{}], nonce=[{}], type=[{}], corpid=[{}] ]",
    73. signature, timestamp, nonce, type, corpid);
    74. try{
    75. response.setContentType("text/html;charset=utf-8");
    76. response.setStatus(HttpServletResponse.SC_OK);
    77. String id = "";
    78. // 访问应用和企业回调传不同的ID
    79. if("data".equals(type)){
    80. // 企微后台设置【数据回调URL】的链接为https://wx.naturobot.com/qywx/d3f?type=data&corpid=$CORPID$
    81. id = corpid;
    82. } else {
    83. id = MsgUtil.val("suite_id");
    84. }
    85. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(MsgUtil.val(
    86. "wechat.cp.appConfigs[0].token"),
    87. MsgUtil.val("wechat.cp.appConfigs[0].aesKey"),
    88. id);
    89. // 密文,对应POST请求的数据
    90. String postData = "";
    91. // 获取加密的请求消息:使用输入流获得加密请求消息postData
    92. ServletInputStream in = request.getInputStream();
    93. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    94. // 作为输出字符串的临时串,用于判断是否读取完毕
    95. String tempStr = "";
    96. while(null != (tempStr=reader.readLine())){
    97. postData += tempStr;
    98. }
    99. String suiteXml = wxcpt.DecryptMsg(signature, timestamp, nonce, postData);
    100. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
    101. log.info("\n req map={}", suiteMap);
    102. if("suite_ticket".equals(suiteMap.get("InfoType"))){
    103. // https://developer.work.weixin.qq.com/document/10975#%E8%8E%B7%E5%8F%96%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E5%87%AD%E8%AF%81
    104. // 主动推送SuiteTicket直接写入
    105. // 每十分钟更新一次
    106. //suite_ticket实际有效期为30分钟,
    107. String suite_ticket_value = (String) suiteMap.get("SuiteTicket");
    108. String SuiteId = (String) suiteMap.get("SuiteId");
    109. log.info("suite_ticket={},SuiteId={}",suite_ticket_value,SuiteId);
    110. RBucket idBucket = redissonClient.getBucket(QywxProperties.suite_ticket_key);
    111. idBucket.set(suite_ticket_value);
    112. // 调用企业微信接口
    113. d3fService.get_suite_access_token();
    114. }else if("create_auth".equals(suiteMap.get("InfoType"))){
    115. String authCode = (String) suiteMap.get("AuthCode");
    116. // SuiteId代表一个企业,相当于suite_id
    117. String SuiteId = (String) suiteMap.get("SuiteId");
    118. log.info("第三方应用测试上线,AuthCode={},SuiteId={}",authCode,SuiteId);
    119. RBucket idBucket = redissonClient.getBucket(QywxProperties.authCode_key+"_"+SuiteId);
    120. idBucket.set(authCode);
    121. // 获取企业永久授权码
    122. idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
    123. String suite_access_token = idBucket.get();
    124. String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token="+suite_access_token;
    125. PermanentReqBean permanentReqBean = new PermanentReqBean();
    126. permanentReqBean.setAuth_code(authCode);
    127. ResponseEntity postForEntity1 = restTemplate.postForEntity(url1, permanentReqBean, PermanentRespBean.class);
    128. log.info("get_permanent_code={}",postForEntity1.getBody());
    129. if(postForEntity1.getBody().getExpires_in() != null){
    130. String authCorpId = postForEntity1.getBody().getAuth_corp_info().getCorpid();
    131. log.info("永久授权码中获取的第三方应用的authCorpId={}",authCorpId);
    132. String userIdD3f = postForEntity1.getBody().getAuth_user_info().getUserid();
    133. // 直接取第一个
    134. String agentId = postForEntity1.getBody().getAuth_info().getAgent().get(0).getAgentid();
    135. String permanent_code_access_token = postForEntity1.getBody().getAccess_token();
    136. String permanent_code = postForEntity1.getBody().getPermanent_code();
    137. log.info("permanent_code={}",permanent_code);
    138. String open_userid = postForEntity1.getBody().getAuth_user_info().getOpen_userid();
    139. // 可以设置企业的许可自动激活状态
    140. // 这里面的东西需要保存下来,不然后面使用的时候没有了就完蛋了
    141. // 这里面的东西需要保存下来,不然后面使用的时候没有了就完蛋了
    142. // 这里面的东西需要保存下来,不然后面使用的时候没有了就完蛋了
    143. }else{
    144. log.error("get_permanent_code api is error");
    145. }
    146. }else if("cancel_auth".equals(suiteMap.get("InfoType"))){
    147. String AuthCorpId = (String) suiteMap.get("AuthCorpId");
    148. log.info("取消订阅cancel_auth AuthCorpId={}",AuthCorpId);
    149. }
    150. if("unlicensed_notify".equals(suiteMap.get("Event"))){
    151. // 该用户帐号未授权
    152. String AgentID = (String) suiteMap.get("AgentID");
    153. String ToUserName = (String) suiteMap.get("ToUserName");
    154. String FromUserName = (String) suiteMap.get("FromUserName");
    155. log.info("用户帐号没有开通授权,需要授权");
    156. }else if("change_app_admin".equals(suiteMap.get("Event"))){
    157. String AgentID = (String) suiteMap.get("AgentID");
    158. // ToUserName=corpId
    159. String ToUserName = (String) suiteMap.get("ToUserName");
    160. log.info("第三方应用change_app_admin,ToUserName={},AgentID={}",ToUserName,AgentID);
    161. }else if("subscribe".equals(suiteMap.get("Event"))){
    162. log.info("新用户关注,user={}",suiteMap);
    163. // 回复感谢关注
    164. String ToUserName = (String) suiteMap.get("ToUserName");
    165. String FromUserName = (String) suiteMap.get("FromUserName");
    166. String AgentID = (String) suiteMap.get("AgentID");
    167. // 获取临时授权码
    168. RBucket idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
    169. String suite_access_token = idBucket.get();
    170. String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=" + suite_access_token;
    171. String postData1 = HttpUtil.sendGet(url1);
    172. log.info("get_pre_auth_code={}", postData1);
    173. String subscribe_pre_auth_code = JSON.parseObject(postData1).getString("pre_auth_code");
    174. String expires_in = JSON.parseObject(postData1).getString("expires_in");
    175. if(!StringUtils.isEmpty(expires_in)){
    176. // 设置授权配置
    177. url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=" + suite_access_token;
    178. SessionInfoReqBean sessionInfoReqBean = new SessionInfoReqBean();
    179. sessionInfoReqBean.setPre_auth_code(subscribe_pre_auth_code);
    180. SessionInfoBean sessionInfoBean = new SessionInfoBean();
    181. sessionInfoBean.setAppid(new Integer[0]);
    182. sessionInfoBean.setAuth_type(Integer.parseInt(MsgUtil.val("authType")));
    183. sessionInfoReqBean.setSession_info(sessionInfoBean);
    184. log.info("sessionInfoReqBean={}", JSON.toJSONString(sessionInfoReqBean));
    185. ResponseEntity postForEntity = restTemplate.postForEntity(url1, sessionInfoReqBean, SessionInfoRespBean.class);
    186. log.info("设置授权配置={}", postForEntity.getBody());
    187. }else{
    188. log.error("get_pre_auth_code api is error");
    189. }
    190. // 发送XML消息给用户
    191. String Title = "谢谢安装该应用";
    192. String Description = "我们的应用很好用,如果有问题请拨打电话021-12345";
    193. String Url = MsgUtil.val("poster.freeUrl");
    194. String PicUrl = "https://wx.naturobot.com/qywx/image/bg1.png";
    195. log.info("Title={},Description={},Url={},PicUrl={},",Title,Description,Url,PicUrl);
    196. String xmlOutMsg = wxcpt.getXmlNewsMessage(FromUserName,ToUserName,Title,Description,Url,PicUrl);
    197. success = wxcpt.EncryptMsg(xmlOutMsg, timestamp, nonce);
    198. }else if("enter_agent".equals(suiteMap.get("Event"))){
    199. // 用户打开应用的事件
    200. }
    201. if("text".equals(suiteMap.get("MsgType"))){
    202. // 用户发送了文本消息给应用
    203. String ToUserName = (String) suiteMap.get("ToUserName");
    204. String FromUserName = (String) suiteMap.get("FromUserName");
    205. String AgentID = (String) suiteMap.get("AgentID");
    206. String xmlOutMsg = wxcpt.getXmlTextMessage(FromUserName,ToUserName,"暂未开启聊天功能。");
    207. success = wxcpt.EncryptMsg(xmlOutMsg, timestamp, nonce);
    208. }
    209. } catch (Exception e) {
    210. e.printStackTrace();
    211. }
    212. response.getWriter().print(success);
    213. return;
    214. }
    215. }

    4、解密工具WXBizMsgCrypt.java

    1. /**
    2. * 对企业微信发送给企业后台的消息加解密示例代码.
    3. *
    4. * @copyright Copyright (c) 1998-2014 Tencent Inc.
    5. */
    6. // ------------------------------------------------------------------------
    7. /**
    8. * 针对org.apache.commons.codec.binary.Base64,
    9. * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
    10. * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
    11. */
    12. package cn.renkai721.wechataes;
    13. import org.apache.commons.codec.binary.Base64;
    14. import javax.crypto.Cipher;
    15. import javax.crypto.spec.IvParameterSpec;
    16. import javax.crypto.spec.SecretKeySpec;
    17. import java.nio.charset.Charset;
    18. import java.util.Arrays;
    19. import java.util.Random;
    20. /**
    21. * 提供接收和推送给企业微信消息的加解密接口(UTF8编码的字符串).
    22. *
      1. *
      2. 第三方回复加密消息给企业微信
    23. *
    24. 第三方收到企业微信发送的消息,验证消息的安全性,并对消息进行解密。
  • *
  • * 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案
  • *
    1. *
    2. 在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
    3. * http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
    4. *
    5. 下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
    6. *
    7. 如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
    8. *
    9. 如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件
    10. *
    11. */
    12. public class WXBizMsgCrypt {
    13. static Charset CHARSET = Charset.forName("utf-8");
    14. Base64 base64 = new Base64();
    15. byte[] aesKey;
    16. String token;
    17. String receiveid;
    18. /**
    19. * 构造函数
    20. * @param token 企业微信后台,开发者设置的token
    21. * @param encodingAesKey 企业微信后台,开发者设置的EncodingAESKey
    22. * @param receiveid, 不同场景含义不同,详见文档
    23. *
    24. * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
    25. */
    26. public WXBizMsgCrypt(String token, String encodingAesKey, String receiveid) throws AesException {
    27. if (encodingAesKey.length() != 43) {
    28. throw new AesException(AesException.IllegalAesKey);
    29. }
    30. this.token = token;
    31. this.receiveid = receiveid;
    32. aesKey = Base64.decodeBase64(encodingAesKey + "=");
    33. }
    34. // 生成4个字节的网络字节序
    35. byte[] getNetworkBytesOrder(int sourceNumber) {
    36. byte[] orderBytes = new byte[4];
    37. orderBytes[3] = (byte) (sourceNumber & 0xFF);
    38. orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
    39. orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
    40. orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
    41. return orderBytes;
    42. }
    43. // 还原4个字节的网络字节序
    44. int recoverNetworkBytesOrder(byte[] orderBytes) {
    45. int sourceNumber = 0;
    46. for (int i = 0; i < 4; i++) {
    47. sourceNumber <<= 8;
    48. sourceNumber |= orderBytes[i] & 0xff;
    49. }
    50. return sourceNumber;
    51. }
    52. // 随机生成16位字符串
    53. String getRandomStr() {
    54. String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    55. Random random = new Random();
    56. StringBuffer sb = new StringBuffer();
    57. for (int i = 0; i < 16; i++) {
    58. int number = random.nextInt(base.length());
    59. sb.append(base.charAt(number));
    60. }
    61. return sb.toString();
    62. }
    63. /**
    64. * 对明文进行加密.
    65. *
    66. * @param text 需要加密的明文
    67. * @return 加密后base64编码的字符串
    68. * @throws AesException aes加密失败
    69. */
    70. String encrypt(String randomStr, String text) throws AesException {
    71. ByteGroup byteCollector = new ByteGroup();
    72. byte[] randomStrBytes = randomStr.getBytes(CHARSET);
    73. byte[] textBytes = text.getBytes(CHARSET);
    74. byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
    75. byte[] receiveidBytes = receiveid.getBytes(CHARSET);
    76. // randomStr + networkBytesOrder + text + receiveid
    77. byteCollector.addBytes(randomStrBytes);
    78. byteCollector.addBytes(networkBytesOrder);
    79. byteCollector.addBytes(textBytes);
    80. byteCollector.addBytes(receiveidBytes);
    81. // ... + pad: 使用自定义的填充方式对明文进行补位填充
    82. byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
    83. byteCollector.addBytes(padBytes);
    84. // 获得最终的字节流, 未加密
    85. byte[] unencrypted = byteCollector.toBytes();
    86. try {
    87. // 设置加密模式为AES的CBC模式
    88. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    89. SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
    90. IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
    91. cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
    92. // 加密
    93. byte[] encrypted = cipher.doFinal(unencrypted);
    94. // 使用BASE64对加密后的字符串进行编码
    95. String base64Encrypted = base64.encodeToString(encrypted);
    96. return base64Encrypted;
    97. } catch (Exception e) {
    98. e.printStackTrace();
    99. throw new AesException(AesException.EncryptAESError);
    100. }
    101. }
    102. /**
    103. * 对密文进行解密.
    104. *
    105. * @param text 需要解密的密文
    106. * @return 解密得到的明文
    107. * @throws AesException aes解密失败
    108. */
    109. String decrypt(String text) throws AesException {
    110. byte[] original;
    111. try {
    112. // 设置解密模式为AES的CBC模式
    113. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    114. SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
    115. IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
    116. cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
    117. // 使用BASE64对密文进行解码
    118. byte[] encrypted = Base64.decodeBase64(text);
    119. // 解密
    120. original = cipher.doFinal(encrypted);
    121. } catch (Exception e) {
    122. e.printStackTrace();
    123. throw new AesException(AesException.DecryptAESError);
    124. }
    125. String xmlContent, from_receiveid;
    126. try {
    127. // 去除补位字符
    128. byte[] bytes = PKCS7Encoder.decode(original);
    129. // 分离16位随机字符串,网络字节序和receiveid
    130. byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
    131. int xmlLength = recoverNetworkBytesOrder(networkOrder);
    132. xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
    133. from_receiveid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
    134. CHARSET);
    135. } catch (Exception e) {
    136. e.printStackTrace();
    137. throw new AesException(AesException.IllegalBuffer);
    138. }
    139. // receiveid不相同的情况
    140. System.out.println("------ from_receiveid="+from_receiveid+", receiveid="+receiveid);
    141. if (!from_receiveid.equals(receiveid)) {
    142. throw new AesException(AesException.ValidateCorpidError);
    143. }
    144. return xmlContent;
    145. }
    146. /**
    147. * 将企业微信回复用户的消息加密打包.
    148. *
      1. *
      2. 对要发送的消息进行AES-CBC加密
      3. *
      4. 生成安全签名
      5. *
      6. 将消息密文和安全签名打包成xml格式
      7. *
      8. *
      9. * @param replyMsg 企业微信待回复用户的消息,xml格式的字符串
      10. * @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp
      11. * @param nonce 随机串,可以自己生成,也可以用URL参数的nonce
      12. *
      13. * @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
      14. * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
      15. */
      16. public String EncryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
      17. // 加密
      18. String encrypt = encrypt(getRandomStr(), replyMsg);
      19. // 生成安全签名
      20. if (timeStamp == "") {
      21. timeStamp = Long.toString(System.currentTimeMillis());
      22. }
      23. String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
      24. // System.out.println("发送给平台的签名是: " + signature[1].toString());
      25. // 生成发送的xml
      26. String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
      27. System.out.println("call wechat xml message=["+result+"]");
      28. return result;
      29. }
      30. /**
      31. * 检验消息的真实性,并且获取解密后的明文.
      32. *
        1. *
        2. 利用收到的密文生成安全签名,进行签名验证
        3. *
        4. 若验证通过,则提取xml中的加密消息
        5. *
        6. 对消息进行解密
        7. *
        8. *
        9. * @param msgSignature 签名串,对应URL参数的msg_signature
        10. * @param timeStamp 时间戳,对应URL参数的timestamp
        11. * @param nonce 随机串,对应URL参数的nonce
        12. * @param postData 密文,对应POST请求的数据
        13. *
        14. * @return 解密后的原文
        15. * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
        16. */
        17. public String DecryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
        18. throws AesException {
        19. // 密钥,公众帐号的app secret
        20. // 提取密文
        21. Object[] encrypt = XMLParse.extract(postData);
        22. // 验证安全签名
        23. String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());
        24. // 和URL中的签名比较是否相等
        25. // System.out.println("第三方收到URL中的签名:" + msg_sign);
        26. // System.out.println("第三方校验签名:" + signature);
        27. if (!signature.equals(msgSignature)) {
        28. throw new AesException(AesException.ValidateSignatureError);
        29. }
        30. // 解密
        31. String result = decrypt(encrypt[1].toString());
        32. return result;
        33. }
        34. /**
        35. * 验证URL
        36. * @param msgSignature 签名串,对应URL参数的msg_signature
        37. * @param timeStamp 时间戳,对应URL参数的timestamp
        38. * @param nonce 随机串,对应URL参数的nonce
        39. * @param echoStr 随机串,对应URL参数的echostr
        40. *
        41. * @return 解密之后的echostr
        42. * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
        43. */
        44. public String VerifyURL(String msgSignature, String timeStamp, String nonce, String echoStr)
        45. throws AesException {
        46. String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
        47. if (!signature.equals(msgSignature)) {
        48. throw new AesException(AesException.ValidateSignatureError);
        49. }
        50. String result = decrypt(echoStr);
        51. return result;
        52. }
        53. public String getXmlTextMessage(String FromUserName,String ToUserName, String sendMsgText){
        54. // 文本消息
        55. String timestamp = Long.toString(System.currentTimeMillis()/1000L);
        56. return "" +
        57. " +FromUserName+"]]>" +
        58. " +ToUserName+"]]>" +
        59. " "+timestamp+"" +
        60. " " +
        61. " +sendMsgText+"]]>" +
        62. "";
        63. }
        64. public String getXmlNewsMessage(String FromUserName,String ToUserName, String Title, String Description, String Url, String PicUrl){
        65. // 图文消息
        66. String timestamp = Long.toString(System.currentTimeMillis()/1000L);
        67. return "" +
        68. " +FromUserName+"]]>" +
        69. " +ToUserName+"]]>" +
        70. " "+timestamp+"" +
        71. " " +
        72. " " +
        73. " 1" +
        74. " " +
        75. " " +
        76. " <![CDATA["</span>+Title+<span class="hljs-string">"]]>" +
        77. " +Description+"]]>" +
        78. " +Url+"]]>" +
        79. " +PicUrl+"]]>" +
        80. " " +
        81. " " +
        82. " 0" +
        83. "";
        84. }
        85. }
        86. 5、WxUtil.java

          1. package cn.renkai721.util;
          2. import org.jdom2.Document;
          3. import org.jdom2.Element;
          4. import org.jdom2.JDOMException;
          5. import org.jdom2.input.SAXBuilder;
          6. import java.io.ByteArrayInputStream;
          7. import java.io.IOException;
          8. import java.io.InputStream;
          9. import java.util.*;
          10. public class WxUtil {
          11. /**
          12. * 将 Map 转化为 XML
          13. *
          14. * @param map
          15. * @return
          16. */
          17. public static String transferMapToXml(SortedMap map) {
          18. StringBuffer sb = new StringBuffer();
          19. sb.append("");
          20. for (String key : map.keySet()) {
          21. sb.append("<").append(key).append(">")
          22. .append(map.get(key))
          23. .append(").append(key).append(">");
          24. }
          25. return sb.append("").toString();
          26. }
          27. /**
          28. * 将 XML 转化为 map
          29. *
          30. * @param strxml
          31. * @return
          32. * @throws IOException
          33. */
          34. public static Map transferXmlToMap(String strxml) throws IOException {
          35. strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
          36. if (null == strxml || "".equals(strxml)) {
          37. return null;
          38. }
          39. Map m = new HashMap();
          40. InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
          41. SAXBuilder builder = new SAXBuilder();
          42. Document doc = null;
          43. try {
          44. doc = builder.build(in);
          45. } catch (JDOMException e) {
          46. throw new IOException(e.getMessage()); // 统一转化为 IO 异常输出
          47. }
          48. // 解析 DOM
          49. Element root = doc.getRootElement();
          50. List list = root.getChildren();
          51. Iterator it = list.iterator();
          52. while (it.hasNext()) {
          53. Element e = (Element) it.next();
          54. String k = e.getName();
          55. String v = "";
          56. List children = e.getChildren();
          57. if (children.isEmpty()) {
          58. v = e.getTextNormalize();
          59. } else {
          60. v = getChildrenText(children);
          61. }
          62. m.put(k, v);
          63. }
          64. //关闭流
          65. in.close();
          66. return m;
          67. }
          68. // 辅助 transferXmlToMap 方法递归提取子节点数据
          69. private static String getChildrenText(List children) {
          70. StringBuffer sb = new StringBuffer();
          71. if (!children.isEmpty()) {
          72. Iterator it = children.iterator();
          73. while (it.hasNext()) {
          74. Element e = (Element) it.next();
          75. String name = e.getName();
          76. String value = e.getTextNormalize();
          77. List list = e.getChildren();
          78. sb.append("<" + name + ">");
          79. if (!list.isEmpty()) {
          80. sb.append(getChildrenText(list));
          81. }
          82. sb.append(value);
          83. sb.append(" + name + ">");
          84. }
          85. }
          86. return sb.toString();
          87. }
          88. }

          6、XmlUtil.java

          1. package cn.renkai721.util;
          2. import javax.xml.bind.JAXBContext;
          3. import javax.xml.bind.Unmarshaller;
          4. import java.io.StringReader;
          5. public class XmlUtil {
          6. /**
          7. * 解析XMl内容,转换为POJO类
          8. *
          9. * @param clazz 要解析的对象
          10. * @param xml 解析的xml字符串
          11. * @return 解析完成的对象
          12. */
          13. public static Object xmlStrToObject(Class clazz, String xml) {
          14. Object xmlObject = null;
          15. try {
          16. JAXBContext context = JAXBContext.newInstance(clazz);
          17. // 进行将Xml转成对象的核心接口
          18. Unmarshaller unmarshaller = context.createUnmarshaller();
          19. StringReader sr = new StringReader(xml);
          20. xmlObject = unmarshaller.unmarshal(sr);
          21. } catch (Exception e) {
          22. e.printStackTrace();
          23. }
          24. return xmlObject;
          25. }
          26. }

          7、AesException.java

          1. package cn.renkai721.wechataes;
          2. @SuppressWarnings("serial")
          3. public class AesException extends Exception {
          4. public final static int OK = 0;
          5. public final static int ValidateSignatureError = -40001;
          6. public final static int ParseXmlError = -40002;
          7. public final static int ComputeSignatureError = -40003;
          8. public final static int IllegalAesKey = -40004;
          9. public final static int ValidateCorpidError = -40005;
          10. public final static int EncryptAESError = -40006;
          11. public final static int DecryptAESError = -40007;
          12. public final static int IllegalBuffer = -40008;
          13. //public final static int EncodeBase64Error = -40009;
          14. //public final static int DecodeBase64Error = -40010;
          15. //public final static int GenReturnXmlError = -40011;
          16. private int code;
          17. private static String getMessage(int code) {
          18. switch (code) {
          19. case ValidateSignatureError:
          20. return "签名验证错误";
          21. case ParseXmlError:
          22. return "xml解析失败";
          23. case ComputeSignatureError:
          24. return "sha加密生成签名失败";
          25. case IllegalAesKey:
          26. return "SymmetricKey非法";
          27. case ValidateCorpidError:
          28. return "corpid校验失败";
          29. case EncryptAESError:
          30. return "aes加密失败";
          31. case DecryptAESError:
          32. return "aes解密失败";
          33. case IllegalBuffer:
          34. return "解密后得到的buffer非法";
          35. // case EncodeBase64Error:
          36. // return "base64加密错误";
          37. // case DecodeBase64Error:
          38. // return "base64解密错误";
          39. // case GenReturnXmlError:
          40. // return "xml生成失败";
          41. default:
          42. return null; // cannot be
          43. }
          44. }
          45. public int getCode() {
          46. return code;
          47. }
          48. AesException(int code) {
          49. super(getMessage(code));
          50. this.code = code;
          51. }
          52. }

          8、ByteGroup.java

          1. package cn.renkai721.wechataes;
          2. import java.util.ArrayList;
          3. public class ByteGroup {
          4. ArrayList byteContainer = new ArrayList();
          5. public byte[] toBytes() {
          6. byte[] bytes = new byte[byteContainer.size()];
          7. for (int i = 0; i < byteContainer.size(); i++) {
          8. bytes[i] = byteContainer.get(i);
          9. }
          10. return bytes;
          11. }
          12. public ByteGroup addBytes(byte[] bytes) {
          13. for (byte b : bytes) {
          14. byteContainer.add(b);
          15. }
          16. return this;
          17. }
          18. public int size() {
          19. return byteContainer.size();
          20. }
          21. }

          9、D3fService.java

          1. package cn.renkai721.biz;
          2. import cn.renkai721.bean.*;
          3. import cn.renkai721.configuration.QywxProperties;
          4. import cn.renkai721.util.HttpUtil;
          5. import cn.renkai721.util.MsgUtil;
          6. import com.alibaba.druid.util.StringUtils;
          7. import com.alibaba.fastjson.JSON;
          8. import com.alibaba.fastjson.JSONObject;
          9. import lombok.extern.slf4j.Slf4j;
          10. import org.redisson.api.RBucket;
          11. import org.redisson.api.RedissonClient;
          12. import org.springframework.http.ResponseEntity;
          13. import org.springframework.stereotype.Component;
          14. import org.springframework.web.client.RestTemplate;
          15. import javax.annotation.Resource;
          16. import java.util.*;
          17. import java.util.concurrent.TimeUnit;
          18. @Slf4j
          19. @Component
          20. public class D3fBiz {
          21. @Resource
          22. private RedissonClient redissonClient;
          23. @Resource
          24. private RestTemplate restTemplate;
          25. public String get_suite_ticket(){
          26. RBucket idBucket = redissonClient.getBucket(QywxProperties.suite_ticket_key);
          27. String get_suite_ticket = idBucket.get();
          28. return get_suite_ticket;
          29. }
          30. public String get_suite_access_token(){
          31. RBucket idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
          32. String suite_access_token = idBucket.get();
          33. log.info("suite_access_token={}",suite_access_token);
          34. if(StringUtils.isEmpty(suite_access_token)){
          35. String suite_ticket = this.get_suite_ticket();
          36. // 如果上线后,没有最新的suite,手动在企微控制台点击刷新ticket
          37. // 通过本接口获取的suite_access_token有效期为2小时,开发者需要进行缓存,不可频繁获取。
          38. // 参考地址=https://work.weixin.qq.com/api/doc/90001/90143/90600
          39. String url1= "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
          40. Map paramMap1 = new HashMap<>();
          41. paramMap1.put("suite_id", MsgUtil.val(QywxProperties.suite_id_key));
          42. paramMap1.put("suite_secret", MsgUtil.val(QywxProperties.suite_secret_key));
          43. paramMap1.put("suite_ticket", suite_ticket);
          44. String postData1 = HttpUtil.sendPost(url1, JSONObject.toJSONString(paramMap1));
          45. log.info("get_suite_token={}",postData1);
          46. suite_access_token = JSON.parseObject(postData1).getString(QywxProperties.suite_access_token_key);
          47. String expires_in = JSON.parseObject(postData1).getString("expires_in");
          48. if(!StringUtils.isEmpty(expires_in)){
          49. idBucket.set(suite_access_token,Integer.parseInt(expires_in), TimeUnit.SECONDS);
          50. }else{
          51. log.error("get_suite_token api is error");
          52. }
          53. }
          54. return suite_access_token;
          55. }
          56. public String get_access_token(String corpId){
          57. String suite_access_token = this.get_suite_access_token();
          58. RBucket idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
          59. String corpIdAndAgentId = idBucket.get();
          60. log.info("corpIdAndAgentId={}",corpIdAndAgentId);
          61. String permanent_code = corpIdAndAgentId.split(";")[3];
          62. Map paramMap1 = new HashMap<>();
          63. // 获取企业access_token
          64. idBucket = redissonClient.getBucket(QywxProperties.access_token_key+"_"+corpId);
          65. String access_token = idBucket.get();
          66. log.info("access_token={}",access_token);
          67. if(StringUtils.isEmpty(access_token)){
          68. String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token="+suite_access_token;
          69. paramMap1 = new HashMap<>();
          70. paramMap1.put("auth_corpid", corpId);
          71. paramMap1.put("permanent_code", permanent_code);
          72. String postData1 = HttpUtil.sendPost(url1, JSONObject.toJSONString(paramMap1));
          73. log.info("get_corp_token={}",postData1);
          74. access_token = JSON.parseObject(postData1).getString("access_token");
          75. String expires_in = JSON.parseObject(postData1).getString("expires_in");
          76. if(!StringUtils.isEmpty(expires_in)){
          77. idBucket.set(access_token,Integer.parseInt(expires_in), TimeUnit.SECONDS);
          78. }else{
          79. log.error("get_corp_token is error");
          80. }
          81. }
          82. return access_token;
          83. }
          84. public void sendD3fTextMsg(String corpId, String toUser, String message){
          85. log.info("sendD3fTextMsg corpId={},toUser={},message={}"
          86. ,corpId,toUser,message);
          87. RBucket idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
          88. String corpIdAndAgentId = idBucket.get();
          89. log.info("corpIdAndAgentId={}",corpIdAndAgentId);
          90. String agentId = corpIdAndAgentId.split(";")[2];
          91. String access_token = this.get_access_token(corpId);
          92. String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
          93. MsgRequestDTO requestData = new MsgRequestDTO();
          94. requestData.setAgentid(Integer.parseInt(agentId));
          95. requestData.setTouser(toUser);
          96. requestData.setMsgtype("text");
          97. Map text = new HashMap<>();
          98. text.put("content", message);
          99. requestData.setText(text);
          100. log.info("sendD3fTextMsg requestData={}",requestData);
          101. ResponseEntity postForEntity = restTemplate.postForEntity(msgUrl, requestData, MsgResult.class);
          102. log.info("sendD3fTextMsg postForEntity={}",postForEntity);
          103. }
          104. public void sendD3fNewsMsg(String corpId, String toUser, String Title,
          105. String Description, String Url, String PicUrl){
          106. log.info("sendD3fNewsMsg corpId={},toUser={},Title={},Description={},Url={},PicUrl={},"
          107. ,corpId,toUser,Title,Description,Url,PicUrl);
          108. RBucket idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
          109. String corpIdAndAgentId = idBucket.get();
          110. log.info("corpIdAndAgentId={}",corpIdAndAgentId);
          111. String agentId = corpIdAndAgentId.split(";")[2];
          112. String access_token = this.get_access_token(corpId);
          113. String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
          114. Map body = new HashMap<>();
          115. body.put("touser",toUser);
          116. body.put("msgtype","news");
          117. body.put("agentid",Integer.parseInt(agentId));
          118. Map news = new HashMap<>();
          119. List articles = new ArrayList();
          120. Map article = new HashMap<>();
          121. article.put("title",Title);
          122. if(!StringUtils.isEmpty(Description)){
          123. article.put("description",Description);
          124. }
          125. if(!StringUtils.isEmpty(Url)){
          126. article.put("url",Url);
          127. }
          128. article.put("picurl",PicUrl);
          129. articles.add(article);
          130. news.put("articles",articles);
          131. body.put("news",news);
          132. JSONObject jsonObject = new JSONObject(body);
          133. log.info("sendNewsMsg body={},",jsonObject);
          134. ResponseEntity postForEntity = restTemplate.postForEntity(msgUrl, jsonObject, MsgResult.class);
          135. log.info("sendNewsMsg postForEntity={}",postForEntity);
          136. }
          137. public void sendMarkdownMsg(String corpId,String toUser,String message) {
          138. log.info("sendMarkdownMsg corpId={},toUser={},message={}"
          139. ,corpId,toUser,message);
          140. RBucket idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
          141. String corpIdAndAgentId = idBucket.get();
          142. log.info("corpIdAndAgentId={}",corpIdAndAgentId);
          143. String agentId = corpIdAndAgentId.split(";")[2];
          144. String access_token = this.get_access_token(corpId);
          145. String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
          146. Map body = new HashMap<>();
          147. body.put("touser",toUser);
          148. body.put("msgtype","markdown");
          149. body.put("agentid",agentId);
          150. Map markdown = new HashMap<>();
          151. markdown.put("content", message);
          152. body.put("markdown",markdown);
          153. JSONObject jsonObject = new JSONObject(body);
          154. log.info("sendMarkdownMsg body={},",jsonObject);
          155. ResponseEntity postForEntity = restTemplate.postForEntity(msgUrl, jsonObject, MsgResult.class);
          156. log.info("sendMarkdownMsg={}",postForEntity);
          157. }
          158. }

           10、开发代码测试的时候,记得把服务器IP添加到白名单,使用管理员登录服务商后台,点击企业信息,然后输入IP。

          第四章 应用上架

          1、开发结束后,登录到企业服务商管理后台,普通的管理员也可以操作。

          2、【应用和模板上线】-【提交上线】-选一个要上线的应用-【确定】。

           3、如果失败了,服务商后台的消息会收到通知,成功也会收到通知。

          4、上线成功后,可以设置应用市场可搜索的配置,发布上线还是要填写一些东西,包括图片,需要美工制作专门格式的图片才可以。

          第五章 企微官方接口及其它参考文章

          企业微信服务商-开发前必读 - 接口文档https://developer.work.weixin.qq.com/document/path/91201企微服务商平台收费接口对接教程_renkai721的博客-CSDN博客_企微服务商前言1、以前的流程是用户添加第三方应用,然后登录,然后操作。2、现在的流程是用户添加第三方应用,然后服务商购买账号,服务商在用户添加第三方应用时或用户登录时或接收到【unlicensed_notify】接口许可失效通知时,授权激活该用户,然后用户登录,然后操作。企微官方文档面向服务商进行平台收费模式调整的说明平台接口许可付费企微服务商后台管理操作教程1、用户在企微应用市场搜索服务商开发的第3方应用,假如应用名字【天气助手】。然后点击安装。2、这时候服务商的后台服务会收到腾讯服https://blog.csdn.net/renkai721/article/details/124970456解读:企微面向服务商进行平台收费模式调整的说明_renkai721的博客-CSDN博客前言1、以前的流程是用户添加第三方应用,然后登录,然后操作。2、现在是服务商购买账号,服务商在用户添加第三方应用时或用户登录时授权激活该用户,然后用户登录,然后操作。企微官方文档面向服务商进行平台收费模式调整的说明平台接口许可付费一、如果不购买【基础帐号】,那么【身份验证】【小程序登录】【发送应用消息】这3个接口无法调用。表现出来的场景为:1、第三方应用和小程序的用户是无法登录的。2、也不能调用接口API发送消息给用户。二、如果不购买【互通帐号】,那么【获取.https://blog.csdn.net/renkai721/article/details/124675211

        87. 相关阅读:
          vue+Ts+element组件封装
          一篇必读的物联网平台物模型开发指南,为你解锁未来科技趋势
          【微信小程序】uni-app 配置网络请求
          [MyBatis] SQL动态标签,SelecKey标签
          C/C++常用关键字详解
          Java_只出现一次的数字
          计算机网络部分(一)
          RxJava/RxAndroid的操作符使用(二)
          SeaweedFS安全配置(Security Configuration)
          Python网络爬虫4-实战爬取pdf
        88. 原文地址:https://blog.csdn.net/renkai721/article/details/126362206