wlzboy
5 天以前 3bbd80a63ac7728ac01b641a48a26befcb171a0f
feat:增加企业微信登录判断
1个文件已添加
4个文件已修改
391 ■■■■■ 已修改文件
app/App.vue 56 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/pages/index.vue 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/pages/login.vue 88 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/pages/qylogin.vue 139 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/utils/wechat.js 106 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/App.vue
@@ -4,6 +4,7 @@
  import { getToken } from '@/utils/auth'
  import { getUnreadCount } from '@/api/message'
  import storage from '@/utils/storage'
  import { redirectToLoginByEnvironment } from '@/utils/wechat'
  export default {
    data() {
@@ -87,59 +88,8 @@
      // 检查登录状态并自动跳转到合适的登录页面
      checkLoginAndRedirect(options) {
        if (!getToken()) {
          // 检查运行环境并跳转到对应的登录页面
          // #ifdef MP-WEIXIN
          // 在微信小程序环境中
          try {
            // 获取系统信息
            const systemInfo = uni.getSystemInfoSync()
            console.log('系统信息:', systemInfo)
            // 检查environment字段是否为wxwork
            if (systemInfo.environment === 'wxwork') {
              console.log('检测到企业微信环境,跳转到企业微信免登页面')
              // 构造带参数的URL
              let url = '/pages/qylogin'
              if (options && options.query) {
                const queryParams = Object.keys(options.query).map(key => `${key}=${encodeURIComponent(options.query[key])}`).join('&')
                if (queryParams) {
                  url += '?' + queryParams
                }
              }
              this.$tab.reLaunch(url)
              return
            } else {
              console.log('检测到普通微信环境,跳转到微信登录页面')
              // 构造带参数的URL
              let url = '/pages/login'
              if (options && options.query) {
                const queryParams = Object.keys(options.query).map(key => `${key}=${encodeURIComponent(options.query[key])}`).join('&')
                if (queryParams) {
                  url += '?' + queryParams
                }
              }
              this.$tab.reLaunch(url)
              return
            }
          } catch (e) {
            console.error('获取系统信息失败:', e)
            // 默认跳转到普通登录页面
            this.$tab.reLaunch('/pages/login')
          }
          // #endif
          // #ifndef MP-WEIXIN
          // 非微信小程序环境,跳转到普通登录页面
          console.log('非微信小程序环境,跳转到普通登录页面')
          let url = '/pages/login'
          if (options && options.query) {
            const queryParams = Object.keys(options.query).map(key => `${key}=${encodeURIComponent(options.query[key])}`).join('&')
            if (queryParams) {
              url += '?' + queryParams
            }
          }
          this.$tab.reLaunch(url)
          // #endif
          // 使用工具类根据环境自动跳转到合适的登录页面
          redirectToLoginByEnvironment(options, this.$tab);
        }
      },
      
app/pages/index.vue
@@ -279,7 +279,7 @@
    this.hasSubscribed = true;//subscribeManager.checkLocalSubscribeStatus();
    // 自动订阅(如果未订阅则显示确认弹窗)
    this.autoSubscribeOnLaunch();
    // this.autoSubscribeOnLaunch();
    // 加载用户绑定车辆信息
    this.loadUserVehicle();
app/pages/login.vue
@@ -64,6 +64,7 @@
<script>
  import { getCodeImg, loginByOpenId, loginByWechatPhone } from '@/api/login'
  import { isWxWorkEnvironment,redirectToQyLogin } from '@/utils/wechat'
  export default {
    data() {
@@ -92,6 +93,9 @@
    onLoad(options) {
      // 保存页面参数
      this.pageOptions = options || {}
      if(isWxWorkEnvironment()){
        redirectToQyLogin(options,this.$tab);
      }
    },
    created() {
      this.getCode()
@@ -159,15 +163,8 @@
        this.$store.dispatch('GetInfo').then(res => {
          // 触发登录成功事件,启动消息轮询
          uni.$emit('user-login')
          // 检查是否有redirect参数指定跳转页面
          if (this.pageOptions.redirect) {
            // 解码redirect参数
            const redirectUrl = decodeURIComponent(this.pageOptions.redirect)
            this.$tab.reLaunch(redirectUrl)
          } else {
            // 默认跳转到首页
            this.$tab.reLaunch('/pages/index')
          }
          // 处理自动跳转逻辑
          this.redirectAfterLogin()
        })
      },
      
@@ -184,6 +181,8 @@
        this.isWechat = false
        console.log('当前环境:非微信小程序')
        // #endif
      },
      
      // 尝试自动登录(检查本地是否有保存的OpenID)
@@ -251,15 +250,10 @@
                  const { setToken } = require('@/utils/auth')
                  setToken(token)
                  
                  // 检查是否有redirect参数指定跳转页面
                  if (this.pageOptions.redirect) {
                    // 解码redirect参数
                    const redirectUrl = decodeURIComponent(this.pageOptions.redirect)
                    this.$tab.reLaunch(redirectUrl)
                  } else {
                    // 默认跳转到首页
                    this.$tab.reLaunch('/pages/index')
                  }
                  // 获取用户信息并处理自动跳转逻辑
                  this.$store.dispatch('GetInfo').then(() => {
                    this.redirectAfterLogin()
                  });
                } else {
                  this.$modal.msgError(response.msg || '登录失败')
                }
@@ -297,15 +291,10 @@
            const { setToken } = require('@/utils/auth')
            setToken(token)
            
            // 检查是否有redirect参数指定跳转页面
            if (this.pageOptions.redirect) {
              // 解码redirect参数
              const redirectUrl = decodeURIComponent(this.pageOptions.redirect)
              this.$tab.reLaunch(redirectUrl)
            } else {
              // 默认跳转到首页
              this.$tab.reLaunch('/pages/index')
            }
            // 获取用户信息并处理自动跳转逻辑
            this.$store.dispatch('GetInfo').then(() => {
              this.redirectAfterLogin()
            });
          } else {
            // OpenID未绑定或验证失败,需要获取手机号绑定
            console.log('该OpenID尚未绑定或验证失败,需要获取手机号')
@@ -317,6 +306,51 @@
          console.error('登录失败:', error)
          this.$modal.msgError('登录失败,请重试')
        })
      },
      /**
       * 获取URL参数
       */
      getUrlParam(name) {
        // #ifdef H5
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        const r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        // #endif
        // #ifdef MP-WEIXIN
        // 在小程序中,参数通过onLoad的options传递
        if (this.pageOptions && this.pageOptions[name]) {
          return decodeURIComponent(this.pageOptions[name]);
        }
        // #endif
        return null;
      },
      /**
       * 登录成功后的跳转处理
       */
      redirectAfterLogin() {
        try {
          // 检查是否有redirect参数指定跳转页面
          let redirectUrl = this.getUrlParam("redirect");
          if (redirectUrl) {
            // 解码redirect参数
            redirectUrl = decodeURIComponent(redirectUrl);
            console.log("自动跳转到指定页面:", redirectUrl);
            this.$tab.reLaunch(redirectUrl);
          } else {
            // 默认跳转到首页
            console.log("跳转到首页");
            this.$tab.reLaunch('/pages/index');
          }
        } catch (e) {
          console.error("跳转失败,使用默认跳转:", e);
          // 出现异常时,默认跳转到首页
          this.$tab.reLaunch('/pages/index');
        }
      }
    }
  }
app/pages/qylogin.vue
@@ -20,6 +20,7 @@
<script>
import { qyWechatAutoLogin } from "@/api/login";
import { buildUrlWithParams } from "@/utils/wechat";
export default {
  data() {
@@ -40,26 +41,6 @@
  },
  methods: {
    async getLoginCode() {
      //这里要调用wx.qy.login获取code,是否有集成到uni-app中呢
      return new Promise((resolve, reject) => {
        wx.qy.login({
          success: (res) => {
            if (res.code) {
              console.log("企业微信小程序 ---> code:", res.code);
              resolve(res.code); // 返回 code 给后端
            } else {
              reject(new Error("获取 code 失败:" + res.errMsg));
            }
          },
          fail: (err) => {
            console.error("wx.qy.login 调用失败:", err);
            // 常见失败原因:非企业微信客户端打开、小程序未关联企业微信等
            reject(new Error("企业微信登录接口调用失败:" + err.errMsg));
          },
        });
      });
    },
    /**
     * 企业微信免登流程
     */
@@ -72,13 +53,11 @@
        // 在微信小程序环境中,通过企业微信免登
        console.log("企业微信小程序环境免登");
        // 获取URL参数中的code
        // 直接通过企业微信API获取code,不使用URL中的code
        const code = await this.getLoginCode();
        if (!code) {
          // 如果没有code,尝试通过企业微信API获取
          this.handleWxWorkLogin();
          return;
          throw new Error("无法获取企业微信授权code");
        }
        // 调用后端接口进行免登
@@ -89,7 +68,7 @@
          const token = response.data.token;
          
          this.$store.commit('SET_TOKEN', token)
           // 必须调用setToken保存到本地存储
          // 必须调用setToken保存到本地存储
          const { setToken } = require('@/utils/auth')
          setToken(token)
          // 获取用户信息
@@ -109,10 +88,10 @@
        }
        // 获取URL参数中的code
        const codeH5 = this.getUrlParam("code");
        let codeH5 = this.getUrlParam("code");
        // 如果URL中没有code,则跳转到企业微信授权页面
        if (!codeH5) {
          // 如果没有code,则跳转到企业微信授权页面
          this.redirectToWxWorkAuth();
          return;
        }
@@ -148,56 +127,46 @@
    },
    /**
     * 处理企业微信登录
     * 获取企业微信登录code
     */
    handleWxWorkLogin() {
      // #ifdef MP-WEIXIN
      // 在企业微信小程序中,可以直接调用企业微信登录API
      uni.login({
        provider: "weixin",
        success: (loginRes) => {
          console.log("企业微信登录成功", loginRes);
          // 调用后端接口进行免登
          qyWechatAutoLogin(loginRes.code)
            .then((response) => {
              if (response.code === 200) {
                // 免登成功,保存token
                const token = response.data.token;
                this.$store.commit("SET_TOKEN", token);
                uni.setStorageSync("token", token);
                // 获取用户信息
                this.$store.dispatch("GetInfo").then(() => {
                  // 跳转到首页或其他指定页面
                  this.redirectAfterLogin();
                });
              } else {
                throw new Error(response.msg || "免登失败");
              }
            })
            .catch((error) => {
              console.error("免登失败:", error);
              this.loading = false;
              this.error = true;
              this.errorMessage = error.message || "免登失败,请稍后重试";
            });
        },
        fail: (err) => {
          console.error("企业微信登录失败:", err);
          this.loading = false;
          this.error = true;
          this.errorMessage = "企业微信登录失败,请稍后重试";
        },
    getLoginCode() {
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        // 使用企业微信小程序API获取code
        wx.qy.login({
          success: (res) => {
            if (res.code) {
              console.log("企业微信小程序 ---> code:", res.code);
              resolve(res.code);
            } else {
              reject(new Error("获取code失败:" + res.errMsg));
            }
          },
          fail: (err) => {
            console.error("wx.qy.login调用失败:", err);
            reject(new Error("企业微信登录接口调用失败:" + err.errMsg));
          },
        });
        // #endif
        // #ifndef MP-WEIXIN
        resolve(null);
        // #endif
      });
      // #endif
    },
    /**
     * 检查是否在企业微信环境
     */
    isWxWorkEnvironment() {
      // #ifdef H5
      const userAgent = navigator.userAgent.toLowerCase();
      return userAgent.includes("wxwork");
      // #endif
      // #ifndef H5
      return false;
      // #endif
    },
    /**
@@ -211,17 +180,20 @@
      // #endif
      // #ifdef MP-WEIXIN
      // 在小程序中可以通过其他方式获取参数
      // 这里简化处理,实际项目中可以根据需要调整
      // 在小程序中,参数通过onLoad的options传递
      if (this.pageOptions && this.pageOptions[name]) {
        return decodeURIComponent(this.pageOptions[name]);
      }
      // #endif
      return null;
    },
    /**
     * 跳转到企业微信授权页面
     * 跳转到企业微信授权页面(H5环境)
     */
    redirectToWxWorkAuth() {
      // #ifdef H5
      // 从全局配置中获取企业微信配置
      const config = getApp().globalData.config;
      const corpId = config.qyWechatCorpId || "your_corp_id"; // 企业ID
@@ -232,19 +204,30 @@
      const authUrl = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${corpId}&agentid=${agentId}&redirect_uri=${redirectUri}&state=${state}`;
      window.location.href = authUrl;
      // #endif
    },
    /**
     * 登录成功后的跳转处理
     */
    redirectAfterLogin() {
      // 检查是否有redirect参数指定跳转页面
      if (this.pageOptions.redirect) {
        // 解码redirect参数
        const redirectUrl = decodeURIComponent(this.pageOptions.redirect);
        this.$tab.reLaunch(redirectUrl);
      } else {
        // 默认跳转到首页
      try {
        // 检查是否有redirect参数指定跳转页面
        let redirectUrl = this.getUrlParam("redirect");
        if (redirectUrl) {
          // 解码redirect参数
          redirectUrl = decodeURIComponent(redirectUrl);
          console.log("自动跳转到指定页面:", redirectUrl);
          this.$tab.reLaunch(redirectUrl);
        } else {
          // 默认跳转到首页
          console.log("跳转到首页");
          this.$tab.reLaunch("/pages/index");
        }
      } catch (e) {
        console.error("跳转失败,使用默认跳转:", e);
        // 出现异常时,默认跳转到首页
        this.$tab.reLaunch("/pages/index");
      }
    },
app/utils/wechat.js
New file
@@ -0,0 +1,106 @@
/**
 * 微信环境检测和跳转工具类
 */
/**
 * 检查是否为企业微信环境
 * @returns {Promise<boolean>} 是否为企业微信环境
 */
export function isWxWorkEnvironment() {
  return new Promise((resolve) => {
    // #ifdef MP-WEIXIN
    try {
      // 获取系统信息
      const systemInfo = uni.getSystemInfoSync();
      console.log('系统信息:', systemInfo);
      // 检查environment字段是否为wxwork
      resolve(systemInfo.environment === 'wxwork');
    } catch (e) {
      console.error('获取系统信息失败:', e);
      resolve(false);
    }
    // #endif
    // #ifndef MP-WEIXIN
    resolve(false);
    // #endif
  });
}
/**
 * 构造带参数的URL
 * @param {string} baseUrl 基础URL
 * @param {Object} queryParameters 查询参数对象
 * @returns {string} 构造后的URL
 */
export function buildUrlWithParams(baseUrl, queryParameters) {
  if (!queryParameters) return baseUrl;
  const queryParams = Object.keys(queryParameters)
    .map(key => `${key}=${encodeURIComponent(queryParameters[key])}`)
    .join('&');
  if (queryParams) {
    return baseUrl + '?' + queryParams;
  }
  return baseUrl;
}
/**
 * 根据环境自动跳转到合适的登录页面
 * @param {Object} options 启动参数
 * @param {Object} tab tab导航对象
 */
export async function redirectToLoginByEnvironment(options, tab) {
  // #ifdef MP-WEIXIN
  // 在微信小程序环境中
  try {
    const isWxWork = await isWxWorkEnvironment();
    if (isWxWork) {
      console.log('检测到企业微信环境,跳转到企业微信免登页面');
      // 构造带参数的URL
     redirectToQyLogin(options,tab);
      return;
    } else {
      console.log('检测到普通微信环境,跳转到微信登录页面');
      redirectToLogin(options,tab);
      return;
    }
  } catch (e) {
    console.error('环境检测失败:', e);
   redirectToLogin(options,tab);
  }
  // #endif
  // #ifndef MP-WEIXIN
  // 非微信小程序环境,跳转到普通登录页面
  console.log('非微信小程序环境,跳转到普通登录页面');
  redirectToLogin(options,tab);
  // #endif
}
export  function redirectToQyLogin(options,tab){
    let url = '/pages/qylogin';
      if (options && options.query) {
        url = buildUrlWithParams(url, options.query);
      }
      tab.reLaunch(url);
}
export  function redirectToLogin(options,tab){
    let url = '/pages/login';
      if (options && options.query) {
        url = buildUrlWithParams(url, options.query);
      }
      tab.reLaunch(url);
}
export default {
  isWxWorkEnvironment,
  buildUrlWithParams,
  redirectToLogin,
  redirectToQyLogin,
  redirectToLoginByEnvironment
};