引言
基于微信公众号开发时候会用到accessToken,且这个参数两个小时内有效,需要服务器端存储并维护。
方案
springboot通过定时任务更新
@Scheduled(initialDelay = 10000,fixedRate = 6600000)public void creatAccessToken() {String url = "https://api.weixin.qq.com/cgi-bin/token";String path = "?grant_type={grant_type}&appid={appid}&secret={secret}";Map<String, String> params = new HashMap<>(3);params.put("grant_type", "client_credential");params.put("appid",WeChatConfig.appId );params.put("secret", WeChatConfig.secret);RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> forObject = restTemplate.getForEntity(url + path, String.class, params);System.out.println(forObject.getBody());JSONObject jsonObject = JSONObject.parseObject(forObject.getBody());String accessToken = jsonObject.getString("access_token");System.out.println(accessToken);// accessToken获取成功if (accessToken != null) {//有效期设置1小时55分钟redisCache.setCacheObject(ACCESS_TOKEN_KEY, accessToken, 115, TimeUnit.MINUTES);} else {//redisUtil.set(ERROR_KEY, forObject.getBody());redisCache.setCacheObject(ERROR_KEY,forObject.getBody());}log.info("creatAccessToken",accessToken);}
欢迎留言、转发、评论。