|
@@ -0,0 +1,66 @@
|
|
|
|
+package com.ruoyi.generator.util;
|
|
|
|
+
|
|
|
|
+import com.alibaba.fastjson2.JSONObject;
|
|
|
|
+import com.ruoyi.common.constant.CacheConstants;
|
|
|
|
+import com.ruoyi.common.constant.Constants;
|
|
|
|
+import com.ruoyi.common.core.redis.RedisCache;
|
|
|
|
+import com.ruoyi.common.utils.spring.SpringUtils;
|
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
|
+
|
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
|
+
|
|
|
|
+public class WxUtils {
|
|
|
|
+
|
|
|
|
+ private static final String prefix = "https://api.weixin.qq.com";
|
|
|
|
+ private static final RestTemplate restTemplate = new RestTemplate();
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 获取微信token数据
|
|
|
|
+ *
|
|
|
|
+ * @param appId 微信appId
|
|
|
|
+ * @param secret 记录值
|
|
|
|
+ * @return token
|
|
|
|
+ */
|
|
|
|
+ public static String token(String appId, String secret) {
|
|
|
|
+ //查询redis是否已有数值
|
|
|
|
+ String token = (String) SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.WX_TOKEN + appId);
|
|
|
|
+ if (token == null) {
|
|
|
|
+ String url = prefix + "/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
|
|
|
|
+ JSONObject result = restTemplate.getForObject(url, JSONObject.class);
|
|
|
|
+ if (result == null) {
|
|
|
|
+ return token;
|
|
|
|
+ }
|
|
|
|
+ token = result.getString("access_token");
|
|
|
|
+ SpringUtils.getBean(RedisCache.class).setCacheObject(CacheConstants.WX_TOKEN + appId, token, Constants.CAPTCHA_EXPIRATION, TimeUnit.HOURS);
|
|
|
|
+ }
|
|
|
|
+ return token;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 获取ticket
|
|
|
|
+ *
|
|
|
|
+ * @param token 微信token
|
|
|
|
+ * @param type 类型 默认2
|
|
|
|
+ * @return ticket
|
|
|
|
+ */
|
|
|
|
+ public static String ticket(String appId, String token, String type) {
|
|
|
|
+ //查询redis是否已有数值
|
|
|
|
+ String ticket = (String) SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.WX_TICKET + appId);
|
|
|
|
+ if (ticket == null) {
|
|
|
|
+ String url = prefix + "/cgi-bin/ticket/getticket?access_token=" + token + "&type=" + type;
|
|
|
|
+ JSONObject result = restTemplate.getForObject(url, JSONObject.class);
|
|
|
|
+ if (result == null) {
|
|
|
|
+ return ticket;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ Integer errCode = result.getInteger("errcode");
|
|
|
|
+ String errMsg = result.getString("errmsg");
|
|
|
|
+ if (errCode != 0 && errMsg != "ok") {
|
|
|
|
+ return ticket;
|
|
|
|
+ }
|
|
|
|
+ ticket = result.getString("ticket");
|
|
|
|
+ SpringUtils.getBean(RedisCache.class).setCacheObject(CacheConstants.WX_TICKET + appId, ticket, Constants.CAPTCHA_EXPIRATION, TimeUnit.HOURS);
|
|
|
|
+ }
|
|
|
|
+ return ticket;
|
|
|
|
+ }
|
|
|
|
+}
|