当前位置: 首页 > 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.jsqmd.com/news/635379/

相关文章:

  • 避坑指南:vue-flip-page翻页组件在移动端的适配问题与解决方案
  • 第一款AI自动对焦的热成像E8,自动对焦会成为热成像的标配吗 - 博客湾
  • 终极指南:如何用BiliTools构建你的个人B站资源图书馆 [特殊字符]
  • Ubuntu 20.04 下 GAMMA 2022 安装避坑全记录:从依赖库版本到环境变量配置
  • 《哔哩哔哩(B站)商品详情页前端性能优化实战》
  • 从零到一:uniapp蓝牙打印实战避坑指南
  • 终极Alienware灯光控制指南:3个步骤让你的设备重新发光
  • ZED SVO视频转换全攻略:从安装到5种导出模式详解(附常见问题解决)
  • 深度学习周报(4.6~4.12)
  • 【2024最前沿AIAgent架构白皮书】:基于127个生产级Agent案例验证的注意力分层设计法则
  • 毫无经验做Ozon运营,Captain AI助你瞬间成为老手!
  • 从零到一:用Leaflet构建交互式疫情地图可视化
  • Linux内核中的进程调度器详解
  • 2026年新疆新能源汽车漆面防护与轻改升级完全指南|车闪电官方联系方式+行业深度横评 - 精选优质企业推荐榜
  • 55.5%高增速锚定!双足仿人形机器人赛道开启未来六年黄金增长期
  • Transmission终极指南:从基础部署到高级调优的完全手册
  • 电动汽车对IEEE 33节点电网影响的汽车负荷预测与节点潮流网损、压损计算——四种场景应用
  • STM32F407通过FSMC接口驱动LAN9252 EtherCAT从站实战
  • 无线射频基础:从波长、频率到振幅与相位的实战解析
  • STM32H743双CAN总线负载太高?试试用CubeIDE+CanFestival同时跑两个CANopen主站
  • Fish Speech 1.5效果展示:听听AI生成的自然流畅语音
  • 2026年新疆新能源汽车漆面防护与轻改升级完全指南:车闪电官方联系方式+主流品牌横评+避坑指南 - 精选优质企业推荐榜
  • BiliTools:3步解锁哔哩哔哩高效学习新体验,让知识获取速度提升300%
  • 2026 年国内托盘式桥架厂家排名前十权威发布:安徽鑫铂特电气有限公司位居榜首 - 安互工业信息
  • 2026年高纯气体过滤有哪些品牌?行业精选推荐 - 品牌排行榜
  • 如何实现抗体亲和力的高效优化?
  • 如何不用 iTunes 将 iPhone 备份到移动硬盘?
  • 现代 .NET(.NET Core 5+)架构,原生跨平台
  • 基于.NET 6 + GTK的Winform跨平台实战:从Windows到Linux/Mac的无缝迁移
  • 这 12 个神级免费工具,我用了才知道白白多花了好几年冤枉钱!