思路拿到微信 code → 传给后端 → 后端验证成功 → 跳首页验证失败 → 弹错误提示。技术采用vue2jsuviewUi的技术使用Hx多端开发工具进行开发第一步分装微信登录请求服务函数用于获取code临时登录凭证要有code发给后端后端才能返回微信用户的个人信息data() { return { app_height : 0, functionArr : [{ text : 便携预约, logo : },{ text : 专业教练, logo : ‍ },{ text : 学习跟踪, logo : }], title: Hello, wxLoginForm: { code : , phonenumber : , password : }, phoneObj : {}, otherBtnArr : [ {logo : ,color : rgb(102, 126, 234)}, {logo : ,color : rgb(18, 183, 245)} ], } },// 方法名wxLogin // 作用【微信登录核心第一步】调用微信授权获取临时登录凭证 code // async标记为异步方法虽然内部用了回调也可以用 async/await 优化 async wxLogin(){ // 1. 获取当前设备支持的登录服务商微信、支付宝、苹果等 uni.getProvider({ // service: oauth 表示获取【登录授权】类的服务商 service: oauth, // 成功获取到服务商信息时执行 success: (res) { // res.provider 是数组返回支持的服务商列表例如 [weixin] // ~ 是按位取反运算符这里用来判断数组中是否包含 weixin 字符串 // 等价于 res.provider.includes(weixin) if (~res.provider.indexOf(weixin)) { // 2. 设备支持微信登录 → 调用 uni.login 发起微信登录 uni.login({ // 指定登录服务商为 微信 provider: weixin, // 微信登录成功 → 获取到临时登录凭证 code success: (loginRes) { // loginRes 包含登录成功信息 // 最重要的就是loginRes.code微信临时凭证5分钟有效 // 把获取到的 code 赋值给表单对象 wxLoginForm this.wxLoginForm.code loginRes.code; // 3. 获取 code 成功后调用方法把 code 传给后端服务 this.sendWxLoginFormToLocalService(); }, // 微信登录失败用户取消授权、网络异常、微信未安装等 fail: (err) { console.error(获取 code 失败:, err); // 控制台打印错误 // 给用户提示 uni.showToast({ title: 获取登录凭证失败, icon: none }); } }) } }, // 获取服务商信息失败系统异常、权限问题 fail: (err) { console.error(获取服务商信息失败:, err); uni.showToast({ title: 获取登录信息失败, icon: none }); } }) },第二步封装微信登录请求用户信息的函数把获取到的code发送给后端// 方法名sendWxLoginFormToLocalService // 作用【微信登录第二步】将前端获取到的微信 code 发送给后端完成登录验证 // async异步方法因为要调用接口请求 async sendWxLoginFormToLocalService() { // 1. 显示加载提示框给用户等待反馈登录中... uni.showLoading({ title:登录中... }); // 2. try-catch捕获登录过程中可能出现的异常网络错误、后端返回失败等 try { // 3. 调用 Vuex 的 action 方法wxLogin // 把登录表单数据包含微信 code传给后端接口 // await等待接口请求完成再执行后面的代码 await this.$store.dispatch(wxLogin, this.wxLoginForm); // 4. 接口请求成功 → 隐藏加载框 uni.hideLoading(); // 5. 弹出成功提示 uni.showToast({ title: 登录成功, icon: success }); // 6. 延迟1.5秒再跳转页面 // 目的让用户能完整看到“登录成功”的提示体验更好 setTimeout(() { // 关闭当前页跳转到首页不能返回 uni.redirectTo({ url: /pages/sub-tabar/index/index }); }, 1500); } // 7. 捕获异常登录失败时执行 catch (error) { // 隐藏加载框 uni.hideLoading(); // 弹出错误提示框 uni.showModal({ title: 提示, // 优先显示后端返回的错误信息没有就显示默认提示 content: ${error.msg} || 登录失败请联系管理员, showCancel: false, // 不显示取消按钮只显示确定 confirmText: 确定 }) } }第三步我在vuex状态管理库的action中封装了最终微信登录的函数// 登录 wxLogin({ commit, dispatch }, loginForm){ return new Promise((resolve, reject) { wxLogin(loginForm).then(res { setToken(res.token) dispatch(getStudentInfo) resolve() }).catch(error reject(error)) }) },