公众号获取AccessToken
以 AppId, AppSecret 获取AccessToken
如果使用缓存token 时,缓存过期时间最好小于公众号返回的过期时间
使用的接口地址:
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=?&secret=?"
public static AjaxResult getAccessToken(BasePubTokenEntity entity) {
String method = "[获取公众号微信AccessToken] ";
Object cacheAccessToken = CacheUtils.get(CacheConstant.WE_CHAT_ACCESS_TOKEN + entity.getAppId());
if (StringUtils.isNotNull(cacheAccessToken)) {
log.info(method + "从缓存中获取");
return AjaxResult.success("", cacheAccessToken);
}
try {
String url = "https://api.weixin.qq.com/cgi-bin/token";
entity.setGrantType("client_credential");
url += "?" + UrlUtils.getUrlParamsByMap(getTokenParams(entity));
String body = OkHttpUtils.getInstance().get(url).body().string();
log.debug(method + "返回信息:{}", body);
AjaxResult result = getAccessTokenResult(body);
if (result.isError() || StringUtils.isNull(result.getData())) {
log.error(method + ",返回信息{}", result);
return AjaxResult.error(result.getCode(), result.getMsg());
}
JSONObject data = JSONObject.parseObject(result.getData() + "");
CacheUtils.set(CacheConstant.WE_CHAT_ACCESS_TOKEN + entity.getAppId(),
data.getString("access_token"), (data.getInteger("expires_in") - 20));
return AjaxResult.success("", data.get("access_token"));
} catch (Exception e) {
e.printStackTrace();
log.error(method + e.getMessage());
}
return AjaxResult.error(-9, "获取Access Token 失败");
}