errcode:40001 errmsg:invalid credential, access_token is invalid or not latest hint

时间:2024-04-14 12:28:03

前段时间水运头条线上分享功能调用微信接口获取小程序码时,报errcode:40001,并且获取小程序码时有时报错有时不报错.可是我本地和测试环境并没有发生这种情况.于是乎就去百度微信errcode:40001代表的含义(获取access_token时Secret错误,或者access_token无效)

errcode:40001 errmsg:invalid credential, access_token is invalid or not latest hint

微信接口状态码的返回含义时,大致知道原因了.本地和测试环境只有一台机器,我的本地和测试环境调用微信接口获取access_token时,是用static修饰的变量接收的,所以access_token不会实时刷新,只有过了有效期才会重新去刷新,这时获取access_token是不会出现token失效的.

private static final Logger LOGGER = LoggerFactory.getLogger(WeixinUtils.class);
private static String accessToken = null;
private static long getAccessTokenTime;
private static int expires_in;
public static String getAccessToken(ConfigurationService configurationService) {
    accessToken = configurationService.get("accessToken");
    if (accessToken == null) {
        return doAccessToken(configurationService);
    } else {
        getAccessTokenTime = Long.parseLong(configurationService.get("getAccessTokenTime"));
        long totalSeconds = (System.currentTimeMillis() - getAccessTokenTime) / 1000;
        expires_in = Integer.parseInt(configurationService.get("expires_in"));
            if (totalSeconds > expires_in) {
            return doAccessToken(configurationService);
        } else {
            return accessToken;
        }
    }
}

errcode:40001 errmsg:invalid credential, access_token is invalid or not latest hint

可是线上环境有负载均衡请求会被分配到多台机器上去执行,每台机器都会去获取一次access_token,根据微信开发文档说明多次获取access_token时,老token的有效期只有5分钟.这样过了5分钟后,老token就失效了.可是有台机器存储的token还是老token,失效时间还有115分钟才会重新获取token,在这期间这台机器调用这个接口就会报errorcode:40001.

解决方法:采用分布式缓存来缓存access_token,这样就能保证线上每台机器都是同一个access_token.

注:案例代码采用的就是分布式缓存来解决这个问题的.