wecomLogin.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import { wecomAuth } from "@/api/indexAI";
  2. import router from '@/router'; // 导入你的路由实例
  3. // 企业微信登录相关类型定义(无变化,无需可选链)
  4. export interface GuidInfo {
  5. guid: string;
  6. time: number; // 时间戳(毫秒)
  7. }
  8. export interface LastCode {
  9. code: string;
  10. }
  11. export interface WecomAuthResponse {
  12. StatusCode: number;
  13. Data: {
  14. token: string; // AIToken
  15. };
  16. Message?: string;
  17. }
  18. // 登录中状态锁(避免并发登录请求)
  19. let isLogging = false;
  20. /**
  21. * 校验是否已登录(AIToken 存在 + guidInfo 未过期)
  22. * @returns {boolean} 是否已登录
  23. */
  24. export const checkLoginStatus = (): boolean => {
  25. const AIToken = window.localStorage.getItem('AIToken');
  26. const guidInfoStr = window.localStorage.getItem('guidInfo');
  27. if (!AIToken) return false;
  28. if (!guidInfoStr) return false;
  29. return true;
  30. // try {
  31. // const guidInfo: GuidInfo = JSON.parse(guidInfoStr);
  32. // const currentTime = new Date().getTime();
  33. // const expireTime = 1000 * 60 * 60 * 12; // 12 小时过期
  34. // return guidInfo && guidInfo.guid && (currentTime - guidInfo.time) < expireTime;
  35. // } catch (error) {
  36. // return false;
  37. // }
  38. };
  39. /**
  40. * 初始化 guidInfo
  41. */
  42. export const initGuidInfo = (): void => {
  43. let guidInfo = JSON.parse(window.localStorage.getItem("guidInfo"));
  44. const currentTime = new Date().getTime();
  45. const guid = getGuid();
  46. const guidTime = new Date().getTime();
  47. const newGuidInfo: GuidInfo = { guid, time: guidTime };
  48. // 有缓存但过期-存储
  49. if (guidInfo && (currentTime - guidInfo.time) >= (1000 * 60 * 60 * 12)) {
  50. window.localStorage.setItem("guidInfo", JSON.stringify(newGuidInfo));
  51. window.localStorage.removeItem('lastCode');
  52. } else if (!guidInfo) {
  53. // 无缓存-存储
  54. window.localStorage.setItem('guidInfo', JSON.stringify(newGuidInfo));
  55. }
  56. };
  57. /**
  58. * 企业微信登录核心流程(获取 code → 兑换 AIToken)
  59. * @param code 企业微信授权返回的 code
  60. * @returns {Promise<void>}
  61. */
  62. export const doWecomLogin = async (code: string): Promise<void> => {
  63. if (isLogging) return; // 正在登录中,忽略重复调用
  64. isLogging = true;
  65. try {
  66. const lastCodeStr = window.localStorage.getItem('lastCode');
  67. const lastCode: LastCode | null = lastCodeStr ? JSON.parse(lastCodeStr) : null;
  68. // 同一 code 不重复请求
  69. if (lastCode && lastCode.code === code) {
  70. isLogging = false;
  71. return;
  72. }
  73. // 存储当前 code,避免重复使用
  74. window.localStorage.setItem('lastCode', JSON.stringify({ code }));
  75. const formData = new FormData();
  76. formData.append('code', code);
  77. // 本地登录-需注释
  78. // formData.append("code", 'QWert!@345');
  79. // 调用接口兑换 AIToken
  80. const res: WecomAuthResponse = await wecomAuth(formData);
  81. if (res && res.StatusCode === 200 && res.Data && res.Data.token) {
  82. // 登录成功:存储 AIToken
  83. window.localStorage.setItem('AIToken', res.Data.token);
  84. // 处理身份,身份可能为多个,只能按身份权限大小来固定为某个身份;
  85. let roleIds = res.Data.roleIds, agent = '';
  86. if (roleIds) {
  87. if (roleIds.includes('2')) {
  88. agent = 'stoneLikePaint';//服务商
  89. } else if (roleIds.includes('0')) {
  90. agent = 'ssb';//经销商
  91. } else if (roleIds.includes('4')) {
  92. agent = 'dg';//导购
  93. } else if (roleIds.includes('1')) {
  94. agent = 'hbs';//好邦手
  95. } else if (roleIds.includes('3')) {
  96. agent = 'goldShop';//金牌店
  97. }
  98. console.log("roleIds=", roleIds)
  99. console.log("agent=", agent)
  100. window.localStorage.setItem('agentFrom', agent);
  101. window.localStorage.setItem('agentFromAI', agent);
  102. }
  103. isLogging = false;
  104. // console.log("router.currentRoute.fullPath=",router.currentRoute.fullPath)
  105. // 重新跳转目标页面(此时登录状态已满足)
  106. // router.push(router.currentRoute.fullPath);
  107. } else if (res && res.StatusCode === 403) {
  108. // 无权限 → 跳错误页
  109. isLogging = false;
  110. router.push('/error');
  111. } else if (res && res.StatusCode === 420) {
  112. // 需重新获取 code → 清除缓存并重定向
  113. isLogging = false;
  114. getQyCode(); // 你的获取企业微信二维码/授权链接的函数
  115. } else {
  116. isLogging = false;
  117. throw new Error(res && res.Message ? res.Message : '登录失败');
  118. }
  119. } catch (error) {
  120. isLogging = false;
  121. console.error('企业微信登录失败:', error);
  122. // 登录失败可提示用户或重试
  123. alert('登录失败,请刷新页面重试');
  124. }
  125. };
  126. export const getGuid = () => {
  127. return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  128. let r = Math.random() * 16 | 0,
  129. v = c == 'x' ? r : (r & 0x3 | 0x8);
  130. return v.toString(16);
  131. });
  132. }
  133. export const getQyCode = () => {
  134. window.localStorage.clear();
  135. let url, appid, agentid;
  136. // url = encodeURIComponent(process.env.VUE_APP_AUTHURL);
  137. url = encodeURIComponent(window.location.href);
  138. // console.log("-url=",url)
  139. appid = process.env.VUE_APP_APPID;
  140. agentid = process.env.VUE_APP_AGENTID;
  141. window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=&agentid=${agentid}&t=${new Date().getTime()}#wechat_redirect`;
  142. }
  143. // utils/authLock.js
  144. export const authLock = {
  145. // 内存锁:实时判断
  146. isAuthorizing: false,
  147. // 初始化:从本地缓存恢复锁状态(防止页面刷新后锁失效)
  148. init() {
  149. const lock = window.localStorage.getItem('isWechatAuthorizing');
  150. this.isAuthorizing = lock === 'true';
  151. },
  152. // 加锁:同时更新内存和本地缓存
  153. lock() {
  154. this.isAuthorizing = true;
  155. window.localStorage.setItem('isWechatAuthorizing', 'true');
  156. },
  157. // 解锁:同时更新内存和本地缓存
  158. unlock() {
  159. this.isAuthorizing = false;
  160. window.localStorage.removeItem('isWechatAuthorizing');
  161. }
  162. };
  163. // 初始化锁
  164. authLock.init();