我们在做小程序开发的过程中,经常会涉及到用户认证的问题,最普遍的就是获取用户的手机号码一键登录
获取用户手机号码 分为以下几步:
1、第一点击页面获取授权code
2、第二获取小程序token
3、第三根据token与code获取手机号码
4、执行登录认证逻辑
接下来我们来实现以上四步
首先先看前端页面获取code与手机号码:
weChatLogin(e){ uni.showLoading({title:"登录中....",mask:true}) let code= e.detail.code; let url = "/api/miniWxApi/getPhoneNum?code="+code; this.$u.get(url).then(res => { let phoneNum = res.phoneNum let weChatUrl = "/api/weChatLogin"; this.$u.post(weChatUrl,{ username: phoneNum, code: code }).then(data => { uni.hideLoading(); // 登录成功初始化token与用户信息 this.$u.vuex('vuex_token', data.token); this.$u.vuex('vuex_user', data.loginUser); uni.switchTab({ url: '/pages/index/index' }) }); }); },
接下来我们看后端获取token与认证逻辑:
/** * 获取用户手机号码 */ @GetMapping("/getPhoneNum") public AjaxResult getPhoneNum(String code){ AjaxResult ajax = AjaxResult.success(); // Object token = getAccessToken(); Object token = WxUtil.obtainAccessToken(APPID, SECRET); String phoneNum = WxUtil.getPhoneNum(token,code); ajax.put("phoneNum",phoneNum); return ajax; } /** * 获取AccessToken */ @GetMapping("/getAccessToken") public AjaxResult getAccessToken(){ AjaxResult ajax = AjaxResult.success(); Object token = redisCache.getCacheObject(accessTokenKey); if(StringUtils.isNull(token)){ token = WxUtil.obtainAccessToken(APPID, SECRET); redisCache.setCacheObject(accessTokenKey,token,30,TimeUnit.MINUTES); } ajax.put(accessTokenKey,token); return ajax; } /** * 微信小程序注册/登录 */ @PostMapping("/weChatLogin") public AjaxResult weChatLogin(HttpServletRequest request,@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); String msg = "登录成功"; if (StringUtils.isEmpty(loginBody.getUsername())){ msg = "用户名不能为空"; return error(msg); } // 判断是否为新用户 SysUser sysUser = userService.selectUserByUserName(loginBody.getUsername()); // 不是新用户,创建用户 if(sysUser == null){ sysUser = new SysUser(); sysUser.setUserName(loginBody.getUsername()); sysUser.setNickName(loginBody.getUsername()); sysUser.setPassword(loginBody.getUsername()); sysUser.setPhonenumber(loginBody.getUsername()); sysUser.setPassword(SecurityUtils.encryptPassword(loginBody.getUsername())); sysUser.setDeptId(110L); Long[] postIds = new Long[1]; postIds[0] = 8L; Long[] roleIds = new Long[1]; roleIds[0] = 5L; sysUser.setPostIds(postIds); sysUser.setRoleIds(roleIds); // 保存完用户后,还需要设置用户的角色,部门与岗位 userService.insertUser(sysUser); } // 生成token LoginUser loginUser = new LoginUser(sysUser,null); String token = tokenService.createToken(loginUser); ajax.put(Constants.TOKEN, token); ajax.put("loginUser", loginUser); return ajax; }
如上步骤即可实现uniapp微信小程序登录,开源字节坚持写优雅的代码,以上代码可在开源字节低代码平台中免费获取
如若转载,请注明出处:开源字节 https://sourcebyte.cn/article/209.html