导入Maven:

        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>wx-java-miniapp-spring-boot-starter</artifactId>
            <version>4.6.1.B</version>
        </dependency>

yaml和properties配置文件:

appid查看:
自己的在微信小程序管理后台,设置》基本设置》账号信息。 或 开发》开发管理》开发设置》开发者ID(可重置 AppSecret 小程序密钥

properties:

wx.miniapp.appid=你的小程序appid
wx.miniapp.secret=你的小程序密钥

yaml:

wx:
  miniapp:
    appid: xxx
    secret: xxx

 现在能获取的用户信息就只有呢称(nickName)和头像(avatarUrl),根据自己需求看需不要保存用户信息。openid这个建议保存,不要暴露在前端。

{
    "nickName": "xxxx",
    "gender": 0,
    "language": "zh_CN",
    "city": "",
    "province": "",
    "country": "",
    "avatarUrl": "头像"
}
    /**
     *
     * @param appid 小程序appid
     * @param code 前端wx.login获取的code
     * @return
     */
   
    @GetMapping("/login")
    public R<Object> login(@PathVariable String appid, String code) {
        if (StrUtil.isBlank(code)) {
            return R.error(RC112.getCode(), "登录凭证不能为空");
        }
        if (!wxMaService.switchover(appid)) {
            return R.error(RC112.getCode(), String.format("未找到对应appid=[%s]的配置,请核实!", appid));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
         //下面做自己的业务逻辑,大概就是去数据库查询信息存不存在,不存在创建用户信息,保存openid
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return R.error(200,e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return R.error(RC500.getCode(),RC500.getMsg());
    }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐