uniapp 小程序实现微信授权登录(前端和后端)

时间:2024-04-11 18:47:04

                       
原文链接:https://blog.csdn.net/weixin_43835425/article/details/131147690

掘金地址:https://juejin.cn/post/7290371873547583548
1.前端:通过 uni.getUserProfile 和 uni.login 来实现
1.主要流程:先通过 uni.getUserProfile授权获取用户名称和头像等信息 在调用 uni.login 获取微信登录需要的临时code
2. 前端代码:

    async onLogin() {
      //获取用户信息 (头像和名称)
      const [, userProfile] = await uni.getUserProfile({
        desc: "获取用户信息",
        lang: "zh_CN",
      });
      if (userProfile) {
        //调用微信登录接口获取临时code 
        const [, loginInfo] = await uni.login({ provider: "weixin" });
        if (loginInfo) {
         // 登录临时code
          const { code } =  loginInfo;
          const {userInfo: { avatarUrl, nickName }} = userProfile;
          // 组装后端接口需要的数据
          const params = {code, avatarUrl, userName: nickName};
          // 调用登录接口
          const { data } = await wxLogin(params);
          uni.setStorageSync(USER_TOKEN, data.token);
          this.$store.commit("SET_USER_INFO", data);
          this.$api.msg("登陆成功");
        }
      }
    },

2.后端:需要通过调用微信提供的第三方接口来实现
1.主要流程:在前端调用接口成功的将临时code 传递给后端时 ,后端通过调用微信的第三方接口拿到 openid, session_key 这两个参数,查询数据库是否有 openid 如果有则更新 session_key ,如果没有则在数据库中新建一条用户信息的数据
2.后端代码(node.js)

/** 
   @description 微信登录
  * @param {String} code 
  * @type {POST}
  * @return 
*/
router.post('/wxLogin', async (req, res, next) => {
  try {
    const { code, avatarUrl, userName } = req.body
    let token = Token.tokenSet()
    // 当前微信开发者的appId
    const appId = 'wx66dee29d470c6095'
    const appSecret = '79ee1240fa1ee8f67066d67fa7692e21';
    // 微信登录的第三方接口
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
    //调用微信登录第三方接口
    const { data: { openid, session_key } } = await axios({ url, method: 'get' })
     //更新当前用户的信息
    const updateInfo = await db.findOneAndUpdate({ openId: openid }, { $set: { sessionKey: session_key, token,avatarUrl,userName } })
    if (updateInfo) {
      const userInfo = await db.findOne({openId: openid})
      return res.jsonp({ code: 1, message: '登录成功', data: userInfo})
    } else {
      //如果当前用户没有登录则插入一条新的用户信息
      const insertInfo = { openId: openid, sessionKey: session_key, userType: 2, status: 1, token, userName,avatarUrl }
      const userInfo = await db.findOne({openId: openid})
      await db.insertMany(insertInfo)
      return res.jsonp({ code: 1, message: '登录成功', data: userInfo})
    }

  } catch {
    next({ message: '接口错误' })
  }
})

 

完整的代码逻辑可参考
前端:https://gitee.com/ZHANG_6666/uni-app/blob/master/pages/myCenter/myCenter.vue
后端:https://gitee.com/ZHANG_6666/express–vue3–ant-design2/blob/master/routes/users.js