WechatService.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package com.train.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.http.HttpEntity;
  7. import org.springframework.http.HttpHeaders;
  8. import org.springframework.http.MediaType;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.client.RestTemplate;
  12. import java.nio.charset.StandardCharsets;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. /**
  16. * 微信 API 封装:jscode2session 换 openid、getPhoneNumber 换手机号。
  17. * 对齐 cfc(E:\cfc)的 WechatService 逻辑;test-mode 下全部走模拟值,
  18. * 不依赖真实微信 API,便于本地无 secret 环境启动。
  19. */
  20. @Slf4j
  21. @Component
  22. public class WechatService {
  23. @Value("${wechat.appid}")
  24. private String appid;
  25. @Value("${wechat.secret}")
  26. private String secret;
  27. @Value("${wechat.login-url}")
  28. private String loginUrl;
  29. @Value("${wechat.phone-url:https://api.weixin.qq.com/wxa/business/getuserphonenumber}")
  30. private String phoneUrl;
  31. @Value("${wechat.token-url:https://api.weixin.qq.com/cgi-bin/token}")
  32. private String tokenUrl;
  33. @Value("${wechat.qrcode-url:https://api.weixin.qq.com/wxa/getwxacodeunlimit}")
  34. private String qrcodeUrl;
  35. @Value("${wechat.qrcode-env-version:release}")
  36. private String qrcodeEnvVersion;
  37. @Value("${wechat.test-mode}")
  38. private boolean testMode;
  39. @Value("${wechat.test-phone:13800138000}")
  40. private String testPhone;
  41. private final RestTemplate restTemplate = new RestTemplate();
  42. /** access_token 缓存(生产环境用;test-mode 不走此路径) */
  43. private volatile String cachedAccessToken;
  44. private volatile long tokenExpireAt;
  45. /**
  46. * 用 login code 换取 openid(jscode2session)。
  47. * test-mode:openid = "test_" + code,与既有 AuthController 行为一致。
  48. */
  49. public String code2Session(String code) {
  50. return code2SessionInfo(code).get("openid");
  51. }
  52. /**
  53. * 用 login code 换取 openid + session_key + unionid(jscode2session)。
  54. * unionid 仅在小程序已绑定微信开放平台账号时由微信返回,用于跨小程序身份归一。
  55. * test-mode:openid = "test_" + code,unionid 为空(对齐 cfc 的 test-mode 行为)。
  56. */
  57. public Map<String, String> code2SessionInfo(String code) {
  58. Map<String, String> result = new HashMap<>();
  59. if (testMode) {
  60. result.put("openid", "test_" + code);
  61. result.put("session_key", "");
  62. result.put("unionid", "");
  63. return result;
  64. }
  65. try {
  66. String url = loginUrl + "?appid=" + appid + "&secret=" + secret
  67. + "&js_code=" + code + "&grant_type=authorization_code";
  68. ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
  69. JSONObject json = JSON.parseObject(response.getBody());
  70. int errcode = json.getIntValue("errcode");
  71. if (errcode != 0) {
  72. throw new RuntimeException("jscode2session 失败: " + json.getString("errmsg"));
  73. }
  74. result.put("openid", json.getString("openid"));
  75. result.put("session_key", json.getString("session_key"));
  76. result.put("unionid", json.getString("unionid"));
  77. return result;
  78. } catch (Exception e) {
  79. log.error("code2Session 异常", e);
  80. throw new RuntimeException("微信登录失败");
  81. }
  82. }
  83. /**
  84. * 用 phoneCode 换取手机号(新版 getPhoneNumber 接口,需 access_token)。
  85. * test-mode:test_<phone> -> phone;合法手机号直接返回;否则返回配置的测试手机号。
  86. */
  87. public String getPhoneNumber(String phoneCode) {
  88. if (testMode) {
  89. if (phoneCode != null && phoneCode.startsWith("test_")) {
  90. return phoneCode.substring(5);
  91. }
  92. if (phoneCode != null && phoneCode.matches("^1[3-9]\\d{9}$")) {
  93. return phoneCode;
  94. }
  95. return testPhone;
  96. }
  97. try {
  98. String accessToken = getAccessToken();
  99. String url = phoneUrl + "?access_token=" + accessToken;
  100. JSONObject body = new JSONObject();
  101. body.put("code", phoneCode);
  102. ResponseEntity<String> response = restTemplate.postForEntity(url, body.toJSONString(), String.class);
  103. JSONObject json = JSON.parseObject(response.getBody());
  104. int errcode = json.getIntValue("errcode");
  105. // access_token 过期/失效(42001/40001):phoneCode 不会被消耗,可安全重试
  106. if (errcode == 42001 || errcode == 40001) {
  107. log.warn("获取手机号 access_token 失效(errcode={}),刷新重试", errcode);
  108. invalidateAccessToken();
  109. accessToken = getAccessToken();
  110. url = phoneUrl + "?access_token=" + accessToken;
  111. response = restTemplate.postForEntity(url, body.toJSONString(), String.class);
  112. json = JSON.parseObject(response.getBody());
  113. errcode = json.getIntValue("errcode");
  114. }
  115. if (errcode == 0) {
  116. JSONObject phoneInfo = json.getJSONObject("phone_info");
  117. return phoneInfo.getString("phoneNumber");
  118. }
  119. throw new RuntimeException("获取手机号失败: " + json.getString("errmsg"));
  120. } catch (Exception e) {
  121. log.error("getPhoneNumber 异常", e);
  122. throw new RuntimeException("获取手机号失败");
  123. }
  124. }
  125. /**
  126. * 生成带参小程序码(getwxacodeunlimit),返回 PNG 字节。
  127. * scene 最长 32 字符(调用方负责截断);page 为小程序页面路径(不能是 tabBar 页)。
  128. * test-mode / 接口失败返回 null,由调用方降级处理。
  129. */
  130. public byte[] generateWxacodeBytes(String scene, String page) {
  131. if (testMode) {
  132. return null;
  133. }
  134. try {
  135. String accessToken = getAccessToken();
  136. JSONObject body = new JSONObject();
  137. body.put("scene", scene);
  138. body.put("page", page);
  139. body.put("check_path", false);
  140. body.put("env_version", qrcodeEnvVersion);
  141. body.put("width", 430);
  142. HttpHeaders headers = new HttpHeaders();
  143. headers.setContentType(MediaType.APPLICATION_JSON);
  144. ResponseEntity<byte[]> response = restTemplate.postForEntity(
  145. qrcodeUrl + "?access_token=" + accessToken,
  146. new HttpEntity<>(body.toJSONString(), headers),
  147. byte[].class);
  148. byte[] bytes = response.getBody();
  149. if (bytes == null || bytes.length == 0) {
  150. log.warn("生成小程序码返回空字节 scene={} page={}", scene, page);
  151. return null;
  152. }
  153. // 微信失败时返回 JSON(含 errcode)而非图片字节,需识别后降级
  154. String text = new String(bytes, StandardCharsets.UTF_8);
  155. if (text.contains("\"errcode\"") && !text.contains("\"errcode\":0")) {
  156. log.error("生成小程序码失败 scene={} page={} resp={}", scene, page, text);
  157. return null;
  158. }
  159. return bytes;
  160. } catch (Exception e) {
  161. log.error("生成小程序码异常 scene={} page={}", scene, page, e);
  162. return null;
  163. }
  164. }
  165. /** 获取 access_token(带缓存;供其他服务复用,如订阅消息发送) */
  166. public String getAccessToken() {
  167. if (!testMode && cachedAccessToken != null && System.currentTimeMillis() < tokenExpireAt) {
  168. return cachedAccessToken;
  169. }
  170. return doGetAccessToken();
  171. }
  172. private String doGetAccessToken() {
  173. String url = tokenUrl + "?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
  174. ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
  175. JSONObject json = JSON.parseObject(response.getBody());
  176. if (json.containsKey("access_token")) {
  177. cachedAccessToken = json.getString("access_token");
  178. // 提前 200 秒刷新(微信 token 有效期 7200 秒)
  179. tokenExpireAt = System.currentTimeMillis() + (json.getIntValue("expires_in") - 200) * 1000L;
  180. return cachedAccessToken;
  181. }
  182. throw new RuntimeException("获取 access_token 失败: " + json.toJSONString());
  183. }
  184. private void invalidateAccessToken() {
  185. cachedAccessToken = null;
  186. tokenExpireAt = 0;
  187. }
  188. }