在微信小程序的后端开发中,调用支付、消息推送、用户数据解密等接口都需要用到access_token,而stable_token是微信官方提供的长期稳定凭证,相比普通access_token有更长的有效期和更灵活的刷新机制,下面我们就来看如何用Java实现stable_token的获取。

一、stable_token接口说明
微信官方提供的stable_token获取接口地址为https://api.weixin.qq.com/cgi-bin/stable_token,请求方式为POST,需要传递小程序对应的appid和secret,同时可以指定是否需要强制刷新token。接口返回的内容包含access_token、有效期expires_in等信息,我们需要解析这些内容并做本地缓存,避免频繁调用接口触发频率限制。
二、核心实现步骤
1. 准备请求参数
需要提前准备两个核心参数:小程序的appid和secret,这两个参数可以在微信小程序后台的开发设置中找到。请求参数需要封装成JSON格式,具体结构如下:
// 请求参数实体类
public class StableTokenParam {
// 小程序appid
private String appid;
// 小程序secret
private String secret;
// 填写client_credential即可
private String grant_type = "client_credential";
// 是否强制刷新,true为强制刷新,默认false
private Boolean force_refresh = false;
// 构造方法、getter、setter省略
}2. 发送HTTP POST请求
Java中可以使用HttpClient或者OkHttp等工具发送POST请求,这里以HttpClient为例,实现请求发送和响应接收:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.StandardCharsets;
public class StableTokenClient {
private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/stable_token";
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String getStableToken(String appid, String secret) throws Exception {
// 创建请求参数
StableTokenParam param = new StableTokenParam();
param.setAppid(appid);
param.setSecret(secret);
// 创建HTTP客户端
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(TOKEN_URL);
// 设置请求头为JSON格式
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
// 将参数转为JSON字符串并设置请求体
String paramJson = objectMapper.writeValueAsString(param);
StringEntity entity = new StringEntity(paramJson, StandardCharsets.UTF_8);
httpPost.setEntity(entity);
// 执行请求并获取响应
String response = httpClient.execute(httpPost, httpResponse ->
EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8)
);
return response;
}
}
}3. 解析响应结果
接口返回的JSON格式如下,成功时包含access_token和expires_in,失败时会返回errcode和errmsg:
// 成功响应
{
"access_token": "生成的token字符串",
"expires_in": 7200
}
// 失败响应
{
"errcode": 40013,
"errmsg": "invalid appid"
}我们可以定义对应的响应实体类来解析结果:
public class StableTokenResponse {
// 成功时返回的token
private String access_token;
// token有效期,单位秒
private Integer expires_in;
// 错误码,0表示成功
private Integer errcode;
// 错误信息
private String errmsg;
// getter、setter省略
}4. token缓存与刷新
为了避免每次调用接口都请求微信服务器,我们需要将获取到的token缓存到本地,比如使用内存缓存或者Redis,这里以简单的内存缓存为例:
import java.util.concurrent.ConcurrentHashMap;
public class TokenCache {
// 缓存token和对应的过期时间戳
private static final ConcurrentHashMap<String, TokenInfo> TOKEN_MAP = new ConcurrentHashMap<>();
// 存储token信息
public static void putToken(String appid, String token, long expiresIn) {
TokenInfo info = new TokenInfo();
info.setToken(token);
// 计算过期时间,提前5分钟刷新避免过期
info.setExpireTime(System.currentTimeMillis() + (expiresIn - 300) * 1000);
TOKEN_MAP.put(appid, info);
}
// 获取有效的token,如果过期则返回null
public static String getToken(String appid) {
TokenInfo info = TOKEN_MAP.get(appid);
if (info == null) {
return null;
}
if (System.currentTimeMillis() > info.getExpireTime()) {
TOKEN_MAP.remove(appid);
return null;
}
return info.getToken();
}
// 内部token信息类
static class TokenInfo {
private String token;
private long expireTime;
// getter、setter省略
}
}三、完整调用示例
将上面的逻辑整合起来,就得到了完整的获取stable_token的方法:
public class WeChatTokenService {
private String appid;
private String secret;
public WeChatTokenService(String appid, String secret) {
this.appid = appid;
this.secret = secret;
}
public String getAccessToken() throws Exception {
// 先从缓存获取
String cachedToken = TokenCache.getToken(appid);
if (cachedToken != null) {
return cachedToken;
}
// 缓存没有则请求接口
String response = StableTokenClient.getStableToken(appid, secret);
StableTokenResponse tokenResponse = new ObjectMapper().readValue(response, StableTokenResponse.class);
// 判断是否请求成功
if (tokenResponse.getErrcode() != null && tokenResponse.getErrcode() != 0) {
throw new RuntimeException("获取stable_token失败:" + tokenResponse.getErrmsg());
}
// 存入缓存
TokenCache.putToken(appid, tokenResponse.getAccess_token(), tokenResponse.getExpires_in());
return tokenResponse.getAccess_token();
}
}四、注意事项
- appid和secret属于敏感信息,不要硬编码在代码中,建议放到配置文件或者环境变量里。
- stable_token虽然有效期较长,但依然有失效的可能,需要实现定时刷新或者过期自动获取的逻辑。
- 微信接口有调用频率限制,不要频繁请求获取token的接口,合理设置缓存时间。
- 如果返回错误码,需要根据官方错误码表排查问题,比如40013是appid无效,40125是secret错误。
微信小程序stable_tokentoken获取Java实现修改时间:2026-05-31 05:02:29