在小程序中获取用户的openid需要使用微信提供的云开发能力。具体步骤如下:

  1. 在小程序的app.js文件中,配置云开发环境:
App({
  onLaunch: function () {
    // 初始化云开发环境
    wx.cloud.init({
      env: 'your-env-id' // 替换成你的云开发环境ID
    })
  }
})
  1. 在登录页面的Page对象中,获取用户的openid并保存到data中:
const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    institution: '',
    username: '',
    password: '',
    openid: '', // 用户1的openid
    role: ''
  },

  // 监听机构号输入
  handleInstitutionInput(e) {
    this.setData({
      institution: e.detail.value,
    });
  },
  // 监听用户名输入
  handleUsernameInput(e) {
    this.setData({
      username: e.detail.value,
    });
  },

  // 监听密码输入
  handlePasswordInput(e) {
    const encryptedPassword = app.encrypt.hex_md5(e.detail.value);
    this.setData({
      password: encryptedPassword,
    });
  },
  // 登录按钮点击事件
  handleLogin(e) {
    const institution = this.data.institution;
    const username = this.data.username;
    const password = this.data.password;

    // 获取用户的openid
    wx.cloud.callFunction({
      name: 'login',
      data: {
        institution: institution,
        username: username,
        password: password,
      },
      success: res => {
        console.log(res.result);
        const loginResult = res.result;
        if (loginResult === 'admin') {
          // 管理员登录成功
          wx.showToast({
            title: '管理员登录成功',
            icon: 'success',
            duration: 2000
          });
          // 保存登录状态,跳转到管理员页面
          wx.setStorageSync('loginStatus', 'admin');
          wx.redirectTo({
            url: '/pages/admin/admin'
          });
        } else if (loginResult === 'normal') {
          // 普通用户登录成功
          wx.showToast({
            title: '普通用户登录成功',
            icon: 'success',
            duration: 2000
          });
          // 保存登录状态,跳转到普通用户页面
          wx.setStorageSync('loginStatus', 'normal');
          wx.redirectTo({
            url: '/pages/nomal/nomal'
          });
        } else {
          // 登录失败
          wx.showToast({
            title: '用户名或密码错误',
            icon: 'none',
            duration: 2000
          });
          // 刷新页面
          wx.redirectTo({
            url: '/pages/login/login'
          });
        }
      },
      fail: err => {
        console.error(err);
      }
    });
  }
})
  1. 在云函数中,获取用户的openid并返回给小程序:
const cloud = require('wx-server-sdk')
cloud.init()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  // 获取用户的openid
  const openid = wxContext.OPENID

  // 根据机构号、用户名、密码等信息进行登录验证
  // ...

  // 返回用户的openid给小程序
  return {
    openid: openid
  }
}

这样,就可以在小程序中获取用户的openid并进行登录验证了

const app = getApp;const db = wxclouddatabase;Page data institution username password openid 用户1的openid role 监听机构号输入 handleInstitutionInpute thissetData

原文地址: http://www.cveoy.top/t/topic/hY22 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录