news 2026/2/25 6:32:48

微信小程序获取-openid和sessionKey以及用户信息

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
微信小程序获取-openid和sessionKey以及用户信息

1.获取openid和sessionKey
yml文件配置appid和secret(申请小程序应用的时候提供):

wechat: appid: 0000 secret: 1111111111

实体类:

package com.jmdz.api.utils.GetWeiXin; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class LoginRequest { @ApiModelProperty("微信登录code") private String code; @ApiModelProperty("租户id") private Integer tenantId; @ApiModelProperty("微信昵称") private String nickName; @ApiModelProperty("微信头像") private String avatarUrl; @ApiModelProperty("性别 0-未知 1-男性 2-女性") private Integer gender; @ApiModelProperty("微信unionId") private String unionId; @ApiModelProperty("国家") private String country; @ApiModelProperty("省份") private String province; @ApiModelProperty("手机号") private String phone; @ApiModelProperty("微信openId") private String openId; @ApiModelProperty("城市") private String city; }

接口调用:

说明:1.接口返回是自己写的方法,可以根据框架自己处理

2.code是小程序前端获取到的

package com.jmdz.api.utils.GetWeiXin; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.jmdz.api.entity.WxUser; import com.jmdz.api.mapper.WxUserDao; import com.jmdz.api.service.WxUserService; import com.jmdz.api.vo.BaseResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.util.Date; /** * 微信用户(WxUser)表接口实现 * * @author add * @since 2025-12-29 */ @RestController @RequestMapping("/auth") public class LoginController { @Value(value = "${wechat.appid}") private String appid; @Value(value = "${wechat.secret}") private String secret; @Resource private WxUserDao wxUserDao; @PostMapping("/login") public BaseResult login(@RequestBody LoginRequest request) { // 1. 用 code 获取 openid 和 session_key String url = "https://api.weixin.qq.com/sns/jscode2session" + "?appid=" + appid + "&secret=" + secret + "&js_code=" + request.getCode() + "&grant_type=authorization_code"; // 发送 HTTP 请求获取 session RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject(url, String.class); // 解析响应,获取 openid 和 session_key JSONObject jsonObject = JSON.parseObject(response); String openid = jsonObject.getString("openid"); String sessionKey = jsonObject.getString("session_key"); WxUser users = wxUserDao.selectOne(new QueryWrapper<WxUser>().eq("open_id", openid)); if (users != null) { return BaseResult.ok("已注册").setData(users); } else { // 2. 处理用户信息,存储到数据库 WxUser user = new WxUser(); user.setOpenId(openid); user.setUsername(request.getNickName()); user.setSessionKey(sessionKey); user.setIsManage(0); // 默认不是管理员 user.setCreateTime(new Date()); user.setDelFlag(0); // 默认不是删除 user.setTenantId(request.getTenantId()); // 租户id user.setCreateBy("system"); int insert = wxUserDao.insert(user); // 返回结果给前端 if (insert <= 0) { return BaseResult.error(500, "登录失败"); } else { return BaseResult.ok("登录成功").setData(user); } } } }

2.获取小程序的手机号,用户名以及头像
在POM文件增加SDK

<dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-miniapp</artifactId> <version>4.4.0</version> </dependency>

用户信息加密实体类:

package com.jmdz.api.utils.send; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @ApiModel("微信登录DTO") public class WxLoginDto { @ApiModelProperty(value = "微信登录code", required = true) private String code; @ApiModelProperty("加密的用户数据") private String encryptedData; @ApiModelProperty("加密算法的初始向量") private String iv; @ApiModelProperty("加密的手机号数据") private String phoneEncryptedData; @ApiModelProperty("手机号加密算法的初始向量") private String phoneIv; }

Config类:

package com.jmdz.api.utils.send; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WxMaConfiguration { @Value(value = "${wechat.appid}") private String appid; @Value(value = "${wechat.secret}") private String secret; @Bean public WxMaConfig wxMaConfig() { WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); config.setAppid(appid); config.setSecret(secret); return config; } @Bean public WxMaService wxMaService(WxMaConfig wxMaConfig) { WxMaService wxMaService = new WxMaServiceImpl(); wxMaService.setWxMaConfig(wxMaConfig); return wxMaService; } }

service:

public interface WxUserService extends IService<WxUser> { /** * 获取微信小程序服务实例 * @return WxMaService */ WxMaService getWxMaService(); }

impl:

@Service("wxUserService") public class WxUserServiceImpl extends ServiceImpl<WxUserDao, WxUser> implements WxUserService { @Autowired private WxMaService wxMaService; /*添加获取WxMaService的方法*/ public WxMaService getWxMaService() { return this.wxMaService; } }

接口调用:(本人将用户名,头像,以及手机号放在一起了,应该是单独请求的将4.1去掉就是分别调用的方法)

package com.jmdz.api.utils.send; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaUserInfo; import com.jmdz.api.entity.WxUser; import com.jmdz.api.service.WxUserService; import com.jmdz.api.vo.BaseResult; import com.jmdz.api.vo.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; ; @Api(tags = "微信用户管理") @RestController @RequestMapping("/wxUser") @Slf4j public class WxUserController { @Resource private WxUserService wxUserService; @ApiOperation(value = "微信登录获取用户信息", notes = "通过微信登录code获取用户信息") @PostMapping("/getInfo") public BaseResult<WxUser> wxLogin(@RequestBody WxLoginDto loginDto) { try { // 1. 获取WxMaService实例 WxMaService wxMaService = wxUserService.getWxMaService(); // 2. 使用code获取session信息 WxMaJscode2SessionResult session = wxMaService.jsCode2SessionInfo(loginDto.getCode()); String openId = session.getOpenid(); String sessionKey = session.getSessionKey(); // 3. 检查用户是否已存在 WxUser existingUser = wxUserService.lambdaQuery() .eq(WxUser::getOpenId, openId) .one(); // 4. 如果有加密数据,解密用户信息 if (loginDto.getEncryptedData() != null && loginDto.getIv() != null) { WxMaUserInfo userInfo = wxMaService.getUserService() .getUserInfo(sessionKey, loginDto.getEncryptedData(), loginDto.getIv()); // 4.1 解密手机号 String phoneNumber = null; if (loginDto.getPhoneEncryptedData() != null && loginDto.getPhoneIv() != null) { WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService() .getPhoneNoInfo(sessionKey, loginDto.getPhoneEncryptedData(), loginDto.getPhoneIv()); phoneNumber = phoneInfo.getPhoneNumber(); } // 创建或更新用户 WxUser wxUser = existingUser != null ? existingUser : new WxUser(); wxUser.setOpenId(openId); wxUser.setPhone(phoneNumber); wxUser.setUsername(userInfo.getNickName()); wxUser.setAvatarUrl(userInfo.getAvatarUrl()); if (existingUser == null) { wxUserService.save(wxUser); } else { wxUserService.updateById(wxUser); } return BaseResult.ok("修改成功").setData(wxUser); } return BaseResult.ok("获取成功").setData(existingUser); } catch (Exception e) { log.error("获取微信信息失败", e); return BaseResult.error("获取微信信息失败: " + e.getMessage()); } } @ApiOperation(value = "获取用户手机号", notes = "解密微信手机号") @PostMapping("/getPhoneNumber") public Result<String> getPhoneNumber(@RequestBody WxLoginDto loginDto) { try { // 1. 获取WxMaService实例 WxMaService wxMaService = wxUserService.getWxMaService(); // 2. 使用code获取session信息 WxMaJscode2SessionResult session = wxMaService.jsCode2SessionInfo(loginDto.getCode()); String sessionKey = session.getSessionKey(); // 3. 解密手机号 WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService() .getPhoneNoInfo(sessionKey, loginDto.getPhoneEncryptedData(), loginDto.getPhoneIv()); String phoneNumber = phoneInfo.getPhoneNumber(); // 4. 更新用户手机号 String openId = session.getOpenid(); wxUserService.lambdaUpdate() .eq(WxUser::getOpenId, openId) .set(WxUser::getPhone, phoneNumber) .update(); return Result.OK("手机号获取成功", phoneNumber); } catch (Exception e) { log.error("获取手机号失败", e); return Result.error("获取手机号失败: " + e.getMessage()); } } }

小程序端调用:

// 1. 微信登录 wx.login({ success: (res) => { const code = res.code; // 获取用户信息 wx.getUserInfo({ success: (userRes) => { const encryptedData = userRes.encryptedData; const iv = userRes.iv; // 调用后端接口 wx.request({ url: '/jeecg-boot/wxUser/wxLogin', method: 'POST', data: { code: code, encryptedData: encryptedData, iv: iv }, success: (result) => { console.log('登录成功', result.data); } }); } }); } }); // 2. 获取手机号 wx.getPhoneNumber({ success: (res) => { const phoneEncryptedData = res.encryptedData; const phoneIv = res.iv; // 再次登录获取新的code wx.login({ success: (loginRes) => { const newCode = loginRes.code; // 调用后端接口 wx.request({ url: '/jeecg-boot/wxUser/getPhoneNumber', method: 'POST', data: { code: newCode, phoneEncryptedData: phoneEncryptedData, phoneIv: phoneIv }, success: (result) => { console.log('手机号获取成功', result.data); } }); } }); } });
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/24 10:06:57

GDS Decompiler终极指南:从零开始掌握文件解编工具

GDS Decompiler终极指南&#xff1a;从零开始掌握文件解编工具 【免费下载链接】gdsdecomp Godot reverse engineering tools 项目地址: https://gitcode.com/gh_mirrors/gd/gdsdecomp 想要深入了解Godot游戏资源的结构吗&#xff1f;GDS Decompiler正是您需要的强大文件…

作者头像 李华
网站建设 2026/2/18 9:42:39

PyTorch-CUDA-v2.9镜像支持实时语音克隆应用

PyTorch-CUDA-v2.9 镜像在实时语音克隆中的实践与优化 在智能语音技术飞速发展的今天&#xff0c;用户对“个性化声音”的需求正以前所未有的速度增长。从虚拟偶像的定制配音&#xff0c;到客服系统的千人千声&#xff0c;再到有声读物中模仿特定播音员语调——实时语音克隆已不…

作者头像 李华
网站建设 2026/2/24 13:01:06

VMware Unlocker完整指南:3分钟解锁macOS虚拟化

想要在普通PC上体验苹果系统吗&#xff1f;VMware Unlocker就是你的完美解决方案&#xff01;这款开源工具专门解除macOS在非苹果硬件上的运行限制&#xff0c;让Windows和Linux用户都能轻松享受完整的苹果系统虚拟化体验。 【免费下载链接】unlocker 项目地址: https://git…

作者头像 李华
网站建设 2026/2/24 14:43:31

PyTorch-CUDA-v2.9镜像支持HuggingFace Transformers无缝接入

PyTorch-CUDA-v2.9 镜像如何让 HuggingFace 模型开箱即用&#xff1f; 在深度学习项目中&#xff0c;最让人头疼的往往不是模型设计本身&#xff0c;而是环境配置——“为什么在我机器上能跑&#xff0c;在你那里就报错&#xff1f;”这种问题几乎成了每个 AI 工程师都经历过的…

作者头像 李华
网站建设 2026/2/25 4:08:43

如何绕过Cursor试用限制:新手必学的5个技巧

如何绕过Cursor试用限制&#xff1a;新手必学的5个技巧 【免费下载链接】go-cursor-help 解决Cursor在免费订阅期间出现以下提示的问题: Youve reached your trial request limit. / Too many free trial accounts used on this machine. Please upgrade to pro. We have this …

作者头像 李华
网站建设 2026/2/22 19:44:50

从焊板子到架构师:我的2025嵌入式技术深耕与创作之路

从硬件焊接到软件架构&#xff0c;从单片机调试到系统设计&#xff0c;技术成长与知识分享同步进行——2025年的我&#xff0c;仍在持续学习、持续创作的道路上。2025年即将画上句号&#xff0c;当我回望这一年&#xff0c;发现时间给予嵌入式开发者的既不是简单重复&#xff0…

作者头像 李华