uniapp 开发微信小程序 登录功能

登录一般会获取电话号码,但是电话号码获取的前提是需要,在微信开发者平台 进行小程序的微信验证。

打开小程序后台 -> 设置 -> 基本设置

 认证时需要支付300元认证费用。大概需要1-3工作日。

如果小程序关联过已认证的工作号,那么可以复用公众号资质快速认证

登录代码参考:

async getPhoneNumber(e) {
      let that = this;
      // console.log("获取手机号code",e.detail.code) //获取手机号已经不需要先进行wx.login(最新文档)
      if (!e.detail.code) {
        uni.showToast({
          title: '登录需要获取您的手机号',
          icon: 'none',
          duration: 2500
        })
        return
      }
      try {
        uni.showLoading({ // 展示加载框
          title: '加载中',
        });
        let phoneRes = await phone({ code: e.detail.code })
        uni.setStorageSync("phone", phoneRes.content.phoneNumber)
        // console.log(phoneRes);
        uni.login({
          provider: 'weixin',
          success: async function (res) {
            console.log(res);
            if (res.errMsg == "login:ok") {
              let loginRes = await login({ code: res.code, phone: phoneRes.content.phoneNumber })
              // let loginRes = await login({ code: res.code, phone: '18720978538' })//bug复现用,登录不同手机号
              if (loginRes.state = 1) {
                // console.log(loginRes);
                that.$store.dispatch("setLogined", loginRes)//保存本地保存到vuex
                uni.showToast({
                  title: "登陆成功~",
                  duration: 1900
                })
              } else {
                uni.showToast({
                  title: "登录失败!",
                  icon: 'error',
                  duration: 2000
                })
                console.log("登录失败");
              }

              try {
                // 登录成功获得userid,然后判断是否关联过加盟商
                let cooerInfo = await iscooper({ userId: loginRes.content.wxUserInfo.userId })
                console.log(cooerInfo);
                that.$store.dispatch("setCooperInfo", cooerInfo)//保存本地保存到vuex
              } catch (error) {
                console.log("获取加盟商信息error", error);
              }
            } else {
              uni.showToast({
                title: "登录网络故障,请重试",
                icon: 'none',
                duration: 2500
              })
            }
          },
          fail: () => { //uni.login 失败的回调
            uni.showToast({
              title: '授权已取消',
              icon: 'error',
              mask: true,
            });
          },
          complete: () => {
            // 隐藏loading
            uni.hideLoading();
          },
        })
      } catch (error) {
        console.log("获取电话号码error", errpr);
      }
    },

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/130982440