手把手教你做微信小程序授权登录交互(二)

简介: 手把手教你做微信小程序授权登录交互(二)

三、源代码


1.调用微信API wx.login()得到code。


2.把得到的code传给后端,后端获取code请求微信小程序官方接口,返回给前端openid。


3.知道openid后进行用户相关的操作,可以用于分别用户的登录状态。


前台:在GetUserInfo中添加接口


GetUserInfo() {
        var _this = this;
        // 增加约束,不选协议无法进行授权
        if (this.value === false) {
          uni.showToast({
            title: '请阅读勾选协议',
            icon: 'error',
            duration: 2000
          });
        } else {
          uni.getUserProfile({
            desc: '登录',
            lang: 'zh_CN',
            success: (res) => {
              console.log('获取的信息', res.userInfo);
              _this.nickName = res.userInfo.nickName;
              _this.setNn(res.userInfo.nickName);
              uni.getLocation({
                type: 'gci02',
                success: res => {
                  uni.reLaunch({
                    url: 'Login2'
                  });
                }
              });
            },
            fail: (res) => {
              console.log('用户拒绝了授权');
              uni.showToast({
                title: '授权失败',
                icon: 'error',
                duration: 2000
              });
            }
          });
        }
      }
login() {
          let _this = this;
          uni.showLoading({
            title: '登录中...'
          });
          // 获取登录用户 code
          uni.login({
            provider: 'weixin',
            success: function(res) {
              if (res.code) {
                let code = res.code;
                console.log('用户code:', res.code);
                uni.request({
                  url: "https://xxxxxxx:8084/wxLogin/getOpenid",
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    code: res.code, //wx.login 登录成功后的code 
                    role: _this.role,
                  },
                  success: function(cts) {
                    var openid = cts.data.openid; //openid 用户唯一标识
                    var userInfo = {
                      openid: openid,
                      role: _this.role
                    };
                    console.log(_this.role);
                    _this.saveUserInfo(userInfo);
                    uni.hideLoading();
                    uni.switchTab({
                                            // 登录成功后的跳转
                      url: '../myCenter/myCenter'
                    });
                  }
                });
              } else {
                uni.showToast({
                  title: '登录失败!',
                  duration: 2000
                });
                console.log('登录失败!' + res.errMsg)
              }
            },
          });
      }
    }


后台:SpringBoot后台数据处理


  1. 首先获取的自己小程序的appid、secret,封装为一个接口


  1. 接口当中,拼接sql,向微信发送http请求


3.将返回的结果进行封装,封装成map集合返回给前端


@PostMapping("/getOpenid")
    @ResponseBody
    public Map<String, Object> getOpenId(@RequestParam("code") String code,
                                         @RequestParam(value = "role") Integer role) throws IOException {
        // 返回code
        System.out.println("========== 进入wxLogin/getOpenid方法  ==========");
        System.err.println("微信授权登录");
        System.err.println("code值:  " + code);
        Map<String, Object> resultMap = new HashMap<>();
        String appid = ConstUtil.getAppId();
        String secret = ConstUtil.getSECRET();
        // 拼接sql
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        // 创建httpGet请求
        HttpGet httpGet = new HttpGet(loginUrl);
        // 发送请求
        client = HttpClients.createDefault();
        // 执行请求
        response = client.execute(httpGet);
        // 得到返回数据
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println("微信返回的结果" + result);
        resultMap.put("data", result);
        // 对返回的结果进行解析
        JSONObject json_test = JSONObject.parseObject(result);
        String openid = json_test.getString("openid");
        String sessionKey = json_test.getString("session_key");
        System.err.println("openid值: " + openid);
        System.err.println("sessionKey值" + sessionKey);
        Users users = usersService.getUserByOpenid(openid);
        System.err.println("用户信息:" + users);
        if (StringUtils.isEmpty(openid)) {
            resultMap.put("state", ResponseCode.SUCCESS.getCode());
            resultMap.put("message", "未获取到openid");
            return resultMap;
        } else {
            // 判断是否为首次登陆
            if (users == null) {
                resultMap.put("state", ResponseCode.SUCCESS.getCode());
                resultMap.put("openid", openid);
                resultMap.put("sessionKey", sessionKey);
                resultMap.put("message", "未查询到用户信息");
            } else {
                // 查询有无结果
                UserRole uRes = userRoleService.getUserRole(openid, role);
                // 封装对象
                UserRole userRole = new UserRole(openid, role);
                // 如果不是第一次登录,第二次登陆进行判断,如果没有这个身份,进行添加,如果有这个身份,不做处理
                if (uRes == null) {
                    userRoleService.insert(userRole);
                }
                resultMap.put("state", ResponseCode.SUCCESS.getCode());
                // 前台拿的数据是map的key
                resultMap.put("openid", openid);
                resultMap.put("sessionKey", sessionKey);
                resultMap.put("user", users);
                resultMap.put("message", "该用户已经存在");
            }
            response.close();
            client.close();
        }
        return resultMap;
    }


四、实现效果


image.png

相关文章
|
13天前
|
存储 小程序 前端开发
微信小程序与Java后端实现微信授权登录功能
微信小程序极大地简化了登录注册流程。对于用户而言,仅仅需要点击授权按钮,便能够完成登录操作,无需经历繁琐的注册步骤以及输入账号密码等一系列复杂操作,这种便捷的登录方式极大地提升了用户的使用体验
133 12
|
3月前
|
小程序 前端开发 算法
|
4月前
|
移动开发 前端开发 Android开发
开发指南059-App实现微信扫描登录
App是用uniapp开发的,打包为apk,上传到安卓平板中使用
|
4月前
|
小程序 算法 前端开发
微信小程序---授权登录
微信小程序---授权登录
133 0
|
6月前
|
存储 小程序 JavaScript
|
27天前
|
小程序 前端开发 关系型数据库
基于Uniapp+php校园小程序,校园圈子论坛系统功能,校园跑腿二手交流功能设计
校园圈子论坛及综合服务平台集成了校园跑腿、兼职信息、外卖团购、闲置交换、租赁服务、表白墙等多功能模块,提供一站式校园生活解决方案。系统采用uniapp前端和PHP后端开发,支持多城市、多学校切换,配备分站式后台管理,确保稳定性和安全性。通过融云IM SDK实现即时通讯功能,增强用户互动与粘性。适用于大学校园、城市及社区圈子,满足多样化需求,提升便捷体验。
|
1月前
|
移动开发 小程序 前端开发
超详细攻略!uniapp陪玩系统,打包陪玩小程序、H5需要注意什么?
陪玩系统的打包过程涵盖APP、小程序和H5平台。APP打包需使用uni-app开发工具,配置项目信息并选择云打包;小程序打包需在微信公众平台注册账号并提交审核;H5打包则直接通过uni-app生成文件并上传至服务器。各平台需注意权限配置、代码规范及充分测试,确保应用稳定性和兼容性。
|
30天前
|
移动开发 小程序
thinkphp+uniapp开发的多端商城系统源码/H5/小程序/APP支持DIY模板直播分销
thinkphp+uniapp开发的多端商城系统源码/H5/小程序/APP支持DIY模板直播分销
27 0
|
3月前
|
小程序 前端开发 JavaScript
在线课堂+工具组件小程序uniapp移动端源码
在线课堂+工具组件小程序uniapp移动端源码
81 0
在线课堂+工具组件小程序uniapp移动端源码
|
4月前
|
移动开发 小程序 数据可视化
基于npm CLI脚手架的uniapp项目创建、运行与打包全攻略(微信小程序、H5、APP全覆盖)
基于npm CLI脚手架的uniapp项目创建、运行与打包全攻略(微信小程序、H5、APP全覆盖)
567 3

热门文章

最新文章