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();
|
}
|
|
}
|