获取微信的AccessToken全局使用

最近开发一个微信小程序,因为全局都要用到AccessToken,所以封装了一个工具类来使用。获取的AccessToken放在redis中,用于全局使用。注意redis保存时间和AccessToken有效时间。

package com.nbomb.town.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Swk
 * @version v1.0
 * @date 2022-12-06 10:28
 */

/**
 *获取微信access_token
 */
@Component
@Slf4j
public class WxAccessToken {
    
    
    @Autowired
    RedisCache redisCache;
    @Value("${wechat.appid}")
    private String APP_ID = "";

    @Value("${wechat.secret}")
    private String SECRET = "";
    private   String  refreshAccessToken() {
    
    
        try {
    
    
            String s = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APP_ID+"&secret="+SECRET, 10 * 1000);
            log.info("获取token返回:{}", s);
            JSONObject jsonObject = JSON.parseObject(s);
            if (jsonObject.containsKey("access_token")) {
    
    
                String access_token = jsonObject.getString("access_token");
                // 单位秒
                int expires_in = jsonObject.getInteger("expires_in");
//                redisCache.setCacheObject(key, access_token, expires_in - 60, TimeUnit.SECONDS);
                updateAccessToken(access_token, expires_in);
                return access_token;
            }
        } catch (Exception e) {
    
    
            log.error("获取token失败:{}", e.getMessage());
        }

return null;
    }
    private void updateAccessToken(String access_token, int expires_in) {
    
    
        redisCache.setCacheObject(tokenKey(), access_token, expires_in - 60, TimeUnit.SECONDS);
    }

    private String tokenKey() {
    
    
        String key = "access_token";
        return key;
    }
    public String getAccessToken() {
    
    
        // 不使用缓存直接查询
        String key = tokenKey();
        Object cacheObject = redisCache.getCacheObject(key);
        if (ObjectUtils.isNotEmpty(cacheObject)) {
    
    
            return (String) cacheObject;
        }

        return refreshAccessToken();
    }

}

Guess you like

Origin blog.csdn.net/weixin_41438423/article/details/128286570