多个wxMpConfig兼容

This commit is contained in:
2025-04-08 15:26:18 +08:00
parent 75eb3732fc
commit 2835346447

View File

@ -6,26 +6,34 @@ import com.alibaba.fastjson.JSONObject;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class WxMpUtil {
private static final String GET_WXA_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
private static final String GET_URL_LICK_URL = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=%s";
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
private static String ACCESS_TOKEN = "";
private static Date expireTime = new Date();
private static final Map<String, String> tokens = new ConcurrentHashMap<>();
private static final Map<String, Date> expireTimes = new ConcurrentHashMap<>();
private static String getAccessToken(String appId, String appSecret) {
if (ACCESS_TOKEN != null && !ACCESS_TOKEN.isEmpty()) {
if (expireTime.getTime() > System.currentTimeMillis()) {
return ACCESS_TOKEN;
if (expireTimes.containsKey(appId)) {
Date expireTime = expireTimes.get(appId);
if (expireTime.getTime() < System.currentTimeMillis()) {
tokens.remove(appId);
}
} else {
tokens.remove(appId);
}
String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
String response = HttpUtil.get(url);
JSONObject jsonObject = JSONObject.parseObject(response);
ACCESS_TOKEN = jsonObject.getString("access_token");
expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
return ACCESS_TOKEN;
return tokens.computeIfAbsent(appId, (k) -> {
String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
String response = HttpUtil.get(url);
JSONObject jsonObject = JSONObject.parseObject(response);
String token = jsonObject.getString("access_token");
Date expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
expireTimes.put(appId, expireTime);
return token;
});
}
public static void generateWXAQRCode(String appId, String appSecret, String envVersion, String path, String filePath) throws Exception {