|
@@ -41,6 +41,7 @@ public class WxOfficeAccountClient {
|
|
|
private StringRedisTemplate stringRedisTemplate;
|
|
|
|
|
|
private static final String ACCESS_TOKEN_KEY = "wx:access_token";
|
|
|
+ private static final String XCX_ACCESS_TOKEN_KEY = "wx:xcx:access_token";
|
|
|
|
|
|
@NotBlank
|
|
|
@Value("${lnxx.wechat.office.account.appId}")
|
|
@@ -54,6 +55,14 @@ public class WxOfficeAccountClient {
|
|
|
@Value("${lnxx.wechat.office.account.templateId}")
|
|
|
private String templateId;
|
|
|
|
|
|
+ @NotBlank
|
|
|
+ @Value("${lnxx.wechat.appid}")
|
|
|
+ private String xcxAppId;
|
|
|
+
|
|
|
+ @NotBlank
|
|
|
+ @Value("${lnxx.wechat.secret}")
|
|
|
+ private String xcxSecret;
|
|
|
+
|
|
|
private static final Gson gson = new Gson();
|
|
|
|
|
|
|
|
@@ -169,7 +178,48 @@ public class WxOfficeAccountClient {
|
|
|
|
|
|
//调用getaccess_token方法,给一键获取手机号登录使用
|
|
|
public String fetchAccessToken() {
|
|
|
- return getAccessToken();
|
|
|
- }
|
|
|
+ return getAppAccessToken();
|
|
|
+ }
|
|
|
+
|
|
|
+ private String getAppAccessToken() {
|
|
|
+ //1.尝试从Redis中获取access_token
|
|
|
+ String cachedToken = stringRedisTemplate.opsForValue().get(XCX_ACCESS_TOKEN_KEY);
|
|
|
+ if (StringUtils.isNotEmpty(cachedToken)) {
|
|
|
+ log.info("从Redis中获取access_token成功: {}", cachedToken);
|
|
|
+ return cachedToken;
|
|
|
+ }
|
|
|
+ //2.如果Redis中没有,则调用微信接口获取
|
|
|
+ String url = "https://api.weixin.qq.com/cgi-bin/token" +
|
|
|
+ "?grant_type=client_credential" +
|
|
|
+ "&appid=" + xcxAppId +
|
|
|
+ "&secret=" + xcxSecret;
|
|
|
+
|
|
|
+ try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
|
|
+ HttpGet httpGet = new HttpGet(url);
|
|
|
+ try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
|
|
+ HttpEntity entity = response.getEntity();
|
|
|
+ String result = EntityUtils.toString(entity);
|
|
|
+ Map<String, Object> map = gson.fromJson(result, Map.class);
|
|
|
|
|
|
+ //3.判断是否有错误码返回
|
|
|
+ if (map.containsKey("errcode")) {
|
|
|
+ log.error("微信接口返回错误码:{}", result);
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ if (map.containsKey("access_token")) {
|
|
|
+ String accessToken = (String) map.get("access_token");
|
|
|
+
|
|
|
+ //4.写入redis,有效期7080秒
|
|
|
+ stringRedisTemplate.opsForValue().set(XCX_ACCESS_TOKEN_KEY, accessToken, 120, TimeUnit.SECONDS);
|
|
|
+ log.info("从微信中获取 access_token 并写入Redis:{}", accessToken);
|
|
|
+ return accessToken;
|
|
|
+ } else {
|
|
|
+ log.error("微信接口未返回 access_token, 原始响应:{}", result);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error("调用微信接口异常,获取 access_token 失败", e);
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
}
|