App.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <script>
  2. import Vue from 'vue'
  3. import BASE_URL from './config.js'
  4. import { mapActions } from 'vuex'
  5. import loginService from '@/api/auth/loginService'
  6. import * as dd from 'dingtalk-jsapi'
  7. export default {
  8. onLaunch: function () {
  9. uni.getSystemInfo({
  10. success: function (e) {
  11. // #ifndef MP
  12. Vue.prototype.StatusBar = e.statusBarHeight;
  13. if (e.platform == 'android') {
  14. Vue.prototype.CustomBar = e.statusBarHeight + 50;
  15. } else {
  16. Vue.prototype.CustomBar = e.statusBarHeight + 45;
  17. };
  18. // #endif
  19. // #ifdef MP-WEIXIN
  20. Vue.prototype.StatusBar = e.statusBarHeight;
  21. let custom = wx.getMenuButtonBoundingClientRect();
  22. Vue.prototype.Custom = custom;
  23. Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
  24. // #endif
  25. // #ifdef MP-ALIPAY
  26. Vue.prototype.StatusBar = e.statusBarHeight;
  27. Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
  28. // #endif
  29. }
  30. })
  31. Vue.prototype.ColorList = [{
  32. title: '嫣红',
  33. name: 'red',
  34. color: '#e54d42'
  35. },
  36. {
  37. title: '桔橙',
  38. name: 'orange',
  39. color: '#f37b1d'
  40. },
  41. {
  42. title: '明黄',
  43. name: 'yellow',
  44. color: '#fbbd08'
  45. },
  46. {
  47. title: '橄榄',
  48. name: 'olive',
  49. color: '#8dc63f'
  50. },
  51. {
  52. title: '森绿',
  53. name: 'green',
  54. color: '#39b54a'
  55. },
  56. {
  57. title: '天青',
  58. name: 'cyan',
  59. color: '#1cbbb4'
  60. },
  61. {
  62. title: '海蓝',
  63. name: 'blue',
  64. color: '#0081ff'
  65. },
  66. {
  67. title: '姹紫',
  68. name: 'purple',
  69. color: '#6739b6'
  70. },
  71. {
  72. title: '木槿',
  73. name: 'mauve',
  74. color: '#9c26b0'
  75. },
  76. {
  77. title: '桃粉',
  78. name: 'pink',
  79. color: '#e03997'
  80. },
  81. {
  82. title: '棕褐',
  83. name: 'brown',
  84. color: '#a5673f'
  85. },
  86. {
  87. title: '玄灰',
  88. name: 'grey',
  89. color: '#8799a3'
  90. },
  91. {
  92. title: '草灰',
  93. name: 'gray',
  94. color: '#aaaaaa'
  95. },
  96. {
  97. title: '墨黑',
  98. name: 'black',
  99. color: '#333333'
  100. },
  101. {
  102. title: '雅白',
  103. name: 'white',
  104. color: '#ffffff'
  105. },
  106. ]
  107. },
  108. onShow: function () {
  109. console.log('App Show')
  110. },
  111. onHide: function () {
  112. console.log('App Hide')
  113. },
  114. created: async function () {
  115. const urlParams = this.getUrlParams();
  116. if (await this.tryDingTalkAutoLogin(urlParams)) {
  117. return;
  118. }
  119. // 获取 URL 中的 code 参数
  120. const code = urlParams.get('code');
  121. console.log('传入 code -------');
  122. console.log(code);
  123. if (code) {
  124. try {
  125. // 发起请求获取用户信息
  126. const [err, res] = await uni.request({
  127. url: BASE_URL + `/flowable-server/app/proxy?appid=wxbcd608a92d6f9412&secret=69d382e18089367566df595b102fe756&code=` + code,
  128. method: 'GET'
  129. });
  130. if (res && res.statusCode === 200) {
  131. //console.log('用户信息获取成功-----------');
  132. const data = res.data;
  133. //console.log(data);
  134. //console.log(data.openId);
  135. // 将微信用户的 openId 存到本地
  136. uni.setStorageSync('openId', data.openId);
  137. //console.log('getStorageSync-> ', uni.getStorageSync('openId'));
  138. } else {
  139. console.error('获取用户信息失败:', res.data);
  140. }
  141. } catch (err) {
  142. console.error('请求失败:', err);
  143. }
  144. }
  145. // 判断当前微信号的openId 是否已经存入到数据库了,如果存入了,那么就直接通过openId匹配登录,否则就进入登录页面
  146. const flag = true;
  147. const localOpenId = uni.getStorageSync('openId');
  148. if (localOpenId) {
  149. try {
  150. // 发起请求获取库中的openId
  151. const [err, res] = await uni.request({
  152. url: BASE_URL + `/system-server/sys/user/allOpenIds`,
  153. method: 'GET'
  154. });
  155. if (res && res.statusCode === 200) {
  156. const data = res.data;
  157. //console.log('allOpenIds:', data);
  158. // 确保 data 是数组
  159. if (Array.isArray(data) && data.includes(localOpenId)) {
  160. // 包含的话,则直接根据 openId来实现登录
  161. //console.log(`data 包含 openId: ${localOpenId}`);
  162. const [err, res] = await uni.request({
  163. url: BASE_URL + `/auth-server/user/sys/wxLogin`,
  164. method: 'POST',
  165. data: { openId: localOpenId },
  166. header: {
  167. 'domain': 'ydddl'
  168. }
  169. });
  170. if (res && res.statusCode === 200) {
  171. this.$store.commit('SET_TOKEN', res.data.token);
  172. await this.refreshUserInfo();
  173. uni.reLaunch({
  174. url: '../index/index',
  175. });
  176. }
  177. }
  178. }
  179. } catch (err) {
  180. console.error('请求失败:', err);
  181. }
  182. }
  183. if (flag) {
  184. console.log('进来了');
  185. }
  186. // 获取 URL 中的 'flow' 参数
  187. const flowParam = this.$route.query.flow;
  188. // 将 URL 编码的 'flow' 参数解析为 JSON 对象
  189. if (!flowParam) {
  190. return;
  191. }
  192. const flowObject = JSON.parse(decodeURIComponent(flowParam));
  193. //console.log("flowObject.openId---> ", flowObject.openId)
  194. if (flowObject.openId) {
  195. const [err, res] = await uni.request({
  196. url: BASE_URL + `/auth-server/user/sys/wxLogin`,
  197. method: 'POST',
  198. data: { openId: flowObject.openId },
  199. header: {
  200. 'domain': 'ydddl'
  201. }
  202. });
  203. if (res && res.statusCode === 200) {
  204. this.$store.commit('SET_TOKEN', res.data.token);
  205. await this.refreshUserInfo();
  206. }
  207. }
  208. },
  209. methods: {
  210. ...mapActions(['refreshUserInfo']),
  211. getUrlParams() {
  212. const params = new URLSearchParams(window.location.search || '');
  213. const hash = window.location.hash || '';
  214. const hashQueryIndex = hash.indexOf('?');
  215. if (hashQueryIndex > -1) {
  216. const hashParams = new URLSearchParams(hash.substring(hashQueryIndex + 1));
  217. hashParams.forEach((value, key) => {
  218. if (!params.has(key)) {
  219. params.set(key, value);
  220. }
  221. });
  222. }
  223. return params;
  224. },
  225. isDingTalkEnv() {
  226. return /DingTalk/i.test(window.navigator.userAgent || '');
  227. },
  228. loadDingTalkJs() {
  229. return Promise.resolve(dd);
  230. },
  231. requestDingTalkAuthCode(corpId) {
  232. return new Promise((resolve, reject) => {
  233. // 节点1:进入方法
  234. //console.log('1. 进入获取钉钉授权码函数,corpId:' + corpId);
  235. // 节点2:判断dd是否存在
  236. if (!dd) {
  237. const errMsg = '钉钉资源未加载成功,请联系管理员';
  238. //console.log('2. 异常:' + errMsg);
  239. reject(new Error(errMsg));
  240. return;
  241. }
  242. //console.log('2. dd对象存在,准备调用getAuthCode');
  243. let hasCallbackTriggered = false;
  244. dd.getAuthCode({
  245. corpId: corpId,
  246. onSuccess: (res) => {
  247. if (hasCallbackTriggered) return;
  248. hasCallbackTriggered = true;
  249. //console.log('3. getAuthCode成功,返回数据:' + JSON.stringify(res));
  250. const code = res.code || res.authCode;
  251. //console.log('4. 提取授权码=' + code);
  252. resolve(code);
  253. },
  254. onFail: (err) => {
  255. if (hasCallbackTriggered) return;
  256. hasCallbackTriggered = true;
  257. //console.log('3. getAuthCode失败,错误信息:' + JSON.stringify(err));
  258. reject(err);
  259. }
  260. });
  261. // 钉钉全局异常监听
  262. dd.error((err) => {
  263. if (hasCallbackTriggered) return;
  264. hasCallbackTriggered = true;
  265. //console.log('5. 钉钉全局捕获异常:' + JSON.stringify(err));
  266. reject(err);
  267. });
  268. });
  269. },
  270. async handleDingTalkLoginSuccess(data) {
  271. this.$store.commit('SET_TOKEN', data.token);
  272. await this.refreshUserInfo();
  273. },
  274. async tryDingTalkAutoLogin(urlParams) {
  275. //console.log('[钉钉自动登录] 1、进入 tryDingTalkAutoLogin 函数');
  276. const isDingEnv = this.isDingTalkEnv();
  277. //console.log('[钉钉自动登录] 2、钉钉环境检测结果:', isDingEnv);
  278. if (!isDingEnv) {
  279. //console.log('[钉钉自动登录] 分支:非钉钉环境,return false,流程终止');
  280. return false;
  281. }
  282. const existToken = !!this.$store.state.user.token;
  283. //console.log('[钉钉自动登录] 3、当前是否存在token:', existToken);
  284. if (this.$store.state.user.token) {
  285. //console.log('[钉钉自动登录] 分支:已有token,自动跳转首页');
  286. // 已有登录态,直接跳首页,解决你不跳转的问题
  287. setTimeout(() => {
  288. uni.reLaunch({
  289. url: '/pages/index/index'
  290. });
  291. }, 200);
  292. return true;
  293. }
  294. //console.log('[钉钉自动登录] 4、无token,继续往下执行免登逻辑');
  295. const tenantId = urlParams.get('tenantId') || uni.getStorageSync('dingTalkTenantId') || '10009';
  296. //console.log('[钉钉自动登录] 5、解析得到tenantId:', tenantId);
  297. try {
  298. //console.log('[钉钉自动登录] 6、开始请求后端 dingTalkClientConfig 获取corpId配置');
  299. const clientConfig = await loginService.dingTalkClientConfig(tenantId);
  300. //console.log('[钉钉自动登录] 7、后端返回clientConfig:', clientConfig);
  301. if (!clientConfig || !clientConfig.corpId) {
  302. //console.log('[钉钉自动登录] 分支:clientConfig为空 或 corpId不存在,抛出异常');
  303. throw new Error('DingTalk corpId is missing');
  304. }
  305. //console.log('[钉钉自动登录] 8、拿到有效corpId:', clientConfig.corpId);
  306. //console.log('[钉钉自动登录] 9、即将执行 loadDingTalkJs 校验钉钉SDK是否加载');
  307. await this.loadDingTalkJs();
  308. //console.log('[钉钉自动登录] 10、loadDingTalkJs执行完成,准备调用 requestDingTalkAuthCode');
  309. //console.log('>>>>>>>>>> 即将进入 requestDingTalkAuthCode 方法 <<<<<<<<<<');
  310. const authCode = await this.requestDingTalkAuthCode(clientConfig.corpId);
  311. //console.log('[钉钉自动登录] 11、requestDingTalkAuthCode执行完成,获取到authCode:', authCode);
  312. //console.log('[钉钉自动登录] 12、调用后端钉钉登录接口 dingTalkLogin');
  313. const loginResult = await loginService.dingTalkLogin({
  314. authCode: authCode,
  315. tenantId: tenantId
  316. });
  317. //console.log('[钉钉自动登录] 13、登录接口返回结果:', loginResult);
  318. if (loginResult.bindRequired) {
  319. //console.log('[钉钉自动登录] 分支:需要账号绑定,跳转绑定页面');
  320. uni.setStorageSync('dingTalkBindKey', loginResult.bindKey);
  321. uni.setStorageSync('dingTalkTenantId', loginResult.tenantId || tenantId);
  322. uni.reLaunch({
  323. url: '/pages/login/login?bind=dingtalk'
  324. });
  325. return true;
  326. }
  327. //console.log('[钉钉自动登录] 14、登录成功,执行保存用户信息');
  328. await this.handleDingTalkLoginSuccess(loginResult);
  329. //console.log('[钉钉自动登录] 15、跳转首页');
  330. uni.reLaunch({
  331. url: '/pages/index/index'
  332. });
  333. } catch (e) {
  334. console.error('[钉钉自动登录] 捕获异常,流程中断,错误对象:', e);
  335. console.error('[钉钉自动登录] 异常信息message:', e.message);
  336. uni.showToast({
  337. title: JSON.stringify(e),
  338. icon: 'none'
  339. });
  340. }
  341. //console.log('[钉钉自动登录] 函数末尾,return true');
  342. return true;
  343. },
  344. }
  345. }
  346. </script>
  347. <style lang="scss">
  348. /*每个页面公共css */
  349. @import "@/uni_modules/uview-ui/index.scss";
  350. @import "static/css/jeeplus.scss";
  351. /* @import 'jeeplus-flowable/lib/jeeplus-flowable.css'; */
  352. @import "static/css/main.css";
  353. @import "static/css/icon.css";
  354. /*每个页面公共css */
  355. </style>