App.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <template>
  2. <div>
  3. <!-- <div @click="send">send</div>-->
  4. <router-view></router-view>
  5. </div>
  6. </template>
  7. <script>
  8. import { isMini } from '@/utils/common';
  9. // import { crmQueryMemberInfo } from '@/utils/api-crm-member';
  10. // import Ws from '@/utils/websocket';
  11. import SockJS from '@/utils/sockjs';
  12. import Stomp from '@/lib/stompjs/index';
  13. // import uni from '@/utils/uniHooks';
  14. import { Encrypt, Decrypt } from '@/utils/crypto';
  15. import CacheTool from '@/utils/cache-tool';
  16. import uni from '@/utils/uniHooks';
  17. import { mapState } from 'vuex';
  18. import { initWxJsSdkConfig } from '@/utils/login.js';
  19. import { getUrlParams, getPlatform } from '@/utils/index.js';
  20. import KipCacheTool from '@/utils/kip-cache-tool.js';
  21. import {
  22. kipCheckToken,
  23. kipGetNewAccessTokenByRefreshToken,
  24. } from '@/utils/api-kip.js';
  25. import { KIP_API_CODE } from '@/common/js/config';
  26. // import qs from 'qs';
  27. export default {
  28. data() {
  29. return {
  30. ws: null,
  31. msg: '',
  32. isInit: false,
  33. stompClient: null,
  34. host: 'https://dev-crm-kpl.kerryprops.com.cn/xcrm-api',
  35. token: '1234',
  36. };
  37. },
  38. created() {
  39. this.init();
  40. },
  41. mounted() {
  42. // if(!this.isInit) {
  43. // this.init();
  44. // }
  45. },
  46. computed: {
  47. disabledBtn() {
  48. return this.numArr.findIndex((val) => !val) !== -1;
  49. },
  50. ...mapState({
  51. groupId: (state) => state.groupId,
  52. openid: (state) => state.openid,
  53. mallId: (state) => state.mallId,
  54. kipUserId: (state) => state.kipUserId,
  55. userInfo: (state) => state.userInfo,
  56. }),
  57. },
  58. methods: {
  59. toLogin() {
  60. let query = getUrlParams();
  61. // 本地
  62. // store
  63. // url 参数
  64. // const query = {
  65. // groupId: mallid,
  66. // };
  67. this.$router.replace({
  68. path: '/login',
  69. query: query,
  70. });
  71. },
  72. async init() {
  73. // 初始化环境变量
  74. CacheTool.init();
  75. if (this.isInit) return;
  76. this.isInit = false;
  77. const kipAccessToken = uni.getStorageSync('kipAccessToken');
  78. const query = getUrlParams();
  79. // console.log('h5登录时的参数', query);
  80. const platform = getPlatform();
  81. if (
  82. (query.groupId && query.groupId !== 'undefined') ||
  83. uni.getStorageSync('mallId')
  84. ) {
  85. this.$store.commit(
  86. 'SET_GROUP_ID',
  87. query?.groupId || uni.getStorageSync('groupId')
  88. );
  89. }
  90. if (
  91. (query.mallId && query.mallId !== 'undefined') ||
  92. uni.getStorageSync('mallId')
  93. ) {
  94. this.$store.commit(
  95. 'SET_MALL_ID',
  96. query?.mallId?.replace('#/', '') || uni.getStorageSync('mallId')
  97. );
  98. }
  99. if (uni.getStorageSync('member')) {
  100. this.$store.dispatch('getUserDetail');
  101. this.$store.commit('SET_USER_INFO', uni.getStorageSync('member'));
  102. this.$store.commit('SET_MEMBER', uni.getStorageSync('member'));
  103. }
  104. // 如果是微信小程序入口,先把 传过来的 token 和 pageId 保存下来
  105. if (platform === 'miniprogram' && !uni.getStorageSync('pageId')) {
  106. const { pageId, token } = query;
  107. uni.setStorageSync('pageId', pageId);
  108. uni.setStorageSync('token', token);
  109. }
  110. // 如果用户没有openid
  111. const openid = uni.getStorageSync('openid');
  112. // console.log(949494, openid);
  113. // 设置openid
  114. if (openid && openid !== 'undefined') {
  115. this.$store.commit('SET_OPENID', openid);
  116. }
  117. if (!openid) {
  118. // 当进入其他页面时,需要先打开路由展示
  119. this.isInit = true;
  120. // 前往授权页面
  121. this.$router.replace({
  122. path: '/openWx',
  123. query: query,
  124. });
  125. return;
  126. }
  127. // 当前页面是否是在微信公众号运行:start
  128. // 微信公众号环境 start
  129. if (platform === 'micromessenger') {
  130. // 如果用户没有登录的话,我们需要让用户完成授权拿到 openid
  131. /* const openid = uni.getStorageSync('openid');
  132. // console.log(949494, openid);
  133. // 设置openid
  134. if (openid && openid !== 'undefined') {
  135. this.$store.commit('SET_OPENID', openid);
  136. } */
  137. if (!openid) {
  138. // 当进入其他页面时,需要先打开路由展示
  139. this.isInit = true;
  140. // 前往授权页面
  141. this.$router.replace({
  142. path: '/openWx',
  143. query: query,
  144. });
  145. return;
  146. }
  147. if (!kipAccessToken) {
  148. /* if (!openid) {
  149. // 当进入其他页面时,需要先打开路由展示
  150. this.isInit = true;
  151. // 前往授权页面
  152. this.$router.replace({
  153. path: '/openWx',
  154. query: query,
  155. });
  156. return;
  157. } */
  158. // 初始化微信
  159. initWxJsSdkConfig(['chooseWXPay', 'scanQRCode', 'checkJsApi']);
  160. // 如果用户不选择登录,则不走登录逻辑
  161. this.isInit = true;
  162. this.$router.replace({
  163. path: '/login',
  164. query: query,
  165. });
  166. return;
  167. }
  168. // 如果用已经登录
  169. // 验证 kipAccessToken 是否过期,过期则刷新
  170. kipCheckToken(kipAccessToken)
  171. .then((resp) => {
  172. // console.log(120, resp);
  173. if (resp && resp.statusCode == '401') {
  174. log.info(
  175. `access_token已过期,使用refresh_token刷新access_token,如果refresh_token过期则删除所有数据`
  176. );
  177. // token过期之后使用refresh_token刷新access_token,如果refresh_token过期则删除所有数据
  178. const kipRefreshToken = KipCacheTool.getKipRefreshToken();
  179. kipGetNewAccessTokenByRefreshToken(kipRefreshToken)
  180. .then((result) => {
  181. // const result = resp.data;
  182. if (
  183. result &&
  184. result.code === '000000' &&
  185. result.data.access_token
  186. ) {
  187. KipCacheTool.setKipToken(result.data.access_token);
  188. log.info(
  189. `refreshToken获取成功,这是新的token:`,
  190. result.data.access_token
  191. );
  192. } else {
  193. if (
  194. result &&
  195. result.code !== KIP_API_CODE.REFRESH_TOKEN_EXPIRED
  196. ) {
  197. uni.showToast({
  198. title: result.message,
  199. duration: 2000,
  200. icon: 'none',
  201. });
  202. }
  203. console.warn('===>清除所有缓存1');
  204. log.info(`清除所有缓存1`);
  205. _this.cleanAll();
  206. this.$router.replace({
  207. path: '/login',
  208. query: query,
  209. });
  210. }
  211. })
  212. .catch((err) => {
  213. console.warn('===>清除所有缓存2');
  214. log.info(`清除所有缓存2`);
  215. _this.cleanAll();
  216. this.$router.replace({
  217. path: '/login',
  218. query: query,
  219. });
  220. });
  221. }
  222. })
  223. .catch((err) => {
  224. console.error(err);
  225. console.warn('===>清除所有缓存3');
  226. log.info(`refresh_token获取失败,清除所有缓存3`, err);
  227. // _this.cleanAll();
  228. });
  229. this.$router.replace({
  230. path: '/home',
  231. query: query,
  232. });
  233. this.isInit = true;
  234. return;
  235. }
  236. // 当前页面是否是在微信公众号运行:end
  237. // 当判断缓存中存在 pageId, token,并且地址栏中不存在 pageId, token。我们需要刷新页面,确保用户在微信小程序和H5公众号中使用的 open ID 保存一致
  238. if (
  239. uni.getStorageSync('pageId') &&
  240. uni.getStorageSync('pageId') !== 'undefined' &&
  241. uni.getStorageSync('token') &&
  242. (!query?.pageId || !query.token)
  243. ) {
  244. this.$router.replace({
  245. path: '/home',
  246. query: {
  247. pageId: uni.getStorageSync('pageId'),
  248. token: uni.getStorageSync('token'),
  249. },
  250. });
  251. return;
  252. }
  253. /* 微信小程序 webview 配置 */
  254. console.log(258, uni.getStorageSync('pageId'));
  255. if (
  256. !uni.getStorageSync('pageId') ||
  257. uni.getStorageSync('pageId') === 'undefined'
  258. ) {
  259. return;
  260. }
  261. window.token = query?.token || uni.getStorageSync('token');
  262. // this.getTicket()
  263. this.wss(() => {
  264. this.$store.dispatch('baseInit', {
  265. // pageId: window.location.href.replace(/.*pageId=([0-9A-Z]*).*/g, '$1'),
  266. pageId: query?.pageId || uni.getStorageSync('pageId'),
  267. // callback: this.wss,
  268. callback: () => {
  269. // console.log(838383, this.isInit);
  270. this.isInit = true;
  271. // if (!openid) {
  272. // this.$router.replace({
  273. // path: '/openWx',
  274. // query: query,
  275. // });
  276. // return
  277. // }
  278. // 当所有的数据都初始化之后再次执行
  279. this.getTicket();
  280. },
  281. });
  282. });
  283. },
  284. send() {
  285. window.stompClient.send(
  286. '/sendToWechat',
  287. {},
  288. JSON.stringify({
  289. token: window.token,
  290. data: Encrypt(
  291. JSON.stringify({
  292. type: 'openWxPay',
  293. options: {},
  294. })
  295. ),
  296. })
  297. );
  298. },
  299. wss(callback) {
  300. try {
  301. console.log(
  302. 107107,
  303. this.host + '/hafengWebsocket' + '?token=' + window.token
  304. );
  305. const socket = new SockJS(
  306. this.host + '/hafengWebsocket' + '?token=' + window.token
  307. );
  308. window.stompClient = Stomp.over(socket);
  309. window.stompClient.debug = null;
  310. const self = this;
  311. this.windowSendInit();
  312. window.stompClient.connect({}, (frame) => {
  313. callback && callback();
  314. window.subscribe('projectId', (options) => {
  315. self.$store.commit('SET_PROJECT_ID', options.projectId);
  316. self.$store.commit('SET_ACCESS_TOKEN', options.accessToken);
  317. });
  318. });
  319. } catch (err) {
  320. console.log(err);
  321. callback && callback();
  322. }
  323. },
  324. disconnect() {
  325. if (window.stompClient != null) {
  326. window.stompClient.disconnect();
  327. }
  328. },
  329. windowSendInit() {
  330. // uni.showToast({title: '哈哈哈哈'})
  331. // return
  332. window.toWXSendMsg = function ({
  333. type = '',
  334. funcName = '',
  335. options = {},
  336. }) {
  337. /**
  338. * 向小程序端发送消息
  339. */
  340. if (!type) return;
  341. console.log(259, '微信支付的options', options);
  342. window.stompClient.send(
  343. '/sendToWechat',
  344. {},
  345. JSON.stringify({
  346. token: window.token,
  347. data: Encrypt(
  348. JSON.stringify({
  349. type: type,
  350. funcName,
  351. options,
  352. })
  353. ),
  354. })
  355. );
  356. };
  357. // 主动订阅事件回调
  358. window.subscribe = function (type, callback) {
  359. const subscribeId = window.stompClient.subscribe(
  360. '/user/' + window.token + '/toH5',
  361. function (response) {
  362. try {
  363. let res = {
  364. token: '', // 微信小程序端 页面的传递过来的token
  365. data: '', // 微信小程序端 页面的传递过来的信息(已加密)
  366. };
  367. if (response.body) {
  368. res = JSON.parse(response.body);
  369. }
  370. // 检查 微信小程序端 发送过来的信息和token是否与当前页面的 token一致。并且 res.data 携带信息,在解密之后是 json 格式
  371. if (res.token && res.token === self.token && res.data) {
  372. const msgJson = JSON.parse(Decrypt(res.data));
  373. const reg = new RegExp(type);
  374. // 获取 projectId
  375. if (reg.test(msgJson.type)) {
  376. callback(msgJson.options, subscribeId);
  377. subscribeId.unsubscribe();
  378. return;
  379. }
  380. }
  381. } catch (err) {
  382. console.log('stomp error', err);
  383. }
  384. }
  385. );
  386. };
  387. },
  388. // 环境变量初始化
  389. envInit() {
  390. const href = `${window.location.href}`;
  391. // dev
  392. if (/8080|dev-/g.test(href)) {
  393. CacheTool.setEnv('qa');
  394. return;
  395. }
  396. // qa
  397. if (/qa-/g.test(href)) {
  398. CacheTool.setEnv('dev');
  399. return;
  400. }
  401. // prod
  402. CacheTool.setEnv('prod');
  403. },
  404. // h5获取配置---公众号支付
  405. getTicket() {
  406. console.log(173);
  407. let self = this;
  408. var datas = {
  409. groupId: this.groupId,
  410. mallid: this.mallId,
  411. url: window.location.href.split('#')[0],
  412. };
  413. self.$md(datas);
  414. console.log(199, datas);
  415. uni.request({
  416. // url: self.$baseURL + "api/1.0/login/getTicket",
  417. // url: 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api/' + "api/1.0/login/getTicket",
  418. method: 'POST',
  419. data: datas,
  420. header: JSON.parse(uni.getStorageSync('handleUser')),
  421. success: (res) => {
  422. console.log(206, res);
  423. if (res.data.code == 0) {
  424. self.$wx.config({
  425. debug: false, // 开启调试模式
  426. appId: res.data.data.appId, // 必填,公众号的唯一标识
  427. timestamp: res.data.data.timestamp, // 必填,生成签名的时间戳
  428. nonceStr: res.data.data.nonceStr, // 必填,生成签名的随机串
  429. signature: res.data.data.signature, // 必填,签名
  430. jsApiList: ['chooseWXPay', 'scanQRCode', 'checkJsApi'], // 必填,需要使用的JS接口列表
  431. });
  432. self.$wx.ready(function () {
  433. self.$wx.checkJsApi({
  434. jsApiList: ['chooseWXPay'],
  435. success: (res) => {
  436. console.log('checked api:', res);
  437. },
  438. fail: (err) => {
  439. console.log('check api fail:', err);
  440. },
  441. });
  442. });
  443. self.$wx.error(function (res) {
  444. console.log('err', res);
  445. });
  446. } else {
  447. uni.showToast({
  448. title: res.data.msg,
  449. duration: 2000,
  450. icon: 'none',
  451. });
  452. }
  453. },
  454. });
  455. },
  456. h5init() {
  457. if (uni.getStorageSync('groupId')) {
  458. this.$store.commit('SET_GROUP_ID', uni.getStorageSync('groupId'));
  459. }
  460. if (uni.getStorageSync('kipUserId')) {
  461. this.$store.commit('SET_KIP_USER_ID', uni.getStorageSync('kipUserId'));
  462. }
  463. if (uni.getStorageSync('mallId')) {
  464. this.$store.commit('SET_MALL_ID', uni.getStorageSync('mallId'));
  465. }
  466. if (uni.getStorageSync('openid')) {
  467. this.$store.commit('SET_OPENID', uni.getStorageSync('openid'));
  468. }
  469. if (uni.getStorageSync('mobile')) {
  470. this.$store.commit('SET_OPENID', uni.getStorageSync('mobile'));
  471. }
  472. },
  473. },
  474. };
  475. </script>
  476. <style>
  477. page {
  478. display: flex;
  479. flex-direction: column;
  480. height: 100%;
  481. }
  482. body {
  483. padding: 0;
  484. margin: 0;
  485. }
  486. </style>