以前不竭不写那篇文章,是以为企微的效劳商使用绝对简朴。第两个启事是近来正在搞钉钉的ISV上架,以是时间没有是很充沛。邪题开端……
第一章效劳 商进驻
一、使用办理员登录效劳商办理背景
企业微疑-效劳商背景-登录地点
https://open.work.weixin.qq.com/wwopen/login二、输出根本疑息及认证
第两章 使用设置
一、登录后,间接创立创立网页使用,以下图。
二、使用概略-使用设置-参考上面的学程。主页地点是牢固的,只要供写进自己的appid战redirect_uri的地点便止。那里需要留神,可托域名必需设置一下,需要留神的是那个一级域名一朝使用的效劳商使用,那末自修使用是没法正在使用那个域名的,即使是差别的两级域名也不成以。那个仍是比力坑,招致咱们从头恳求了一个一级域名去效劳自修使用。
三、可托域名设置,使用设置-面打【编纂】,而后面打【校验可托域名回属】,而后下载那个文献到nginx设置的域名文献夹下,只要颠末步调2的地点能够会见到便算考证颠末。nginx的设置参考上面的那个文章。
nginx设置websocket或者https的转收学程_renkai721的专客-CSDN专客_nginx websocket转收nginx设置http,https,ssl,websocket转收
https://blog.csdn.net/renkai721/article/details/125991270
四、数据回调的设置
第三章 使用开辟
一、pom.xml中增加剖析XML格局实质- <!--XML 剖析包-->
- <dependency>
- <groupId>org.jdom</groupId>
- <artifactId>jdom2</artifactId>
- <version>2.0.6</version>
- </dependency>
- <dependency>
- <groupId>co妹妹ons-codec</groupId>
- <artifactId>co妹妹ons-codec</artifactId>
- <version>1.15</version>
- </dependency>
复造代码 二、properties文献,没有需要那末多,定名更具自己的喜好,那一瞅即是参考了gitee的binarywang/weixin-java-cp-demo,那个demo假设入门者能够瞅瞅,而后自己启拆。
三、中心解稀controller.java- package cn.renkai721.controller;
- import cn.renkai721.bean.*;
- import cn.renkai721.configuration.QywxProperties;
- import cn.renkai721.service.*;
- import cn.renkai721.util.HttpUtil;
- import cn.renkai721.util.MsgUtil;
- import cn.renkai721.util.WxUtil;
- import cn.renkai721.wechataes.WXBizMsgCrypt;
- import com.alibaba.druid.util.StringUtils;
- import com.alibaba.fastjson.JSON;
- import lombok.extern.slf4j.Slf4j;
- import org.redisson.api.RBucket;
- import org.redisson.api.RedissonClient;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.ResponseEntity;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.client.RestTemplate;
- import javax.annotation.Resource;
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.Map;
- @EnableAsync
- @RestController
- @RequestMapping("/d3f")
- @Slf4j
- public class D3f2Controller {
- @Resource
- private RedissonClient redissonClient;
- @Autowired
- private RestTemplate restTemplate;
- @Autowired
- private D3fService d3fService;
- @GetMapping(produces = "text/plain;charset=utf-8")
- public void d3fGet(@RequestParam(name = "msg_signature", required = false) String signature,
- @RequestParam(name = "timestamp", required = false) String timestamp,
- @RequestParam(name = "nonce", required = false) String nonce,
- @RequestParam(name = "echostr", required = false) String echostr,
- HttpServletResponse response) throws Exception {
- response.setContentType("text/html;charset=utf-8");
- response.setStatus(HttpServletResponse.SC_OK);
- WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(
- MsgUtil.val("wechat.cp.appConfigs[0].token"),
- MsgUtil.val("wechat.cp.appConfigs[0].aesKey"),
- MsgUtil.val("wechat.cp.corpId"));
- // 需要前去的明文
- String sEchoStr = "";
- try {
- sEchoStr = wxcpt.VerifyURL(signature, timestamp, nonce, echostr);
- log.info("resp sEchoStr={}",sEchoStr);
- response.getWriter().print(sEchoStr);
- return;
- } catch (Exception e) {
- // 考证URL失利,毛病启事请检察非常
- e.printStackTrace();
- }
- response.getWriter().print("不法恳求");
- return;
- }
- @PostMapping(produces = "application/xml; charset=UTF-8")
- public void d3fPost(@RequestParam("msg_signature") String signature,
- @RequestParam("timestamp") String timestamp,
- @RequestParam("nonce") String nonce,
- HttpServletResponse response,
- HttpServletRequest request) throws Exception {
- String success = "success";
- String type = request.getParameter("type");
- String corpid = request.getParameter("corpid");
- log.info("领受d3f post恳求:[signature=[{}], timestamp=[{}], nonce=[{}], type=[{}], corpid=[{}] ]",
- signature, timestamp, nonce, type, corpid);
- try{
- response.setContentType("text/html;charset=utf-8");
- response.setStatus(HttpServletResponse.SC_OK);
- String id = "";
- //拜访 使用战企业回调传差别的ID
- if("data".equals(type)){
- // 企微背景树立【数据回调URL】的链交为https://wx.naturobot.com/qywx/d3f?type=data&corpid=$CORPID$
- id = corpid;
- } else {
- id = MsgUtil.val("suite_id");
- }
- WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(MsgUtil.val(
- "wechat.cp.appConfigs[0].token"),
- MsgUtil.val("wechat.cp.appConfigs[0].aesKey"),
- id);
- // 稀文,对于应POST恳求的数据
- String postData = "";
- // 获得减稀的恳求消息:使用输出流得到减稀恳求消息postData
- ServletInputStream in = request.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- // 动作输出字符串的临时串,用于鉴别可否读与结束
- String tempStr = "";
- while(null != (tempStr=reader.readLine())){
- postData += tempStr;
- }
- String suiteXml = wxcpt.DecryptMsg(signature, timestamp, nonce, postData);
- Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
- log.info("\n req map={}", suiteMap);
- if("suite_ticket".equals(suiteMap.get("InfoType"))){
- // 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
- // 主动拉收SuiteTicket间接写进
- // 每一十分钟革新一次
- //suite_ticket理论有用期为30分钟,
- String suite_ticket_value = (String) suiteMap.get("SuiteTicket");
- String SuiteId = (String) suiteMap.get("SuiteId");
- log.info("suite_ticket={},SuiteId={}",suite_ticket_value,SuiteId);
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.suite_ticket_key);
- idBucket.set(suite_ticket_value);
- // 挪用企业微疑交心
- d3fService.get_suite_access_token();
- }else if("create_auth".equals(suiteMap.get("InfoType"))){
- String authCode = (String) suiteMap.get("AuthCode");
- // SuiteId代表一个企业,相称于suite_id
- String SuiteId = (String) suiteMap.get("SuiteId");
- log.info("第三圆使用尝试上线,AuthCode={},SuiteId={}",authCode,SuiteId);
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.authCode_key+"_"+SuiteId);
- idBucket.set(authCode);
- // 获得企业永久受权码
- idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
- String suite_access_token = idBucket.get();
- String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token="+suite_access_token;
- PermanentReqBean permanentReqBean = new PermanentReqBean();
- permanentReqBean.setAuth_code(authCode);
- ResponseEntity<PermanentRespBean> postForEntity1 = restTemplate.postForEntity(url1, permanentReqBean, PermanentRespBean.class);
- log.info("get_permanent_code={}",postForEntity1.getBody());
- if(postForEntity1.getBody().getExpires_in() != null){
- String authCorpId = postForEntity1.getBody().getAuth_corp_info().getCorpid();
- log.info("永久受权码中获得的第三圆使用的authCorpId={}",authCorpId);
- String userIdD3f = postForEntity1.getBody().getAuth_user_info().getUserid();
- // 间接与第一个
- String agentId = postForEntity1.getBody().getAuth_info().getAgent().get(0).getAgentid();
- String permanent_code_access_token = postForEntity1.getBody().getAccess_token();
- String permanent_code = postForEntity1.getBody().getPermanent_code();
- log.info("permanent_code={}",permanent_code);
- String open_userid = postForEntity1.getBody().getAuth_user_info().getOpen_userid();
- // 能够树立企业的容许主动激活形状
- // 那里面的工具需要保留下来,否则前面使用的时候不了便垮台了
- // 那里面的工具需要保留下来,否则前面使用的时候不了便垮台了
- // 那里面的工具需要保留下来,否则前面使用的时候不了便垮台了
- }else{
- log.error("get_permanent_code api is error");
- }
- }else if("cancel_auth".equals(suiteMap.get("InfoType"))){
- String AuthCorpId = (String) suiteMap.get("AuthCorpId");
- log.info("打消定阅cancel_auth AuthCorpId={}",AuthCorpId);
- }
- if("unlicensed_notify".equals(suiteMap.get("Event"))){
- // 该用户帐号已受权
- String AgentID = (String) suiteMap.get("AgentID");
- String ToUserName = (String) suiteMap.get("ToUserName");
- String FromUserName = (String) suiteMap.get("FromUserName");
- log.info("用户帐号不保守受权,需要受权");
- }else if("change_app_admin".equals(suiteMap.get("Event"))){
- String AgentID = (String) suiteMap.get("AgentID");
- // ToUserName=corpId
- String ToUserName = (String) suiteMap.get("ToUserName");
- log.info("第三圆使用change_app_admin,ToUserName={},AgentID={}",ToUserName,AgentID);
- }else if("subscribe".equals(suiteMap.get("Event"))){
- log.info("新用户存眷,user={}",suiteMap);
- // 复兴感谢存眷
- String ToUserName = (String) suiteMap.get("ToUserName");
- String FromUserName = (String) suiteMap.get("FromUserName");
- String AgentID = (String) suiteMap.get("AgentID");
- // 获得临时受权码
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
- String suite_access_token = idBucket.get();
- String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=" + suite_access_token;
- String postData1 = HttpUtil.sendGet(url1);
- log.info("get_pre_auth_code={}", postData1);
- String subscribe_pre_auth_code = JSON.parseObject(postData1).getString("pre_auth_code");
- String expires_in = JSON.parseObject(postData1).getString("expires_in");
- if(!StringUtils.isEmpty(expires_in)){
- // 树立受权设置
- url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=" + suite_access_token;
- SessionInfoReqBean sessionInfoReqBean = new SessionInfoReqBean();
- sessionInfoReqBean.setPre_auth_code(subscribe_pre_auth_code);
- SessionInfoBean sessionInfoBean = new SessionInfoBean();
- sessionInfoBean.setAppid(new Integer[0]);
- sessionInfoBean.setAuth_type(Integer.parseInt(MsgUtil.val("authType")));
- sessionInfoReqBean.setSession_info(sessionInfoBean);
- log.info("sessionInfoReqBean={}", JSON.toJSONString(sessionInfoReqBean));
- ResponseEntity<SessionInfoRespBean> postForEntity = restTemplate.postForEntity(url1, sessionInfoReqBean, SessionInfoRespBean.class);
- log.info("树立受权设置={}", postForEntity.getBody());
- }else{
- log.error("get_pre_auth_code api is error");
- }
- // 收收XML消息给用户
- String Title = "感谢装置该使用";
- String Description = "咱们的使用很佳用,假设有成就请拨挨德律风021-12345";
- String Url = MsgUtil.val("poster.freeUrl");
- String PicUrl = "https://wx.naturobot.com/qywx/image/bg1.png";
- log.info("Title={},Description={},Url={},PicUrl={},",Title,Description,Url,PicUrl);
- String xmlOutMsg = wxcpt.getXmlNewsMessage(FromUserName,ToUserName,Title,Description,Url,PicUrl);
- success = wxcpt.EncryptMsg(xmlOutMsg, timestamp, nonce);
- }else if("enter_agent".equals(suiteMap.get("Event"))){
- // 用户翻开使用的工作
- }
- if("text".equals(suiteMap.get("MsgType"))){
- // 用户收收了文原消息给使用
- String ToUserName = (String) suiteMap.get("ToUserName");
- String FromUserName = (String) suiteMap.get("FromUserName");
- String AgentID = (String) suiteMap.get("AgentID");
- String xmlOutMsg = wxcpt.getXmlTextMessage(FromUserName,ToUserName,"久已启开谈天功用。");
- success = wxcpt.EncryptMsg(xmlOutMsg, timestamp, nonce);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- response.getWriter().print(success);
- return;
- }
- }
复造代码 四、解稀东西WXBizMsgCrypt.java- /**
- * 对于企业微疑收收给企业背景的消息减解稀示例代码.
- *
- * @copyright Copyright (c) 1998-2014 Tencent Inc.
- */
- // ------------------------------------------------------------------------
- /**
- * 针对于org.apache.co妹妹ons.codec.binary.Base64,
- * 需要导进架包co妹妹ons-codec-1.9(或者co妹妹ons-codec-1.8等其余版原)
- * 民间下载地点:http://co妹妹ons.apache.org/proper/co妹妹ons-codec/download_codec.cgi
- */
- package cn.renkai721.wechataes;
- import org.apache.co妹妹ons.codec.binary.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- import java.nio.charset.Charset;
- import java.util.Arrays;
- import java.util.Random;
- /**
- * 供给领受战拉收给企业微疑消息的减解稀交心(UTF8编码的字符串).
- * <ol>
- * <li>第三圆复兴减稀消息给企业微疑</li>
- * <li>第三圆支到企业微疑收收的消息,考证消息的宁静性,并对于消息截至解稀。</li>
- * </ol>
- *说明 :非常java.security.InvalidKeyException:illegal Key Size的处置计划
- * <ol>
- * <li>正在民间网站下载JCE无限造权力战略文献(JDK7的下载地点:
- * http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>
- * <li>下载后解压,能够瞅到local_policy.jar战US_export_policy.jar和readme.txt</li>
- * <li>假设装置了JRE,将二个jar文献搁到%JRE_HOME%\lib\security目次下笼盖本来的文献</li>
- * <li>假设装置了JDK,将二个jar文献搁到%JDK_HOME%\jre\lib\security目次下笼盖本来文献</li>
- * </ol>
- */
- public class WXBizMsgCrypt {
- static Charset CHARSET = Charset.forName("utf-8");
- Base64 base64 = new Base64();
- byte[] aesKey;
- String token;
- String receiveid;
- /**
- *结构 函数
- * @param token 企业微疑背景,开辟者树立的token
- * @param encodingAesKey 企业微疑背景,开辟者树立的EncodingAESKey
- * @param receiveid, 差别场景寄义差别,详睹文档
- *
- * @throws AesException 施行失利,请检察该非常的毛病码战具体的毛病疑息
- */
- public WXBizMsgCrypt(String token, String encodingAesKey, String receiveid) throws AesException {
- if (encodingAesKey.length() != 43) {
- throw new AesException(AesException.IllegalAesKey);
- }
- this.token = token;
- this.receiveid = receiveid;
- 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没有差异的情况
- System.out.println("------ from_receiveid="+from_receiveid+", receiveid="+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 = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
- // System.out.println("收收给仄台的署名是: " + signature[1].toString());
- // 天生收收的xml
- String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
- System.out.println("call wechat xml message=["+result+"]");
- return result;
- }
- /**
- * 查验消息的实在性,而且获得解稀后的明文.
- * <ol>
- * <li>使用支到的稀文天生宁静署名,截至署名考证</li>
- * <li>若考证颠末,则提炼xml中的减稀消息</li>
- * <li>对于消息截至解稀</li>
- * </ol>
- *
- * @param msgSignature 署名串,对于应URL参数的msg_signature
- * @param timeStamp时间 戳,对于应URL参数的timestamp
- * @param nonce 随机串,对于应URL参数的nonce
- * @param postData 稀文,对于应POST恳求的数据
- *
- * @return 解稀后的本文
- * @throws AesException 施行失利,请检察该非常的毛病码战具体的毛病疑息
- */
- public String DecryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
- throws AesException {
- // 稀钥,公家帐号的app secret
- // 提炼稀文
- Object[] encrypt = XMLParse.extract(postData);
- // 考证宁静署名
- String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());
- // 战URL中的署名比力可否相称
- // System.out.println("第三圆支到URL中的署名:" + msg_sign);
- // System.out.println("第三圆校验署名:" + signature);
- if (!signature.equals(msgSignature)) {
- 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 = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
- if (!signature.equals(msgSignature)) {
- throw new AesException(AesException.ValidateSignatureError);
- }
- String result = decrypt(echoStr);
- return result;
- }
- public String getXmlTextMessage(String FromUserName,String ToUserName, String sendMsgText){
- // 文原消息
- String timestamp = Long.toString(System.currentTimeMillis()/1000L);
- return "<xml>" +
- " <ToUserName><![CDATA["+FromUserName+"]]></ToUserName>" +
- " <FromUserName><![CDATA["+ToUserName+"]]></FromUserName>" +
- " <CreateTime>"+timestamp+"</CreateTime>" +
- " <MsgType><![CDATA[text]]></MsgType>" +
- " <Content><![CDATA["+sendMsgText+"]]></Content>" +
- "</xml>";
- }
- public String getXmlNewsMessage(String FromUserName,String ToUserName, String Title, String Description, String Url, String PicUrl){
- // 图文消息
- String timestamp = Long.toString(System.currentTimeMillis()/1000L);
- return "<xml>" +
- " <ToUserName><![CDATA["+FromUserName+"]]></ToUserName>" +
- " <FromUserName><![CDATA["+ToUserName+"]]></FromUserName>" +
- " <CreateTime>"+timestamp+"</CreateTime>" +
- " <MsgType><![CDATA[news]]></MsgType>" +
- " <Content><![CDATA[]]></Content>" +
- " <ArticleCount>1</ArticleCount>" +
- " <Articles>" +
- " <item>" +
- " <Title><![CDATA["+Title+"]]></Title>" +
- " <Description><![CDATA["+Description+"]]></Description>" +
- " <Url><![CDATA["+Url+"]]></Url>" +
- " <PicUrl><![CDATA["+PicUrl+"]]></PicUrl>" +
- " </item>" +
- " </Articles>" +
- " <FuncFlag>0</FuncFlag>" +
- "</xml>";
- }
- }
复造代码 五、WxUtil.java- package cn.renkai721.util;
- import org.jdom2.Document;
- import org.jdom2.Element;
- import org.jdom2.JDOMException;
- import org.jdom2.input.SAXBuilder;
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.*;
- public class WxUtil {
- /**
- * 将 Map 转移为 XML
- *
- * @param map
- * @return
- */
- public static String transferMapToXml(SortedMap<String, Object> map) {
- StringBuffer sb = new StringBuffer();
- sb.append("<xml>");
- for (String key : map.keySet()) {
- sb.append("<").append(key).append(">")
- .append(map.get(key))
- .append("</").append(key).append(">");
- }
- return sb.append("</xml>").toString();
- }
- /**
- * 将 XML 转移为 map
- *
- * @param strxml
- * @return
- * @throws IOException
- */
- public static Map transferXmlToMap(String strxml) throws IOException {
- strxml = strxml.replaceFirst("encoding=".*"", "encoding="UTF-8"");
- if (null == strxml || "".equals(strxml)) {
- return null;
- }
- Map m = new HashMap();
- InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
- SAXBuilder builder = new SAXBuilder();
- Document doc = null;
- try {
- doc = builder.build(in);
- } catch (JDOMException e) {
- throw new IOException(e.getMessage()); //分歧 转移为 IO 非常输出
- }
- // 剖析 DOM
- Element root = doc.getRootElement();
- List list = root.getChildren();
- Iterator it = list.iterator();
- while (it.hasNext()) {
- Element e = (Element) it.next();
- String k = e.getName();
- String v = "";
- List children = e.getChildren();
- if (children.isEmpty()) {
- v = e.getTextNormalize();
- } else {
- v = getChildrenText(children);
- }
- m.put(k, v);
- }
- //封闭流
- in.close();
- return m;
- }
- //辅佐 transferXmlToMap办法 递回提炼子节面数据
- private static String getChildrenText(List<Element> children) {
- StringBuffer sb = new StringBuffer();
- if (!children.isEmpty()) {
- Iterator<Element> it = children.iterator();
- while (it.hasNext()) {
- Element e = (Element) it.next();
- String name = e.getName();
- String value = e.getTextNormalize();
- List<Element> list = e.getChildren();
- sb.append("<" + name + ">");
- if (!list.isEmpty()) {
- sb.append(getChildrenText(list));
- }
- sb.append(value);
- sb.append("</" + name + ">");
- }
- }
- return sb.toString();
- }
- }
复造代码 六、XmlUtil.java- package cn.renkai721.util;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.Unmarshaller;
- import java.io.StringReader;
- public class XmlUtil {
- /**
- * 剖析XMl实质,变换为POJO类
- *
- * @param clazz 要剖析的工具
- * @param xml 剖析的xml字符串
- * @return 剖析完毕的工具
- */
- public static Object xmlStrToObject(Class clazz, String xml) {
- Object xmlObject = null;
- try {
- JAXBContext context = JAXBContext.newInstance(clazz);
- // 退行将Xml转成工具的中心交心
- Unmarshaller unmarshaller = context.createUnmarshaller();
- StringReader sr = new StringReader(xml);
- xmlObject = unmarshaller.unmarshal(sr);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return xmlObject;
- }
- }
复造代码 七、AesException.java- package cn.renkai721.wechataes;
- @SuppressWarnings("serial")
- 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;
- //public final static int EncodeBase64Error = -40009;
- //public final static int DecodeBase64Error = -40010;
- //public final static int GenReturnXmlError = -40011;
- 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 "Sy妹妹etricKey不法";
- case ValidateCorpidError:
- return "corpid校验失利";
- case EncryptAESError:
- return "aes减稀失利";
- case DecryptAESError:
- return "aes解稀失利";
- case IllegalBuffer:
- return "解稀后获得的buffer不法";
- // case EncodeBase64Error:
- // return "base64减稀毛病";
- // case DecodeBase64Error:
- // return "base64解稀毛病";
- // case GenReturnXmlError:
- // return "xml天生失利";
- default:
- return null; // cannot be
- }
- }
- public int getCode() {
- return code;
- }
- AesException(int code) {
- super(getMessage(code));
- this.code = code;
- }
- }
复造代码 8、ByteGroup.java- package cn.renkai721.wechataes;
- import java.util.ArrayList;
- public 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();
- }
- }
复造代码 九、D3fService.java- package cn.renkai721.biz;
- import cn.renkai721.bean.*;
- import cn.renkai721.configuration.QywxProperties;
- import cn.renkai721.util.HttpUtil;
- import cn.renkai721.util.MsgUtil;
- import com.alibaba.druid.util.StringUtils;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import lombok.extern.slf4j.Slf4j;
- import org.redisson.api.RBucket;
- import org.redisson.api.RedissonClient;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Component;
- import org.springframework.web.client.RestTemplate;
- import javax.annotation.Resource;
- import java.util.*;
- import java.util.concurrent.TimeUnit;
- @Slf4j
- @Component
- public class D3fBiz {
- @Resource
- private RedissonClient redissonClient;
- @Resource
- private RestTemplate restTemplate;
- public String get_suite_ticket(){
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.suite_ticket_key);
- String get_suite_ticket = idBucket.get();
- return get_suite_ticket;
- }
- public String get_suite_access_token(){
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.suite_access_token_key);
- String suite_access_token = idBucket.get();
- log.info("suite_access_token={}",suite_access_token);
- if(StringUtils.isEmpty(suite_access_token)){
- String suite_ticket = this.get_suite_ticket();
- //假设 上线后,不最新的suite,脚动正在企微掌握台面打革新ticket
- // 颠末原交心获得的suite_access_token有用期为2小时,开辟者需要截至慢存,不成频仍获得。
- // 参照地点=https://work.weixin.qq.com/api/doc/90001/90143/90600
- String url1= "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
- Map<String, Object> paramMap1 = new HashMap<>();
- paramMap1.put("suite_id", MsgUtil.val(QywxProperties.suite_id_key));
- paramMap1.put("suite_secret", MsgUtil.val(QywxProperties.suite_secret_key));
- paramMap1.put("suite_ticket", suite_ticket);
- String postData1 = HttpUtil.sendPost(url1, JSONObject.toJSONString(paramMap1));
- log.info("get_suite_token={}",postData1);
- suite_access_token = JSON.parseObject(postData1).getString(QywxProperties.suite_access_token_key);
- String expires_in = JSON.parseObject(postData1).getString("expires_in");
- if(!StringUtils.isEmpty(expires_in)){
- idBucket.set(suite_access_token,Integer.parseInt(expires_in), TimeUnit.SECONDS);
- }else{
- log.error("get_suite_token api is error");
- }
- }
- return suite_access_token;
- }
- public String get_access_token(String corpId){
- String suite_access_token = this.get_suite_access_token();
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
- String corpIdAndAgentId = idBucket.get();
- log.info("corpIdAndAgentId={}",corpIdAndAgentId);
- String permanent_code = corpIdAndAgentId.split(";")[3];
- Map paramMap1 = new HashMap<>();
- // 获得企业access_token
- idBucket = redissonClient.getBucket(QywxProperties.access_token_key+"_"+corpId);
- String access_token = idBucket.get();
- log.info("access_token={}",access_token);
- if(StringUtils.isEmpty(access_token)){
- String url1 = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token="+suite_access_token;
- paramMap1 = new HashMap<>();
- paramMap1.put("auth_corpid", corpId);
- paramMap1.put("permanent_code", permanent_code);
- String postData1 = HttpUtil.sendPost(url1, JSONObject.toJSONString(paramMap1));
- log.info("get_corp_token={}",postData1);
- access_token = JSON.parseObject(postData1).getString("access_token");
- String expires_in = JSON.parseObject(postData1).getString("expires_in");
- if(!StringUtils.isEmpty(expires_in)){
- idBucket.set(access_token,Integer.parseInt(expires_in), TimeUnit.SECONDS);
- }else{
- log.error("get_corp_token is error");
- }
- }
- return access_token;
- }
- public void sendD3fTextMsg(String corpId, String toUser, String message){
- log.info("sendD3fTextMsg corpId={},toUser={},message={}"
- ,corpId,toUser,message);
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
- String corpIdAndAgentId = idBucket.get();
- log.info("corpIdAndAgentId={}",corpIdAndAgentId);
- String agentId = corpIdAndAgentId.split(";")[2];
- String access_token = this.get_access_token(corpId);
- String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
- MsgRequestDTO requestData = new MsgRequestDTO();
- requestData.setAgentid(Integer.parseInt(agentId));
- requestData.setTouser(toUser);
- requestData.setMsgtype("text");
- Map<String,String> text = new HashMap<>();
- text.put("content", message);
- requestData.setText(text);
- log.info("sendD3fTextMsg requestData={}",requestData);
- ResponseEntity<MsgResult> postForEntity = restTemplate.postForEntity(msgUrl, requestData, MsgResult.class);
- log.info("sendD3fTextMsg postForEntity={}",postForEntity);
- }
- public void sendD3fNewsMsg(String corpId, String toUser, String Title,
- String Description, String Url, String PicUrl){
- log.info("sendD3fNewsMsg corpId={},toUser={},Title={},Description={},Url={},PicUrl={},"
- ,corpId,toUser,Title,Description,Url,PicUrl);
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
- String corpIdAndAgentId = idBucket.get();
- log.info("corpIdAndAgentId={}",corpIdAndAgentId);
- String agentId = corpIdAndAgentId.split(";")[2];
- String access_token = this.get_access_token(corpId);
- String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
- Map<String, Object> body = new HashMap<>();
- body.put("touser",toUser);
- body.put("msgtype","news");
- body.put("agentid",Integer.parseInt(agentId));
- Map<String, Object> news = new HashMap<>();
- List articles = new ArrayList();
- Map<String, Object> article = new HashMap<>();
- article.put("title",Title);
- if(!StringUtils.isEmpty(Description)){
- article.put("description",Description);
- }
- if(!StringUtils.isEmpty(Url)){
- article.put("url",Url);
- }
- article.put("picurl",PicUrl);
- articles.add(article);
- news.put("articles",articles);
- body.put("news",news);
- JSONObject jsonObject = new JSONObject(body);
- log.info("sendNewsMsg body={},",jsonObject);
- ResponseEntity<MsgResult> postForEntity = restTemplate.postForEntity(msgUrl, jsonObject, MsgResult.class);
- log.info("sendNewsMsg postForEntity={}",postForEntity);
- }
- public void sendMarkdownMsg(String corpId,String toUser,String message) {
- log.info("sendMarkdownMsg corpId={},toUser={},message={}"
- ,corpId,toUser,message);
- RBucket<String> idBucket = redissonClient.getBucket(QywxProperties.corpId_suiteId_agentId+"_"+corpId);
- String corpIdAndAgentId = idBucket.get();
- log.info("corpIdAndAgentId={}",corpIdAndAgentId);
- String agentId = corpIdAndAgentId.split(";")[2];
- String access_token = this.get_access_token(corpId);
- String msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
- Map<String, Object> body = new HashMap<>();
- body.put("touser",toUser);
- body.put("msgtype","markdown");
- body.put("agentid",agentId);
- Map<String,String> markdown = new HashMap<>();
- markdown.put("content", message);
- body.put("markdown",markdown);
- JSONObject jsonObject = new JSONObject(body);
- log.info("sendMarkdownMsg body={},",jsonObject);
- ResponseEntity<MsgResult> postForEntity = restTemplate.postForEntity(msgUrl, jsonObject, MsgResult.class);
- log.info("sendMarkdownMsg={}",postForEntity);
- }
- }
复造代码 十、开辟代码尝试的时候,忘患上把效劳器IP增加到利剑名单,使用办理员登录效劳商背景,面打企业疑息,而后输出IP。
第四章 使用上架
一、开辟完毕后,登录到企业效劳商办理背景,一般的办理员也能够操纵。
二、【使用战模板上线】-【提接上线】-选一个要上线的使用-【肯定】。
三、假设失利了,效劳商背景的消息会支到报告,胜利也会支到报告。
四、上线胜利后,能够树立使用商场可搜刮的设置,公布上线仍是要挖写一点儿工具,包罗图片,需要好工制作特地格局的图片才能够。
第五章 企微民间交心及别的参照文章
企业微佩服务商-开辟前必读 - 交心文档
https://developer.work.weixin.qq.com/document/path/91201企微效劳商仄台免费交心连接学程_renkai721的专客-CSDN专客_企微效劳商媒介一、从前的过程是用户增加第三圆使用,而后登录,而后操纵。二、现在的过程是用户增加第三圆使用,而后效劳商购置账号,效劳商正在用户增加第三圆使用时或者用户登录时或者领受到【unlicensed_notify】交心容许生效报告时,受权激该死用户,而后用户登录,而后操纵。企微民间文档里背效劳商截至仄台免费情势调解的分析仄台交心容许付费企微效劳商背景办理操纵学程一、用户正在企微使用商场搜刮效劳商开辟的第3圆使用,假设使用名字【气候帮忙】。而后面打装置。二、这时候分效劳商的背景效劳会支到腾讯服
https://blog.csdn.net/renkai721/article/details/124970456解读:企微里背效劳商截至仄台免费情势调解的分析_renkai721的专客-CSDN专客媒介一、从前的过程是用户增加第三圆使用,而后登录,而后操纵。二、现在是效劳商购置账号,效劳商正在用户增加第三圆使用时或者用户登录时受权激该死用户,而后用户登录,而后操纵。企微民间文档里背效劳商截至仄台免费情势调解的分析仄台交心容许付费1、假设没有购置【根底帐号】,那末【身份考证】【女伶 href="https://www.taojin168.com/cloud/" target="_blank">小法式登录】【收收使用消息】那3个交心没法挪用。表示进去的场景为:一、第三圆使用战小法式的用户是没法登录的。二、也不克不及挪用交心API收收消息给用户。2、假设没有购置【互通帐号】,那末【获得.
https://blog.csdn.net/renkai721/article/details/124675211 |