com.hn.utils.weixin.offiaccount.AccessTokenUtil Maven / Gradle / Ivy
package com.hn.utils.weixin.offiaccount;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.hn.utils.AssertUtils;
import com.hn.utils.weixin.exception.WxException;
/**
* 描述:
* 微信获取accessToken
* access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
*
* @author fei
*/
public class AccessTokenUtil {
private static final Log log = LogFactory.get();
/**
* access_token的有效期目前为2个小时
* 创建缓存,默认7200秒过期
*/
private static TimedCache timedCache = CacheUtil.newTimedCache(7200 * DateUnit.SECOND.getMillis());
/**
* 公众号的全局唯一接口调用凭据 URL
*/
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
/**
* 公众号
* access_token是公众号的全局唯一接口调用凭据
* @return {@link AccessToken.Result}
*/
public static AccessToken.Result accessToken() {
AccessToken.Param requestParam = AccessToken.getRequestParam();
String appid = requestParam.getAppid();
if (StrUtil.isNotBlank(timedCache.get(appid))) {
String cacheToken = timedCache.get(appid);
return JSONUtil.toBean(cacheToken, AccessToken.Result.class);
}
String resultStr = HttpUtil.get(ACCESS_TOKEN_URL, requestParam.toMap());
AccessToken.Result result = JSONUtil.toBean(resultStr, AccessToken.Result.class);
log.info("[公众号]获取公众号全局唯一后台接口调用凭据 返回结果:{}", resultStr);
Integer errCode = result.getErrcode();
if (ObjectUtil.isNull(errCode)) {
timedCache.put(appid, resultStr);
return result;
}
AssertUtils.isTrue(AccessToken.ErrCode.SUCCESS.code.equals(errCode),
WxException.exception(errCode, result.getErrmsg()));
timedCache.put(appid, resultStr);
return result;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy