微信小程序登录
2025/12/1大约 2 分钟
微信小程序登录
文档地址
总流程:微信小程序登录官方文档
wx.login() 接口:wx.login() 官方文档
服务端获取 session_key 和 openid 接口:code2Session 官方文档
登录流程
- 小程序调用
wx.login()本地调用,获取临时登录凭证 code。 - 小程序将 code 发送到后端服务器。
- 后端服务器使用 code 调用微信的
code2Session接口,获取 session_key 和 openid。 - 后端生成自己的登录态(如 JWT token)并返回给小程序。
- 小程序保存登录态,用于后续请求。
示例代码
springboot 后端示例
DTO只有code属性,VO有openid,session_key,authentication属性
首先controller接收WechatUserLoginDTO仅包含code,
然后向微信接口发送code,appid,secret,grant_type=authorization_code获取session_key和openid。
最后根据openid查询数据库,如果存在则返回,不存在则创建。
创建token返回。
@Operation(summary = "微信小程序登录接口")
@PostMapping("/login")
public Result<WechatUserLoginVO> login(@RequestBody WechatUserLoginDTO wechatUserLoginDTO){
//需要请求微信平台获取用户信息
//请求地址:https://api.weixin.qq.com/sns/jscode2session
//请求参数appid(String),secret(String),js_code(String),grant_type(String)默认authorization_code
HashMap<String, Object> params = new HashMap<>();
params.put("appid",appid);
params.put("secret",secret);
params.put("js_code", wechatUserLoginDTO.getCode());
params.put("grant_type","authorization_code");
String responseBody = httpUtil.get("https://api.weixin.qq.com/sns/jscode2session", params);
log.info("responseBody:{}",responseBody);
Object parseObject = httpUtil.parseJson(responseBody, Object.class);
//相应内容:
//session_key string 会话密钥
//unionid string 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台帐号下会返回,详见 UnionID 机制说明。
//errmsg string 错误信息,请求失败时返回
//openid string 用户唯一标识
//errcode int32 错误码,请求失败时返回
WechatUserLoginVO wechatUserLoginVO = BeanUtil.copyProperties(parseObject, WechatUserLoginVO.class);
log.info("{}",wechatUserLoginVO);
//根据openid唯一标识查询微信用户。
WxUser wxUser = wxUserService.getOrCreateByOpenid(wechatUserLoginVO.getOpenid());
HashMap<String, Object> wxclaims = new HashMap<>();
wxclaims.put("open_id",wxUser.getOpenid());
String authentication = JwtUtil.createJWT(
jwtProperties.getWxSecretKey(),
jwtProperties.getWxTtl(),
wxclaims
);
wechatUserLoginVO.setAuthentication(authentication);
return Result.success(wechatUserLoginVO);
}WechatUserLoginDTO:
@Data
public class WechatUserLoginDTO implements Serializable {
//前端通过wx.login()获取的code
private String code;
}WechatUserLoginVO:
@Data
public class WechatUserLoginVO {
private String authentication;
private String session_key;
private String openid;
}