puzhibing
2023-06-30 f58cca364b731eac2d60a440ffaa804be3cd43fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.stylefeng.guns.modular.system.controller.util;
 
import com.stylefeng.guns.modular.system.config.WxConfig;
import com.stylefeng.guns.modular.system.controller.resp.AccessTokenRespBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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;
 
/**
 * @Description
 * @Author xiaochen
 * @Date 2021/11/5/00519:26
 */
@Component
public class TokenUtils {
    public final static String ACCESS_TOKEN_CACHE_KEY = "accessToken";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private RestTemplate wxRestTemplate;
    @Autowired
    private WxJsonUtils wxJsonUtils;
//    @Autowired
//    private RedisUtils redisUtils;
 
    /**
     * @return
     */
    public String getSimpleAccessToken() {
        String accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_CACHE_KEY);
        if (StringUtils.hasLength(accessToken)) {
            return accessToken;
        }
        String requestUrl = MessageFormat.format(Constant.ACCESS_TOKEN_URL, wxConfig.getAppId(), wxConfig.getSecret());
        String respBody = wxRestTemplate.getForEntity(requestUrl, String.class).getBody();
        AccessTokenRespBody accessTokenRespBody = wxJsonUtils.parseObject(respBody, AccessTokenRespBody.class);
        // 判断有误异常
        if (StringUtils.hasLength(accessTokenRespBody.getErrorMsg())) {
            // 抛出错误
            throw new RuntimeException(accessTokenRespBody.getErrorCode() + ":" + accessTokenRespBody.getErrorMsg());
        }
        redisTemplate.opsForValue().set(ACCESS_TOKEN_CACHE_KEY, accessTokenRespBody.getAccessToken(), 2, TimeUnit.HOURS);
        return accessTokenRespBody.getAccessToken();
    }
 
}