当前位置: 首页 > news >正文

微信小程序授权登录

1. 微信授权登录

官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。

1.1. 登录流程时序

说明:

  1. 调用 wx.login() 获取临时登录凭证code,并回传到开发者服务器。
  2. 调用 auth.code2Session 接口,换取用户唯一标识 OpenID、 用户在微信开放平台账号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台账号) 和会话密钥 session_key

之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。

1.2. 小程序端

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

wx.login(Object object)调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)

详情见官方文档

1.3. 服务器端

官方文档:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。

详情见官方文档

1.4. 微信Java开发工具包

文档:https://gitee.com/binary/weixin-java-tools

微信Java开发工具包,支持包括微信支付、开放平台、公众号、企业微信/企业号、小程序等微信功能模块的后端开发。

微信小程序:weixin-java-miniapp

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

2. 准备工作

首先扫码登录微信公众平台,在【开发管理】页面获取AppID和AppSecrt,此处后面配置会用到。如果忘记AppSecrt可点击重置保存。

其次,小程序登录需要获取code值,什么是code?用大白话来说,它就是微信给小程序用户发的「一次性临时门票」,用来换「永久身份证(openId)」。

接着讲如何获取登录接口所需要的code值。

打开微信开发者工具,加入AppId对应的开发者平台

等待项目自动编译并运行后,在console控制台输入wx.login(res => console.log('code:', res.code))

点击[[PromiseResult]]: Object前面的小箭头 ▶️,展开后就能看到code字段,直接复制后面的字符串即可!

3. 登录接口开发

3.1. 引入依赖

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

3.2. yaml配置

# 可选多个appId配置wx:miniapp:appId:wxcc651fcbab275e33secret:5f353399a2eae7ff6ceda383e924c5f6configs:-appid:wxcc651fcbab275e33secret:5f353399a2eae7ff6ceda383e924c5f6token:s5sda5daf5dawddaesKey:eRA7lTyHSqDZk4j39eOBMwRfxHLUNMZq2Qlc6FiFJtVmsgDataFormat:JSON-appid:wxcc651fcbab275e34secret:5f353399a2eae7ff6ceda383e924c5f7token:s5sda5daf5dawdfaesKey:qgMtJkuKxsDC31DEdZXVAAXJQuuT4TXHe3ftgEwE1uBmsgDataFormat:JSON

3.3. WxMaProperties

@Data@ConfigurationProperties(prefix="wx.miniapp")publicclassWxMaProperties{// private String appId;//// private String secret;privateList<Config>configs;@DatapublicstaticclassConfig{/** * 设置微信小程序的appid */privateStringappid;/** * 设置微信小程序的Secret */privateStringsecret;/** * 设置微信小程序消息服务器配置的token */privateStringtoken;/** * 设置微信小程序消息服务器配置的EncodingAESKey */privateStringaesKey;/** * 消息格式,XML或者JSON */privateStringmsgDataFormat;}}

3.4. WxMaConfiguration

配置WxMaService,通过WxMaService可以快速获取微信OpenId

/** * @author <a href="https://github.com/binarywang">Binary Wang</a> */@Slf4j@Configuration@EnableConfigurationProperties(WxMaProperties.class)publicclassWxMaConfiguration{@AutowiredprivatefinalWxMaPropertiesproperties;@AutowiredpublicWxMaConfiguration(WxMaPropertiesproperties){this.properties=properties;}// @Bean// public WxMaService wxMaService() {// WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();// config.setAppid(properties.getAppId());// config.setSecret(properties.getSecret());//// WxMaService service = new WxMaServiceImpl();// service.setWxMaConfig(config);// return service;// }@BeanpublicWxMaServicewxMaService(){List<WxMaProperties.Config>configs=this.properties.getConfigs();if(configs==null){thrownewWxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");}WxMaServicemaService=newWxMaServiceImpl();maService.setMultiConfigs(configs.stream().map(a->{WxMaDefaultConfigImplconfig=newWxMaDefaultConfigImpl();// WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());// 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常config.setAppid(a.getAppid());config.setSecret(a.getSecret());// config.setToken(a.getToken());// config.setAesKey(a.getAesKey());// config.setMsgDataFormat(a.getMsgDataFormat());returnconfig;}).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid,a->a,(o,n)->o)));returnmaService;}}

3.5. UserDetail

控制台输入wx.getUserInfo({success:res=>console.log(res)})即可获取如下参数值,sessionKey需从登录接口返回值中获取。

@DatapublicclassUserDetail{privateStringappid;privateStringsessionKey;privateStringencryptedData;privateStringiv;privateStringrawData;privateStringsignature;}

3.6. UserInfoApiController

@Slf4j@RestController@RequestMapping("/userInfo")publicclassUserInfoApiController{@AutowiredprivateWxMaServicewxMaService;/** * 登录接口 */@GetMapping("/wxLogin")publicResponseEntity<String>wxLogin(@RequestParamStringcode){StringopenId=null;try{//获取openIdWxMaJscode2SessionResultsessionInfo=wxMaService.getUserService().getSessionInfo(code);log.info("【小程序授权】sessionInfo={}",JSONUtil.toJsonStr(sessionInfo));openId=sessionInfo.getOpenid();log.info("【小程序授权】openId={}",openId);// TODO: 根据openId获取用户信息}catch(Exceptione){thrownewRuntimeException("微信登录失败");}returnResponseEntity.ok("登录成功");}/** * 获取用户信息接口 */@PostMapping("/info")publicStringinfo(@RequestBodyUserDetailuserDetail){Stringappid=userDetail.getAppid();Stringiv=userDetail.getIv();Stringsignature=userDetail.getSignature();StringrawData=userDetail.getRawData();StringsessionKey=userDetail.getSessionKey();StringencryptedData=userDetail.getEncryptedData();if(!wxMaService.switchover(appid)){thrownewIllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!",appid));}// 用户信息校验if(!wxMaService.getUserService().checkUserInfo(sessionKey,rawData,signature)){WxMaConfigHolder.remove();//清理ThreadLocalreturn"user check failed";}// 解密用户信息WxMaUserInfouserInfo=wxMaService.getUserService().getUserInfo(sessionKey,encryptedData,iv);//WxMaPhoneNumberInfo userInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);WxMaConfigHolder.remove();//清理ThreadLocalreturnJSONUtil.toJsonStr(userInfo);}}
http://www.cnnetsun.cn/news/1870277.html

相关文章:

  • 深入理解ES6 Promise
  • Python电子书处理终极指南:如何用EbookLib轻松管理EPUB文件
  • STM32H743双CAN总线负载太高?试试用CubeIDE+CanFestival同时跑两个CANopen主站
  • 深度解析Unity资源管理:YooAsset 2.2.12跨平台加密方案完全指南
  • BiliTools:3步解锁哔哩哔哩高效学习新体验,让知识获取速度提升300%
  • 5个简单步骤:使用Campus-Imaotai实现茅台自动预约的完整指南
  • Redis 高级篇(最佳实践)
  • 解锁博士论文“超能力”:好写作AI,学术征途的“超级外挂”
  • 把 ABAP RFC Gateway 日志真正配明白,SMGW、gw/logging 与 secinfo、reginfo 的实战思路
  • 【自动驾驶】从轨迹规划到安全评估:核心术语场景化解读
  • CoPaw驱动智能RPA:通过自然语言指令自动化办公流程
  • Windows 11系统优化指南:用Win11Debloat释放40%系统性能
  • 终极指南:如何绕过Windows驱动签名强制验证(DSEFix完整教程)
  • SystemVerilog--- task---高效调试与验证技巧
  • DeepSeek-R1-Distill-Qwen-1.5B实战:低配电脑也能流畅运行的代码助手
  • 图图的嗨丝造相-Z-Image-Turbo多场景落地:动漫同人图/轻小说插画/游戏立绘
  • 003、YOLO初探:目标检测核心思想与YOLO系列模型演进史
  • Self-Reflection如何提升Agent输出质量
  • 芯片设计新手必看:三大定律背后的实战避坑指南(附最新行业趋势)
  • Java浏览器自动化的终极革命:Jvppeteer深度解析与实践指南
  • ROS串口通讯实战:从蓝牙设备读取并解析数据
  • 终极指南:Windows系统快速安装苹果USB和移动设备以太网驱动
  • 模块化架构引擎:重构英雄联盟客户端工具集的技术实现
  • 专业VMP脱壳工具:如何高效实现VMProtect逆向分析与修复
  • 智能家居监控——基于STM32与ESP8266-01S的DHT11温湿度数据实时上传至阿里云物联网平台(一)
  • 机器学习与深度学习的区别全面对比:什么区别如何选择研究方向区别
  • 良心推荐:零基础学深度学习需要学哪些框架?PyTorch 和 TensorFlow 选哪个?
  • 测试工程师的“大家来找茬”职业病,在生活中有多可怕?
  • 2025最权威的六大AI学术助手解析与推荐
  • 从产品经理视角看技术实现:拆解‘苍穹外卖’套餐管理的业务逻辑与接口设计