微信小程序使用code换openid的Java/SpringBoot实现方法
核心实现步骤前端传递code小程序通过wx.login()获取临时登录凭证code,通过HTTP请求发送到后端接口(如/api/wx/session)。
后端接收code并请求微信接口后端使用code向微信服务器换取openid和session_key,需携带小程序的appid和appsecret。
返回结果给前端将微信接口返回的JSON数据(包含openid)直接透传给小程序前端。
代码实现详解1. 配置文件(application.properties或application.yml)# 微信小程序配置wx.appId=你的小程序appidwx.appSecret=你的小程序appsecretwx.grantType=authorization_codewx.requestUrl=https://api.weixin.qq.com/sns/jscode2session
2. 控制器(WeixinController.java)@RestController@RequestMapping("/api/wx")public class WeixinController { private static final Logger log = LoggerFactory.getLogger(WeixinController.class); @Value("${wx.appId}") private String appId; @Value("${wx.appSecret}") private String appSecret; @Value("${wx.grantType}") private String grantType; @Value("${wx.requestUrl}") private String requestUrl; / * 接收小程序code并换取openid */ @GetMapping("/session") public Map<String, Object> getSession(@RequestParam String code) { String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=%s", requestUrl, appId, appSecret, code, grantType); // 调用微信接口 String response = HttpUtil.get(url); log.debug("微信接口响应: {}", response); // 解析JSON结果 ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(response, Map.class); } catch (Exception e) { log.error("解析微信响应失败", e); return Map.of("error", "解析失败"); } }}3. HTTP工具类(HttpUtil.java)public class HttpUtil { private static final String CHARSET = "UTF-8"; / * 发送GET请求 */ public static String get(String url) { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpGet get = new HttpGet(url); try (CloseableHttpResponse response = client.execute(get)) { if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(response.getEntity(), CHARSET); } } } catch (Exception e) { e.printStackTrace(); } return null; }}关键注意事项安全性
必须后端处理:appsecret是敏感信息,严禁在前端暴露。
HTTPS:确保接口使用HTTPS,防止code在传输中被截获。
微信接口响应成功响应示例:
{ "openid": "o123456789", "session_key": "abcdefghijklmn", "unionid": "optional"}错误响应示例:
{"errcode": 40029, "errmsg": "invalid code"}异常处理
记录日志以便排查问题(如无效code、网络错误)。
返回友好错误信息给前端。
前端调用示例(小程序)wx.login({ success(res) { if (res.code) { wx.request({ url: 'https://你的域名/api/wx/session', data: { code: res.code }, success(res) { console.log('openid:', res.data.openid); } }); } }});优化建议缓存机制对openid和session_key进行短期缓存(如Redis),避免频繁请求微信接口。
参数校验检查code是否为空或格式错误。
统一响应格式封装成功/失败响应,例如:
return Map.of( "success", true, "data", json // 微信返回的数据);
通过以上实现,即可安全高效地完成小程序code换取openid的功能。