package com.train.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** * 微信 API 封装:jscode2session 换 openid、getPhoneNumber 换手机号。 * 对齐 cfc(E:\cfc)的 WechatService 逻辑;test-mode 下全部走模拟值, * 不依赖真实微信 API,便于本地无 secret 环境启动。 */ @Slf4j @Component public class WechatService { @Value("${wechat.appid}") private String appid; @Value("${wechat.secret}") private String secret; @Value("${wechat.login-url}") private String loginUrl; @Value("${wechat.phone-url:https://api.weixin.qq.com/wxa/business/getuserphonenumber}") private String phoneUrl; @Value("${wechat.token-url:https://api.weixin.qq.com/cgi-bin/token}") private String tokenUrl; @Value("${wechat.qrcode-url:https://api.weixin.qq.com/wxa/getwxacodeunlimit}") private String qrcodeUrl; @Value("${wechat.qrcode-env-version:release}") private String qrcodeEnvVersion; @Value("${wechat.test-mode}") private boolean testMode; @Value("${wechat.test-phone:13800138000}") private String testPhone; private final RestTemplate restTemplate = new RestTemplate(); /** access_token 缓存(生产环境用;test-mode 不走此路径) */ private volatile String cachedAccessToken; private volatile long tokenExpireAt; /** * 用 login code 换取 openid(jscode2session)。 * test-mode:openid = "test_" + code,与既有 AuthController 行为一致。 */ public String code2Session(String code) { return code2SessionInfo(code).get("openid"); } /** * 用 login code 换取 openid + session_key + unionid(jscode2session)。 * unionid 仅在小程序已绑定微信开放平台账号时由微信返回,用于跨小程序身份归一。 * test-mode:openid = "test_" + code,unionid 为空(对齐 cfc 的 test-mode 行为)。 */ public Map code2SessionInfo(String code) { Map result = new HashMap<>(); if (testMode) { result.put("openid", "test_" + code); result.put("session_key", ""); result.put("unionid", ""); return result; } try { String url = loginUrl + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code"; ResponseEntity response = restTemplate.getForEntity(url, String.class); JSONObject json = JSON.parseObject(response.getBody()); int errcode = json.getIntValue("errcode"); if (errcode != 0) { throw new RuntimeException("jscode2session 失败: " + json.getString("errmsg")); } result.put("openid", json.getString("openid")); result.put("session_key", json.getString("session_key")); result.put("unionid", json.getString("unionid")); return result; } catch (Exception e) { log.error("code2Session 异常", e); throw new RuntimeException("微信登录失败"); } } /** * 用 phoneCode 换取手机号(新版 getPhoneNumber 接口,需 access_token)。 * test-mode:test_ -> phone;合法手机号直接返回;否则返回配置的测试手机号。 */ public String getPhoneNumber(String phoneCode) { if (testMode) { if (phoneCode != null && phoneCode.startsWith("test_")) { return phoneCode.substring(5); } if (phoneCode != null && phoneCode.matches("^1[3-9]\\d{9}$")) { return phoneCode; } return testPhone; } try { String accessToken = getAccessToken(); String url = phoneUrl + "?access_token=" + accessToken; JSONObject body = new JSONObject(); body.put("code", phoneCode); ResponseEntity response = restTemplate.postForEntity(url, body.toJSONString(), String.class); JSONObject json = JSON.parseObject(response.getBody()); int errcode = json.getIntValue("errcode"); // access_token 过期/失效(42001/40001):phoneCode 不会被消耗,可安全重试 if (errcode == 42001 || errcode == 40001) { log.warn("获取手机号 access_token 失效(errcode={}),刷新重试", errcode); invalidateAccessToken(); accessToken = getAccessToken(); url = phoneUrl + "?access_token=" + accessToken; response = restTemplate.postForEntity(url, body.toJSONString(), String.class); json = JSON.parseObject(response.getBody()); errcode = json.getIntValue("errcode"); } if (errcode == 0) { JSONObject phoneInfo = json.getJSONObject("phone_info"); return phoneInfo.getString("phoneNumber"); } throw new RuntimeException("获取手机号失败: " + json.getString("errmsg")); } catch (Exception e) { log.error("getPhoneNumber 异常", e); throw new RuntimeException("获取手机号失败"); } } /** * 生成带参小程序码(getwxacodeunlimit),返回 PNG 字节。 * scene 最长 32 字符(调用方负责截断);page 为小程序页面路径(不能是 tabBar 页)。 * test-mode / 接口失败返回 null,由调用方降级处理。 */ public byte[] generateWxacodeBytes(String scene, String page) { if (testMode) { return null; } try { String accessToken = getAccessToken(); JSONObject body = new JSONObject(); body.put("scene", scene); body.put("page", page); body.put("check_path", false); body.put("env_version", qrcodeEnvVersion); body.put("width", 430); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ResponseEntity response = restTemplate.postForEntity( qrcodeUrl + "?access_token=" + accessToken, new HttpEntity<>(body.toJSONString(), headers), byte[].class); byte[] bytes = response.getBody(); if (bytes == null || bytes.length == 0) { log.warn("生成小程序码返回空字节 scene={} page={}", scene, page); return null; } // 微信失败时返回 JSON(含 errcode)而非图片字节,需识别后降级 String text = new String(bytes, StandardCharsets.UTF_8); if (text.contains("\"errcode\"") && !text.contains("\"errcode\":0")) { log.error("生成小程序码失败 scene={} page={} resp={}", scene, page, text); return null; } return bytes; } catch (Exception e) { log.error("生成小程序码异常 scene={} page={}", scene, page, e); return null; } } /** 获取 access_token(带缓存;供其他服务复用,如订阅消息发送) */ public String getAccessToken() { if (!testMode && cachedAccessToken != null && System.currentTimeMillis() < tokenExpireAt) { return cachedAccessToken; } return doGetAccessToken(); } private String doGetAccessToken() { String url = tokenUrl + "?grant_type=client_credential&appid=" + appid + "&secret=" + secret; ResponseEntity response = restTemplate.getForEntity(url, String.class); JSONObject json = JSON.parseObject(response.getBody()); if (json.containsKey("access_token")) { cachedAccessToken = json.getString("access_token"); // 提前 200 秒刷新(微信 token 有效期 7200 秒) tokenExpireAt = System.currentTimeMillis() + (json.getIntValue("expires_in") - 200) * 1000L; return cachedAccessToken; } throw new RuntimeException("获取 access_token 失败: " + json.toJSONString()); } private void invalidateAccessToken() { cachedAccessToken = null; tokenExpireAt = 0; } }