Ver código fonte

生成小程序二维码时,底部文字字体改为默认。在生成图片失败后,把token设置为失效

lsd 3 meses atrás
pai
commit
1b20072227

+ 12 - 4
leromro-common/src/main/java/com/leromro/common/utils/WeChatMiniProgramUtil.java

@@ -36,6 +36,8 @@ public class WeChatMiniProgramUtil {
     private final RedissonClient redissonClient;
     private final RestTemplate restTemplate;
     private final ObjectMapper objectMapper;
+    private final String cacheKey = "wechat:access_token";
+    private final String lockKey = "lock:wechat:access_token";
 
     private final String wxUrl;
     private final String appId;
@@ -62,9 +64,6 @@ public class WeChatMiniProgramUtil {
      * 获取 access_token(带 Redis 缓存和 Redisson 分布式锁)
      */
     public String getAccessToken() throws InterruptedException {
-        String cacheKey = "wechat:access_token";
-        String lockKey = "lock:wechat:access_token";
-
         // 1. 先从缓存获取
         String accessToken = redisTemplate.opsForValue().get(cacheKey);
         if (accessToken != null) {
@@ -164,6 +163,7 @@ public class WeChatMiniProgramUtil {
 
         byte[] body = response.getBody();
         if (body != null && body.length > 0 && body[0] == '{') {
+            handleFailure(response);
             String error = new String(body, StandardCharsets.UTF_8);
             throw new RuntimeException("生成小程序码失败:" + error);
         }
@@ -171,6 +171,14 @@ public class WeChatMiniProgramUtil {
         return body;
     }
 
+    /**
+     * 请求失败处理
+     */
+    private void handleFailure(ResponseEntity response) {
+        // todo 直接清除原来的token(防止多环境导致的token失效)
+        redisTemplate.delete(cacheKey);
+    }
+
     /**
      * 在小程序码图片底部添加指定文字(带白色背景)
      *
@@ -204,7 +212,7 @@ public class WeChatMiniProgramUtil {
         g.drawImage(originalImage, 0, 0, null);
 
         // 设置字体样式和颜色
-        Font font = new Font(fontName, Font.BOLD, fontSize);
+        Font font = new Font(null, Font.BOLD, fontSize);
         g.setFont(font);
         g.setColor(color);