uni-app 微信小程序授权登录的实现步骤

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了uni-app 微信小程序授权登录的实现步骤脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在这里插入图片描述

一、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);
        },
      });
    },
   }

获取的用户基础数据(无openid=》微信用户唯一标识)

在这里插入图片描述

2.2. 获取用户信息2

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

页面一样,js部分:

   getUserInfo() {
      uni.getUserProfile({
        desc: '登录后可同步数据',
        lang: 'zh_CN',
        success: (res) => {
          console.log('getUserProfile', res);
        },
      });
    },

获取的用户基础数据(无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.1. 官网文档

官网文档
使用获取到的code请求微信登录接口,获取 openid 和 session_key

在这里插入图片描述

4.2. 接口简述

在这里插入图片描述

请求方式:GET
APPID:小程序唯一标识,上面有获取方式
SECRET:小程序唯一标识的秘钥,上面参考APPID获取方式,就在他的下面
JSCODE:这个前端调用 &nbsp;uni.login获取

GET https://api.weixin.QQ.COM/sns/jscode2session?appid=APPID&amp;secret=SECRET&js_code=JSCODE&grant_type=authorization_code

在这里插入图片描述

五、绑定用户 实现登录

获取到微信用户的唯一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();
        },
      });
    },

后端部分

   @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();
        }
    }

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();
        },
      });
    },
  },

user.js

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

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));
    },

在这里插入图片描述

在这里插入图片描述

六、项目开地址

6.1. 前端

applet-chock-in

6.2. 后端

weixin-java-miniapp

到此这篇关于uni-app 微信小程序授权登录的文章就介绍到这了,更多相关uni-app 微信小程序授权登录内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的uni-app 微信小程序授权登录的实现步骤全部内容,希望文章能够帮你解决uni-app 微信小程序授权登录的实现步骤所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: