关键词搜索

源码搜索 ×
×

uni-app 微信小程序授权登录

发布2022-01-02浏览8504次

详情内容

在这里插入图片描述

一、appID相关申请和配置
1. appid获取方式

登录微信公众平台
官网链接:https://mp.weixin.qq.com/
第一次需要小伙伴们点击注册按钮,进行注册,如果有账号,直接扫描登录即可
在这里插入图片描述

官网小程序链接:

在这里插入图片描述

2. appID配置

在manifest.json中输入申请的微信小程序id
在这里插入图片描述

二、获取用户基础数据

这里给小伙伴们演示二种api

2.1. 获取用户信息

可以使用uni.getUserProfile请求用户授权获取用户信息, 也可以使用uni.getUserInfo获取
在这里插入图片描述
授权成功后获取到的用户信息在userInfo中:
在这里插入图片描述

  • 页面部分:
  <button class="login-btn" type="primary" @click="getUserInfo">
        微信用户一键登录
      </button>
    • js部分:
    
     methods: {
        getUserInfo() {
          uni.getUserInfo({
            provider: 'weixin',
            success: (res) => {
              console.log('getUserInfo', res);
            },
          });
        },
       }
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 获取的用户基础数据(无openid=》微信用户唯一标识)
      在这里插入图片描述
    2.2. 获取用户信息2

    可以使用uni.getUserInfo请求用户授权获取用户信息

    • 页面一样,js部分:
       getUserInfo() {
          uni.getUserProfile({
            desc: '登录后可同步数据',
            lang: 'zh_CN',
            success: (res) => {
              console.log('getUserProfile', res);
            },
          });
        },
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 获取的用户基础数据(无openid=》微信用户唯一标识)
      在这里插入图片描述
      总结:uni.getUserProfile和uni.getUserInfo 二个api获取的用户数据基本一样,都无openid=》微信用户唯一标识。
    三、调用登录api
    3.1. 登录api

    使用uni.login方法,provider参数输入’weixin’,成功的返回值中如果errMsg=“login:ok” 代表成功,
    微信小程序端会返回一个code字符串
    在这里插入图片描述

    3.2. 案例代码
          uni.login({
                provider: 'weixin',
                success: (res) => {
                  console.log('res-login', res);
                  this.code = res.code;
                  console.log('code', res.code);
                  if (res.errMsg == 'login:ok') {
                  //TODO 获取code 携带code参数调用后端接口}
    
      4
    • 5
    • 6
    • 7
    • 8
    四、获取唯一标识信息
    4.1. 官网文档

    官网文档
    使用获取到的code请求微信登录接口,获取 openid 和 session_key
    在这里插入图片描述

    4.2. 接口简述

    在这里插入图片描述

    请求方式:GET
    APPID:小程序唯一标识,上面有获取方式
    SECRET:小程序唯一标识的秘钥,上面参考APPID获取方式,就在他的下面
    JSCODE:这个前端调用  uni.login获取
    
      4
    GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    
    
    • 1
    • 2

    在这里插入图片描述

    五、绑定用户 实现登录

    获取到微信用户的唯一id后,就可以绑定至自己系统中的用户,我的做法是在用户表中加入weixinId字段,跳转至自己的用户绑定界面,如果用户选择绑定微信,则更新该行用户数据的weixinId。下次用户使用微信登录时,如果通过openId能够查询到一条用户数据,说明已经绑定,则登录该用户

    5.1. 代码案例(未封装)
    • 前端部分:
     /**
         *
         * 获取用户信息
         */
        getUserInfo() {
          // 展示加载框
          uni.showLoading({
            title: '加载中',
          });
          uni.getUserProfile({
            desc: '登录后可同步数据',
            success: async (obj) => {
              console.log('obj', obj);
              // 调用 action ,请求登录接口
              // await this.login(obj);
              uni.login({
                provider: 'weixin',
                success: (res) => {
                  console.log('res-login', res);
                  this.code = res.code;
                  console.log('code', res.code);
                  if (res.errMsg == 'login:ok') {
                    uni
                      .request({
                        url:
                          'http://127.0.0.1:8080/wxh5/wx/user/' +
                          'wx55822xxxx75e422' +
                          '/login/',
                        data: {
                          code: this.code,
                        },
                      })
                      .then((res) => {
                      //获取到 openid 和 session_k后,自己的逻辑
                        console.log('授权登录', res[1].data);
                        console.log(res[1].data.openid);
                        console.log(res[1].data.session_key);
                        // DoSomeThing.................
                      });
                    console.log('res', res);
                  }
                },
              });
            },
            fail: () => {
              uni.showToast({
                title: '授权已取消',
                icon: 'error',
                mask: true,
              });
            },
            complete: () => {
              // 隐藏loading
              uni.hideLoading();
            },
          });
        },
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 后端部分
       @GetMapping("/login")
        public String login(@PathVariable String appid, String code) {
            if (StringUtils.isBlank(code)) {
                return "empty jscode";
            }
    
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
    
            try {
                WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
                this.logger.info(session.getSessionKey());
                this.logger.info(session.getOpenid());
                //TODO 可以增加自己的逻辑,关联业务相关数据
                return JsonUtils.toJson(session);
            } catch (WxErrorException e) {
                this.logger.error(e.getMessage(), e);
                return e.toString();
            }
        }
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    5.2. 代码案例(封装)
      /**
         *
         * 获取用户信息
         */
        getUserInfo() {
          // 展示加载框
          uni.showLoading({
            title: '加载中',
          });
          uni.getUserProfile({
            desc: '登录后可同步数据',
            success: async (obj) => {
              // this.userInfo = obj.userInfo;
              // 调用 action ,请求登录接口
              uni.login({
                provider: 'weixin',
                success: async (res) => {
                  this.code = res.code;
                  // console.log('登录获取code', res.code);
                  if (res.errMsg == 'login:ok') {
                    await this.loginAuth({
                      userProfile: obj,
                      appid: 'wx558xxxxxxxxxxxxxxx2',
                      code: this.code,
                    });
                  }
                },
              });
            },
            fail: () => {
              uni.showToast({
                title: '授权已取消',
                icon: 'error',
                mask: true,
              });
            },
            complete: () => {
              // 隐藏loading
              uni.hideLoading();
            },
          });
        },
      },
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    user.js

    /**
     * 微信用户授权登录,携带appid和code参数,调用后端接口获取Openid
     */
    export function loginAuth(data) {
      return request({
        url: '/wx/user/' + data.appid + '/login/',
        data: {
          code: data.code,
        },
      });
    }
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    vuex user模块(user.js)

      // 微信用户授权登录,携带appid和code参数,调用后端接口获取Openid
        async loginAuth(context, data) {
          console.log('data', data);
          const userInfo = data.userProfile;
          const { content: res } = await loginAuth({
            appid: data.appid,
            code: data.code,
          });
    
          // 解析后端传送过来的json对象
          const userAuthInfo = JSON.parse(res);
          const openid = userAuthInfo.openid;
          // console.log('sessionKey', userAuthInfo.sessionKey);
          console.log('openid', openid);
    
          // 保存到vuex中,通过commit
          this.commit('user/setOpenid', userAuthInfo.openid);
          this.commit('user/setUserInfo', JSON.parse(userInfo.rawData));
        },
    
      4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述
    在这里插入图片描述

    六、项目开源地址
    6.1. 前端

    applet-chock-in

    6.2. 后端

    weixin-java-miniapp

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载