WeChatHandler.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package com.ads.common.handler;
  2. import cn.hutool.core.util.StrUtil;
  3. import cn.hutool.crypto.SecureUtil;
  4. import cn.hutool.http.HttpUtil;
  5. import cn.hutool.json.JSONObject;
  6. import cn.hutool.json.JSONUtil;
  7. import com.ads.common.constant.CodeConstant;
  8. import com.ads.common.constant.UrlConstant;
  9. import com.ads.common.enums.ErrCodeEnum;
  10. import com.ads.common.exception.BusinessException;
  11. import com.ads.common.exception.WechatApiErrException;
  12. import com.ads.common.util.FileUtil;
  13. import com.ads.common.util.RedisUtil;
  14. import com.ads.common.util.aes.AesException;
  15. import com.ads.common.util.aes.WXBizMsgCrypt;
  16. import lombok.extern.slf4j.Slf4j;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import org.springframework.context.annotation.Configuration;
  19. import org.springframework.web.multipart.MultipartFile;
  20. import javax.annotation.PostConstruct;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.util.*;
  24. import static com.ads.common.util.CodecUtil.encryptMD5;
  25. /**
  26. * 微信接口
  27. *
  28. * @author huzhihao
  29. * @date 2021-12-22 11:47
  30. **/
  31. @Slf4j
  32. @Configuration
  33. public class WeChatHandler {
  34. @Value("${app.appId}")
  35. String appId_;
  36. @Value("${app.appSecret}")
  37. String appSecret_;
  38. @Value("${app.token}")
  39. String token_;
  40. @Value("${app.encodingAESKey}")
  41. String encodingAesKey_;
  42. static String appId, appSecret, token, encodingAesKey;
  43. private volatile static WXBizMsgCrypt instance = null;
  44. /**
  45. * [初始化]
  46. *
  47. * @param
  48. * @return void
  49. * @author huzhihao
  50. * @date 2021/12/22 14:05
  51. */
  52. @PostConstruct
  53. public void init() {
  54. appId = appId_;
  55. appSecret = appSecret_;
  56. token = token_;
  57. encodingAesKey = encodingAesKey_;
  58. }
  59. /**
  60. * [获取WXBizMsgCrypt实例]
  61. *
  62. * @param
  63. * @return com.example.wechat_event_demo.qq.weixin.mp.aes.WXBizMsgCrypt
  64. * @author huzhihao
  65. * @date 2021/12/22 14:05
  66. */
  67. public static WXBizMsgCrypt getWXBizMsgCrypt() throws AesException {
  68. if (instance == null) {
  69. synchronized (WXBizMsgCrypt.class) {
  70. if (instance == null) {
  71. instance = new WXBizMsgCrypt(token, encodingAesKey, appId);
  72. }
  73. }
  74. }
  75. return instance;
  76. }
  77. /**
  78. * [校验]
  79. *
  80. * @param signature
  81. * @param timestamp
  82. * @param nonce
  83. * @param echostr
  84. * @return java.lang.String
  85. * @author huzhihao
  86. * @date 2021/12/27 14:02
  87. */
  88. public static String callbackValidate(String signature, String timestamp, String nonce, String echostr) {
  89. log.info(signature);
  90. List<String> list = new ArrayList<>();
  91. list.add(token);
  92. list.add(timestamp);
  93. list.add(nonce);
  94. Collections.sort(list);
  95. String str = "";
  96. for (String s : list) {
  97. str += s;
  98. }
  99. String sha1Str = SecureUtil.sha1(str);
  100. if (Objects.equals(sha1Str, signature)) {
  101. return echostr;
  102. }
  103. return null;
  104. }
  105. /**
  106. * [解码]
  107. *
  108. * @param encrypt
  109. * @return java.lang.String
  110. * @author huzhihao
  111. * @date 2021/12/22 14:05
  112. */
  113. public static String decrypt(String encrypt) throws AesException {
  114. WXBizMsgCrypt wxBizMsgCrypt = WeChatHandler.getWXBizMsgCrypt();
  115. return wxBizMsgCrypt.decrypt(encrypt);
  116. }
  117. /**
  118. * [缓存获取access_token]
  119. *
  120. * @return java.lang.String
  121. * @author huzhihao
  122. * @date 2021/12/22 15:40
  123. */
  124. public static String accessToken() {
  125. String accessToken = getAccessToken();
  126. log.info("===>缓存获取access_token"+accessToken);
  127. return accessToken;
  128. }
  129. /**
  130. * [查询access_token]
  131. *
  132. * @return java.lang.String
  133. * @author huzhihao
  134. * @date 2021/12/22 15:52
  135. */
  136. static String getAccessToken() {
  137. String url = UrlConstant.URL_HSAY_OPEN;
  138. HashMap<String,Object> params = new HashMap<>();
  139. String appCode ="HSAY_SHARE_COUPON";
  140. Long timestamp = (new Date()).getTime();
  141. String sign = encryptMD5(appCode + "hsay-wx-app-0302" + timestamp);
  142. params.put("timestamp",timestamp);
  143. params.put("appCode",appCode);
  144. params.put("sign",sign);
  145. String param = JSONUtil.toJsonStr(params);
  146. log.info("===>请求access_token");
  147. try{
  148. String res = HttpUtil.post(url, param);
  149. JSONObject jsonObject = JSONUtil.parseObj(res);
  150. if(jsonObject.getInt("code")==200){
  151. log.info("===>请求access_token成功");
  152. String data = jsonObject.getStr("data");
  153. return JSONUtil.parseObj(data).getStr("accessToken");
  154. }else{
  155. throw new BusinessException("获取token失败:"+jsonObject.getStr("msg"));
  156. }
  157. }
  158. catch (Exception e){
  159. throw new BusinessException("获取token失败");
  160. }
  161. // String url = StrUtil.format(
  162. // UrlConstant.ACCESS_TOKEN,
  163. // appId,
  164. // appSecret
  165. // );
  166. // String res = HttpUtil.get(url);
  167. // JSONObject jsonObject = JSONUtil.parseObj(res);
  168. // String accessToken = jsonObject.getStr(CodeConstant.WECHAT.ACCESS_TOKEN);
  169. // if (StrUtil.isBlank(accessToken)) {
  170. // String errCode = jsonObject.getStr(CodeConstant.WECHAT.ERR_CODE);
  171. // throw new RuntimeException("请求access_token失败!");
  172. // }
  173. // log.info("===>请求access_token成功");
  174. // return accessToken;
  175. }
  176. /**
  177. * [验证access_token]
  178. *
  179. * @param accessToken
  180. * @return java.lang.Boolean
  181. * @author huzhihao
  182. * @date 2021/12/22 15:53
  183. */
  184. static Boolean validateAccessToken(String accessToken) {
  185. if (StrUtil.isBlank(accessToken)) {
  186. return false;
  187. }
  188. String url = StrUtil.format(
  189. UrlConstant.IP_LIST,
  190. accessToken
  191. );
  192. String res = HttpUtil.get(url);
  193. JSONObject jsonObject = JSONUtil.parseObj(res);
  194. String ipList = jsonObject.getStr(CodeConstant.WECHAT.IP_LIST);
  195. if (StrUtil.isNotBlank(ipList)) {
  196. return true;
  197. }
  198. return false;
  199. }
  200. /**
  201. * [通用get请求]
  202. *
  203. * @param url_ 请求地址
  204. * @param resStr 返回中需要提取的字符串
  205. * @return java.lang.String
  206. * @author huzhihao
  207. * @date 2021/12/22 14:52
  208. */
  209. public static String httpGetMethod(String url_, String resStr) {
  210. String access_token = (String) RedisUtil.get(CodeConstant.REDIS.ACCESS_TOKEN);
  211. return httpGetMethod(url_, access_token, resStr);
  212. }
  213. /**
  214. * [通用get请求]
  215. *
  216. * @param url_ 请求地址
  217. * @param token_ access_token
  218. * @param resStr 返回中需要提取的字符串
  219. * @return java.lang.String
  220. * @author huzhihao
  221. * @date 2021/12/22 14:52
  222. */
  223. public static String httpGetMethod(String url_, String token_, String resStr) {
  224. //装配新的url
  225. String url = StrUtil.format(
  226. url_,
  227. token_
  228. );
  229. //发送请求
  230. log.info("===>通用get请求,url = {}", url);
  231. String res = HttpUtil.get(url);
  232. log.info("===>通用get请求,返回值 = {}", res);
  233. JSONObject jsonObject = JSONUtil.parseObj(res);
  234. String errCode = jsonObject.getStr(CodeConstant.WECHAT.ERR_CODE);
  235. String errMsg = jsonObject.getStr(CodeConstant.WECHAT.ERR_MSG);
  236. if (errCode != null && !ErrCodeEnum.OK.getCode().equals(errCode)) {
  237. if (StrUtil.isBlank(errMsg)) {
  238. errMsg = ErrCodeEnum.get(errCode);
  239. }
  240. throw new WechatApiErrException(errMsg);
  241. }
  242. return jsonObject.getStr(resStr);
  243. }
  244. /**
  245. * [通用post请求]
  246. *
  247. * @param url_ 请求地址
  248. * @param param_ 请求参数
  249. * @param clazz 接收返回的类
  250. * @return java.lang.Object
  251. * @author huzhihao
  252. * @date 2021/12/22 14:54
  253. */
  254. public static Object httpPostMethod(String url_, Object param_, Class clazz) {
  255. String access_token = (String) RedisUtil.get(CodeConstant.REDIS.ACCESS_TOKEN);
  256. return httpPostMethod(url_, access_token, param_, clazz);
  257. }
  258. /**
  259. * [通用post请求]
  260. *
  261. * @param url_ 请求地址
  262. * @param token_ access_token
  263. * @param param_ 请求参数
  264. * @param clazz 接收返回的类
  265. * @return java.lang.Object
  266. * @author huzhihao
  267. * @date 2021/12/22 14:54
  268. */
  269. public static Object httpPostMethod(String url_, String token_, Object param_, Class clazz) {
  270. //装配新的url
  271. String url = StrUtil.format(
  272. url_,
  273. token_
  274. );
  275. //发送请求
  276. String res, param;
  277. if (param_ == null) {
  278. param = "{}";
  279. } else {
  280. param = JSONUtil.toJsonStr(param_);
  281. }
  282. log.info("===>通用post请求,url = {},param = {}", url, param);
  283. res = HttpUtil.post(url, param);
  284. log.info("===>通用post请求,返回值 = {}", res);
  285. JSONObject jsonObject = JSONUtil.parseObj(res);
  286. String errCode = jsonObject.getStr(CodeConstant.WECHAT.ERR_CODE);
  287. String errMsg = jsonObject.getStr(CodeConstant.WECHAT.ERR_MSG);
  288. if (errCode != null && !ErrCodeEnum.OK.getCode().equals(errCode)) {
  289. if (StrUtil.isBlank(errMsg)) {
  290. errMsg = ErrCodeEnum.get(errCode);
  291. }
  292. throw new WechatApiErrException(errMsg);
  293. }
  294. //转换返回值为指定类型
  295. return JSONUtil.toBean(jsonObject, clazz);
  296. }
  297. /**
  298. * [上传图片到微信获取链接地址]
  299. *
  300. * @param mfile
  301. * @return java.lang.String
  302. * @author huzhihao
  303. * @date 2021/12/24 16:15
  304. */
  305. public static String httpUpload(MultipartFile mfile) {
  306. log.info("===>上传图片到微信获取链接地址,{}", mfile);
  307. //装配新的url
  308. String url = StrUtil.format(
  309. UrlConstant.IMG_UPLOAD,
  310. accessToken()
  311. );
  312. //构建参数
  313. if (!FileUtil.checkFileSize(mfile.getSize(), 2, "M")) {
  314. throw new BusinessException("图片最大支持2MB");
  315. }
  316. File file = FileUtil.multipartFileToFile(mfile);
  317. HashMap<String, String> paramMap = new HashMap<>();
  318. paramMap.put(CodeConstant.WECHAT.RESP_TYPE, CodeConstant.STRING.STR_1);
  319. paramMap.put(CodeConstant.WECHAT.UPLOAD_TYPE, CodeConstant.STRING.STR_0);
  320. Map<String, File> files = new HashMap<>();
  321. files.put("file", file);
  322. //发送请求
  323. String res = null;
  324. try {
  325. res = FileUtil.uploadFile(url, null, paramMap, files);
  326. } catch (IOException e) {
  327. throw new WechatApiErrException("上传失败!");
  328. }
  329. //获取返回值
  330. JSONObject resJson = JSONUtil.parseObj(res);
  331. String errCode = resJson.getStr(CodeConstant.WECHAT.ERR_CODE);
  332. String errMsg = resJson.getStr(CodeConstant.WECHAT.ERR_MSG);
  333. if (errCode != null && !ErrCodeEnum.OK.getCode().equals(errCode)) {
  334. if (StrUtil.isBlank(errMsg)) {
  335. errMsg = ErrCodeEnum.get(errCode);
  336. }
  337. throw new WechatApiErrException(errMsg);
  338. }
  339. String imgInfo = resJson.getStr(CodeConstant.WECHAT.IMG_INFO);
  340. JSONObject imgInfoJson = JSONUtil.parseObj(imgInfo);
  341. return imgInfoJson.getStr(CodeConstant.WECHAT.TEMP_IMG_URL);
  342. }
  343. }