1
0
Code Issues Pull Requests Packages Projects Releases Wiki Activity GitHub Gitee

修复小程序获取小程序码失败的问题

This commit is contained in:
程序员小墨 2023-04-25 01:40:05 +08:00
parent d3fb7827f1
commit b68fde365f
2 changed files with 34 additions and 6 deletions

View File

@ -1,5 +1,6 @@
package com.cxyxiaomo.epp.access.controller;
import com.alibaba.fastjson2.JSONObject;
import com.cxyxiaomo.epp.access.pojo.UnlimitedQRCodeParam;
import com.cxyxiaomo.epp.access.service.WeChatTokenServiceImpl;
import com.cxyxiaomo.epp.common.response.Res;
@ -47,7 +48,28 @@ public class WeChatTokenController {
unlimitedQRCodeParam.setIsHyaline(isHyaline);
okhttp3.ResponseBody responseBody = weChatTokenService.getUnlimitedQRCodeFromApi(accessToken, unlimitedQRCodeParam);
return responseBody.bytes();
try {
// {"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest, could get access_token by getStableAccessToken, more details at https://mmbizurl.cn/s/JtxxFh33r rid: 6446bac4-4a6b0410-118a16e7"}
if (Objects.requireNonNull(responseBody.contentType()).subtype().equals("json")) {
// 返回了 JSON 说明失败了
String jsonString = responseBody.string();
JSONObject jsonObject = JSONObject.parseObject(jsonString);
String errcode = jsonObject.getString("errcode");
if (errcode.equals("40001")) {
// 重新获取 Access Token
accessToken = weChatTokenService.getAccessToken(true);
responseBody = weChatTokenService.getUnlimitedQRCodeFromApi(accessToken, unlimitedQRCodeParam);
} else if (errcode.equals("40013")) {
System.out.println("40013 invalid appid 不合法的 AppID ,请开发者检查 AppID 的正确性,避免异常字符,注意大小写\n" +
"docs: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html");
return null;
}
}
// 返回了图片直接返回
return responseBody.bytes();
} catch (NullPointerException ignored) {
return null;
}
}
@GetMapping(value = "/rpc/getOpenIdFromApi")

View File

@ -35,11 +35,17 @@ public class WeChatTokenServiceImpl implements WeChatTokenService {
@Override
public String getAccessToken() {
// 首先从数据库中查询是否存在 access_token
// 如果存在且没有过期那么就直接返回距离失效时间小于 3 分钟就当作过期
Setting atSetting = accessDao.getValueByKey(SETTING_KEY);
if (atSetting != null && LocalDateTime.now().plusMinutes(3L).compareTo(atSetting.getTime()) < 0) {
return atSetting.getValue();
return getAccessToken(false);
}
public String getAccessToken(Boolean forceUpdate) {
if (!forceUpdate) {
// 首先从数据库中查询是否存在 access_token
// 如果存在且没有过期那么就直接返回距离失效时间小于 3 分钟就当作过期
Setting atSetting = accessDao.getValueByKey(SETTING_KEY);
if (atSetting != null && LocalDateTime.now().plusMinutes(3L).compareTo(atSetting.getTime()) < 0) {
return atSetting.getValue();
}
}
// 否则则去请求一个新的 access_token