puzhibing
2024-10-15 325b09c92e51c26e297a937a6f1be9f6661dceb1
ruoyi-service/ruoyi-account/src/main/java/com/ruoyi/account/wx/tools/WxAppletTools.java
@@ -4,12 +4,14 @@
import com.ruoyi.account.wx.body.resp.Code2SessionRespBody;
import com.ruoyi.account.wx.body.resq.Code2SessionResqBody;
import com.ruoyi.account.wx.model.WeixinProperties;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
/**
 * @author xiaochen
@@ -57,11 +59,12 @@
    public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
    private WeixinProperties wxConfig;
    private RestTemplate wxRestTemplate;
    private WxCacheTemplate<String> wxCacheTemplate;
    private RedisService redisService;
    public WxAppletTools(RestTemplate wxRestTemplate, WeixinProperties wxConfig) {
    public WxAppletTools(RestTemplate wxRestTemplate, WeixinProperties wxConfig, RedisService redisService) {
        this.wxRestTemplate = wxRestTemplate;
        this.wxConfig = wxConfig;
        this.redisService = redisService;
    }
    /**
@@ -101,7 +104,7 @@
     * @return
     */
    public String getAccessToken(String version) {
        String accessToken = wxCacheTemplate.getKey(ACCESSTOKEN_CACHE_KEY + version);
        String accessToken = redisService.getCacheObject(ACCESSTOKEN_CACHE_KEY + version);
        if (StringUtils.hasLength(accessToken)) {
            return accessToken;
        }
@@ -113,7 +116,7 @@
            // 抛出错误
            throw new WxException(accessTokenRespBody.getErrorCode() + ":" + accessTokenRespBody.getErrorMsg());
        }
        wxCacheTemplate.setKey(ACCESSTOKEN_CACHE_KEY + version, accessTokenRespBody.getAccessToken());
        redisService.setCacheObject(ACCESSTOKEN_CACHE_KEY + version, accessTokenRespBody.getAccessToken(), 7200L, TimeUnit.SECONDS);
        return accessTokenRespBody.getAccessToken();
    }