WeChatUtil.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package com.xjrsoft.common.utils;
  2. import cn.hutool.core.util.StrUtil;
  3. import cn.hutool.extra.spring.SpringUtil;
  4. import cn.hutool.http.HttpUtil;
  5. import com.alibaba.fastjson.JSONArray;
  6. import com.alibaba.fastjson.JSONObject;
  7. import com.xjrsoft.common.enums.WeChatType;
  8. import com.xjrsoft.module.organization.dto.WeChatDepartDto;
  9. import com.xjrsoft.module.organization.dto.WeChatUserDto;
  10. import com.xjrsoft.module.system.vo.WeChatUserInfo;
  11. import lombok.Data;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.beans.factory.annotation.Value;
  14. import org.springframework.stereotype.Component;
  15. import java.io.UnsupportedEncodingException;
  16. import java.security.MessageDigest;
  17. import java.security.NoSuchAlgorithmException;
  18. import java.util.Formatter;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.UUID;
  22. @Component
  23. @Data
  24. @Slf4j
  25. public class WeChatUtil {
  26. @Value("${xjrsoft.enterpriseWeChat.corpid}")
  27. public String appKey;
  28. @Value("${xjrsoft.enterpriseWeChat.secret}")
  29. public String appSecret;
  30. @Value("${xjrsoft.enterpriseWeChat.secret1}")
  31. public String appSecret1;
  32. @Value("${xjrsoft.enterpriseWeChat.agentid}")
  33. public Integer agentid;
  34. @Value("${xjrsoft.mpWeChat.appKey}")
  35. public String mpAppKey;
  36. @Value("${xjrsoft.mpWeChat.appSecret}")
  37. public String mpAppSecret;
  38. @Value("${xjrsoft.appletWeChat.appKey}")
  39. public String appletAppKey;
  40. @Value("${xjrsoft.appletWeChat.appSecret}")
  41. public String appletAppSecret;
  42. @Value("${xjrsoft.weChatMessageTemplate.commonTemplate}")
  43. public String commonTemplate;
  44. @Value("${xjrsoft.weChatMessageTemplate.assessmentTemplate}")
  45. public String assessmentTemplate;
  46. //考勤结果通知模板
  47. @Value("${xjrsoft.weChatMessageTemplate.attendanceMessageTemplate}")
  48. public String attendanceMessageTemplate;
  49. @Value("${xjrsoft.weChatMessageTemplate.outInTemplate}")
  50. public String outInTemplate;
  51. @Value("${xjrsoft.weChatMessageTemplate.attenDanceWarnTemplate}")
  52. public String attenDanceWarnTemplate;
  53. //公众号获取Openid
  54. public WeChatUserInfo getMpOpenid(String code) {
  55. HashMap<String, Object> paramMap = new HashMap<>();
  56. paramMap.put("appid", mpAppKey);
  57. paramMap.put("secret", mpAppSecret);
  58. paramMap.put("code", code);
  59. paramMap.put("grant_type", "authorization_code");
  60. String result = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", paramMap);
  61. JSONObject jsonObject = JSONObject.parseObject(result);
  62. if (jsonObject.containsKey("errcode")) {
  63. //throw new MyException(result);
  64. return null;
  65. }
  66. return jsonObject.toJavaObject(WeChatUserInfo.class);
  67. }
  68. // 小程序
  69. public WeChatUserInfo getOpenid(String code) {
  70. HashMap<String, Object> paramMap = new HashMap<>();
  71. paramMap.put("appid", appletAppKey);
  72. paramMap.put("secret", appletAppSecret);
  73. paramMap.put("js_code", code);
  74. paramMap.put("grant_type", "authorization_code");
  75. String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", paramMap);
  76. JSONObject jsonObject = JSONObject.parseObject(result);
  77. if (jsonObject.containsKey("errcode")) {
  78. //throw new MyException(result);
  79. return null;
  80. }
  81. return jsonObject.toJavaObject(WeChatUserInfo.class);
  82. }
  83. //获取通讯录或发消息token
  84. public String getToken(WeChatType type) {
  85. HashMap<String, Object> paramMap = new HashMap<>();
  86. String url = "https://api.weixin.qq.com/cgi-bin/token";
  87. String key = "";
  88. if (WeChatType.WEMINI == type) {
  89. url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
  90. paramMap.put("corpsecret", appSecret);
  91. paramMap.put("corpid", appKey);
  92. key = String.format("access_token_%s",appKey);
  93. } else if (WeChatType.WEWEB == type) {
  94. paramMap.put("grant_type", "client_credential");
  95. paramMap.put("appid", mpAppKey);
  96. paramMap.put("secret", mpAppSecret);
  97. key = String.format("access_token_%s",mpAppKey);
  98. }
  99. // 判断redis中token是否过期
  100. RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
  101. String accessToken = redisUtil.get(key);
  102. if (StrUtil.isNotBlank(accessToken) && !accessToken.equals("null")) {
  103. return accessToken;
  104. }
  105. String result = HttpUtil.get(url, paramMap);
  106. JSONObject jsonObject = JSONObject.parseObject(result);
  107. String token = jsonObject.get("access_token").toString();
  108. // 缓存1小时
  109. redisUtil.set(key,token,3600);
  110. return token;
  111. }
  112. //根据所有部门信息
  113. public List<WeChatDepartDto> getDepartmentList(Long dept_id) {
  114. String token = this.getToken(WeChatType.WEMINI);
  115. HashMap<String, Object> paramMap = new HashMap<>();
  116. paramMap.put("access_token", token);
  117. if (dept_id != null) {
  118. paramMap.put("id", dept_id);
  119. }
  120. String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/department/list", paramMap);
  121. JSONObject jsonObject = JSONObject.parseObject(result);
  122. Object department = jsonObject.get("department");
  123. List<WeChatDepartDto> weChatDepartDtos = JSONObject.parseArray(department.toString(), WeChatDepartDto.class);
  124. return weChatDepartDtos;
  125. }
  126. //获取部门的所有用户信息
  127. public List<WeChatUserDto> getDepartmentUser(Long dept_id) {
  128. String token = this.getToken(WeChatType.WEMINI);
  129. HashMap<String, Object> paramMap = new HashMap<>();
  130. paramMap.put("access_token", token);
  131. paramMap.put("department_id", dept_id);
  132. paramMap.put("fetch_child", 1);
  133. String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/list", paramMap);
  134. JSONObject jsonObject = JSONObject.parseObject(result);
  135. Object department = jsonObject.get("userlist");
  136. List<WeChatUserDto> weChatUserDtos = JSONObject.parseArray(department.toString(), WeChatUserDto.class);
  137. return weChatUserDtos;
  138. }
  139. //公众号发送文本消息给用户
  140. public Boolean sendMessage(String content, String userId) {
  141. String token = this.getToken(WeChatType.WEWEB);
  142. JSONObject object = new JSONObject();
  143. JSONArray touser=new JSONArray();
  144. touser.add(userId);
  145. object.put("touser", touser);
  146. object.put("msgtype", "text");
  147. JSONObject text = new JSONObject();
  148. text.put("content", content);
  149. object.put("text",text);
  150. String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+token, JSONObject.toJSONString(object));
  151. System.out.printf(result);
  152. return true;
  153. }
  154. //{
  155. // "touser":"OPENID",
  156. // "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  157. // "url":"http://weixin.qq.com/download",
  158. // "miniprogram":{
  159. // "appid":"xiaochengxuappid12345",
  160. // "pagepath":"index?foo=bar"
  161. // },
  162. // "client_msg_id":"MSG_000001",
  163. // "data":{
  164. // "keyword1":{
  165. // "value":"巧克力"
  166. // },
  167. // "keyword2": {
  168. // "value":"39.8元"
  169. // },
  170. // "keyword3": {
  171. // "value":"2014年9月22日"
  172. // }
  173. // }
  174. // }
  175. public Boolean sendTemplateMessage(JSONObject object){
  176. String active = SpringUtil.getActiveProfile();
  177. if("dev".equals(active)){
  178. log.info("测试环境,无法执行数据推送");
  179. return false;
  180. }
  181. String token = this.getToken(WeChatType.WEWEB);
  182. String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token, JSONObject.toJSONString(object));
  183. System.out.printf(result);
  184. return true;
  185. }
  186. public String getTicket(String type) {
  187. String token = this.getToken(WeChatType.WEWEB);
  188. HashMap<String, Object> paramMap = new HashMap<>();
  189. paramMap.put("access_token", token);
  190. paramMap.put("type", type);
  191. String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket", paramMap);
  192. JSONObject jsonObject = JSONObject.parseObject(result);
  193. if (jsonObject.containsKey("ticket")) {
  194. //throw new MyException(result);
  195. return jsonObject.get("ticket").toString();
  196. } else {
  197. return "";
  198. }
  199. }
  200. public HashMap<String, Object> SdkSign(String url,String type) throws Exception {
  201. String nonceStr = UUID.randomUUID().toString();
  202. String timestamp = Long.toString(System.currentTimeMillis() / 1000);
  203. String signature = "";
  204. String jsapiTicket = getTicket(type);
  205. String string1 = "jsapi_ticket=" + jsapiTicket +
  206. "&noncestr=" + nonceStr +
  207. "&timestamp=" + timestamp +
  208. "&url=" + url;
  209. try {
  210. MessageDigest crypt = MessageDigest.getInstance("SHA-1");
  211. crypt.reset();
  212. crypt.update(string1.getBytes("UTF-8"));
  213. signature = byteToHex(crypt.digest());
  214. HashMap<String, Object> resultMap = new HashMap<>();
  215. resultMap.put("url",url);
  216. // resultMap.put("jsapi_ticket",jsapiTicket);
  217. resultMap.put("nonceStr",nonceStr);
  218. resultMap.put("timestamp",timestamp);
  219. resultMap.put("signature",signature);
  220. return resultMap;
  221. } catch (NoSuchAlgorithmException e) {
  222. e.printStackTrace();
  223. } catch (UnsupportedEncodingException e) {
  224. e.printStackTrace();
  225. }
  226. return null;
  227. }
  228. private String byteToHex(final byte[] hash) {
  229. Formatter formatter = new Formatter();
  230. for (byte b : hash) {
  231. formatter.format("%02x", b);
  232. }
  233. String result = formatter.toString();
  234. formatter.close();
  235. return result;
  236. }
  237. }