App.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. // 如果用户没有openid
  91. const openid = uni.getStorageSync('openid');
  92. // console.log(949494, openid);
  93. // 设置openid
  94. if (openid && openid !== 'undefined') {
  95. this.$store.commit('SET_OPENID', openid);
  96. }
  97. if (!openid) {
  98. // 当进入其他页面时,需要先打开路由展示
  99. this.isInit = true;
  100. // 前往授权页面
  101. this.$router.replace({
  102. path: '/openWx',
  103. query: query,
  104. });
  105. return;
  106. }
  107. // console.log(85, platform);
  108. if (
  109. (query.mallId && query.mallId !== 'undefined') ||
  110. uni.getStorageSync('mallId')
  111. ) {
  112. this.$store.commit(
  113. 'SET_MALL_ID',
  114. query?.mallId?.replace('#/', '') || uni.getStorageSync('mallId')
  115. );
  116. }
  117. if (uni.getStorageSync('member')) {
  118. this.$store.dispatch('getUserDetail');
  119. this.$store.commit('SET_USER_INFO', uni.getStorageSync('member'));
  120. this.$store.commit('SET_MEMBER', uni.getStorageSync('member'));
  121. }
  122. // 当前页面是否是在微信公众号运行:start
  123. // 微信公众号环境 start
  124. if (platform === 'micromessenger') {
  125. // 如果用户没有登录的话,我们需要让用户完成授权拿到 openid
  126. /* const openid = uni.getStorageSync('openid');
  127. // console.log(949494, openid);
  128. // 设置openid
  129. if (openid && openid !== 'undefined') {
  130. this.$store.commit('SET_OPENID', openid);
  131. } */
  132. if (!kipAccessToken) {
  133. /* if (!openid) {
  134. // 当进入其他页面时,需要先打开路由展示
  135. this.isInit = true;
  136. // 前往授权页面
  137. this.$router.replace({
  138. path: '/openWx',
  139. query: query,
  140. });
  141. return;
  142. } */
  143. // 初始化微信
  144. initWxJsSdkConfig(['chooseWXPay']);
  145. // 如果用户不选择登录,则不走登录逻辑
  146. this.isInit = true;
  147. this.$router.replace({
  148. path: '/login',
  149. query: query,
  150. });
  151. return;
  152. }
  153. // 如果用已经登录
  154. // 验证 kipAccessToken 是否过期,过期则刷新
  155. kipCheckToken(kipAccessToken)
  156. .then((resp) => {
  157. // console.log(120, resp);
  158. if (resp && resp.statusCode == '401') {
  159. log.info(
  160. `access_token已过期,使用refresh_token刷新access_token,如果refresh_token过期则删除所有数据`
  161. );
  162. // token过期之后使用refresh_token刷新access_token,如果refresh_token过期则删除所有数据
  163. const kipRefreshToken = KipCacheTool.getKipRefreshToken();
  164. kipGetNewAccessTokenByRefreshToken(kipRefreshToken)
  165. .then((result) => {
  166. // const result = resp.data;
  167. if (
  168. result &&
  169. result.code === '000000' &&
  170. result.data.access_token
  171. ) {
  172. KipCacheTool.setKipToken(result.data.access_token);
  173. log.info(
  174. `refreshToken获取成功,这是新的token:`,
  175. result.data.access_token
  176. );
  177. } else {
  178. if (
  179. result &&
  180. result.code !== KIP_API_CODE.REFRESH_TOKEN_EXPIRED
  181. ) {
  182. uni.showToast({
  183. title: result.message,
  184. duration: 2000,
  185. icon: 'none',
  186. });
  187. }
  188. console.warn('===>清除所有缓存1');
  189. log.info(`清除所有缓存1`);
  190. _this.cleanAll();
  191. this.$router.replace({
  192. path: '/login',
  193. query: query,
  194. });
  195. }
  196. })
  197. .catch((err) => {
  198. console.warn('===>清除所有缓存2');
  199. log.info(`清除所有缓存2`);
  200. _this.cleanAll();
  201. this.$router.replace({
  202. path: '/login',
  203. query: query,
  204. });
  205. });
  206. }
  207. })
  208. .catch((err) => {
  209. console.error(err);
  210. console.warn('===>清除所有缓存3');
  211. log.info(`refresh_token获取失败,清除所有缓存3`, err);
  212. // _this.cleanAll();
  213. });
  214. this.$router.replace({
  215. path: '/home',
  216. query: query,
  217. });
  218. this.isInit = true;
  219. return;
  220. }
  221. // 当前页面是否是在微信公众号运行:end
  222. /* 微信小程序 webview 配置 */
  223. if (!query?.pageId?.length || !query?.token?.length) {
  224. return;
  225. }
  226. window.token = query?.token;
  227. // this.getTicket()
  228. this.wss(() => {
  229. this.$store.dispatch('baseInit', {
  230. pageId: window.location.href.replace(/.*pageId=([0-9A-Z]*).*/g, '$1'),
  231. // callback: this.wss,
  232. callback: () => {
  233. console.log(838383, this.isInit);
  234. this.isInit = true;
  235. // 当所有的数据都初始化之后再次执行
  236. this.getTicket();
  237. },
  238. });
  239. });
  240. },
  241. send() {
  242. window.stompClient.send(
  243. '/sendToWechat',
  244. {},
  245. JSON.stringify({
  246. token: window.token,
  247. data: Encrypt(
  248. JSON.stringify({
  249. type: 'openWxPay',
  250. options: {},
  251. })
  252. ),
  253. })
  254. );
  255. },
  256. wss(callback) {
  257. try {
  258. console.log(
  259. 107107,
  260. this.host + '/hafengWebsocket' + '?token=' + window.token
  261. );
  262. const socket = new SockJS(
  263. this.host + '/hafengWebsocket' + '?token=' + window.token
  264. );
  265. window.stompClient = Stomp.over(socket);
  266. window.stompClient.debug = null;
  267. const self = this;
  268. this.windowSendInit();
  269. window.stompClient.connect({}, (frame) => {
  270. callback && callback();
  271. window.subscribe('projectId', (options) => {
  272. self.$store.commit('SET_PROJECT_ID', options.projectId);
  273. self.$store.commit('SET_ACCESS_TOKEN', options.accessToken);
  274. });
  275. });
  276. } catch (err) {
  277. console.log(err);
  278. callback && callback();
  279. }
  280. },
  281. disconnect() {
  282. if (window.stompClient != null) {
  283. window.stompClient.disconnect();
  284. }
  285. },
  286. windowSendInit() {
  287. // uni.showToast({title: '哈哈哈哈'})
  288. // return
  289. window.toWXSendMsg = function ({
  290. type = '',
  291. funcName = '',
  292. options = {},
  293. }) {
  294. /**
  295. * 向小程序端发送消息
  296. */
  297. if (!type) return;
  298. console.log(259, '微信支付的options', options);
  299. window.stompClient.send(
  300. '/sendToWechat',
  301. {},
  302. JSON.stringify({
  303. token: window.token,
  304. data: Encrypt(
  305. JSON.stringify({
  306. type: type,
  307. funcName,
  308. options,
  309. })
  310. ),
  311. })
  312. );
  313. };
  314. // 主动订阅事件回调
  315. window.subscribe = function (type, callback) {
  316. const subscribeId = window.stompClient.subscribe(
  317. '/user/' + window.token + '/toH5',
  318. function (response) {
  319. try {
  320. let res = {
  321. token: '', // 微信小程序端 页面的传递过来的token
  322. data: '', // 微信小程序端 页面的传递过来的信息(已加密)
  323. };
  324. if (response.body) {
  325. res = JSON.parse(response.body);
  326. }
  327. // 检查 微信小程序端 发送过来的信息和token是否与当前页面的 token一致。并且 res.data 携带信息,在解密之后是 json 格式
  328. if (res.token && res.token === self.token && res.data) {
  329. const msgJson = JSON.parse(Decrypt(res.data));
  330. const reg = new RegExp(type);
  331. // 获取 projectId
  332. if (reg.test(msgJson.type)) {
  333. callback(msgJson.options, subscribeId);
  334. subscribeId.unsubscribe();
  335. return;
  336. }
  337. }
  338. } catch (err) {
  339. console.log('stomp error', err);
  340. }
  341. }
  342. );
  343. };
  344. },
  345. // 环境变量初始化
  346. envInit() {
  347. const href = `${window.location.href}`;
  348. // dev
  349. if (/8080|dev-/g.test(href)) {
  350. CacheTool.setEnv('qa');
  351. return;
  352. }
  353. // qa
  354. if (/qa-/g.test(href)) {
  355. CacheTool.setEnv('dev');
  356. return;
  357. }
  358. // prod
  359. CacheTool.setEnv('prod');
  360. },
  361. // h5获取配置---公众号支付
  362. getTicket() {
  363. console.log(173);
  364. let self = this;
  365. var datas = {
  366. groupId: this.groupId,
  367. mallid: this.mallId,
  368. url: window.location.href.split('#')[0],
  369. };
  370. self.$md(datas);
  371. console.log(199, datas);
  372. uni.request({
  373. // url: self.$baseURL + "api/1.0/login/getTicket",
  374. // url: 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api/' + "api/1.0/login/getTicket",
  375. method: 'POST',
  376. data: datas,
  377. header: JSON.parse(uni.getStorageSync('handleUser')),
  378. success: (res) => {
  379. console.log(206, res);
  380. if (res.data.code == 0) {
  381. self.$wx.config({
  382. debug: false, // 开启调试模式
  383. appId: res.data.data.appId, // 必填,公众号的唯一标识
  384. timestamp: res.data.data.timestamp, // 必填,生成签名的时间戳
  385. nonceStr: res.data.data.nonceStr, // 必填,生成签名的随机串
  386. signature: res.data.data.signature, // 必填,签名
  387. jsApiList: ['chooseWXPay'], // 必填,需要使用的JS接口列表
  388. });
  389. self.$wx.ready(function () {
  390. self.$wx.checkJsApi({
  391. jsApiList: ['chooseWXPay'],
  392. success: (res) => {
  393. console.log('checked api:', res);
  394. },
  395. fail: (err) => {
  396. console.log('check api fail:', err);
  397. },
  398. });
  399. });
  400. self.$wx.error(function (res) {
  401. console.log('err', res);
  402. });
  403. } else {
  404. uni.showToast({
  405. title: res.data.msg,
  406. duration: 2000,
  407. icon: 'none',
  408. });
  409. }
  410. },
  411. });
  412. },
  413. h5init() {
  414. if (uni.getStorageSync('groupId')) {
  415. this.$store.commit('SET_GROUP_ID', uni.getStorageSync('groupId'));
  416. }
  417. if (uni.getStorageSync('kipUserId')) {
  418. this.$store.commit('SET_KIP_USER_ID', uni.getStorageSync('kipUserId'));
  419. }
  420. if (uni.getStorageSync('mallId')) {
  421. this.$store.commit('SET_MALL_ID', uni.getStorageSync('mallId'));
  422. }
  423. if (uni.getStorageSync('openid')) {
  424. this.$store.commit('SET_OPENID', uni.getStorageSync('openid'));
  425. }
  426. if (uni.getStorageSync('mobile')) {
  427. this.$store.commit('SET_OPENID', uni.getStorageSync('mobile'));
  428. }
  429. },
  430. },
  431. };
  432. </script>
  433. <style>
  434. page {
  435. display: flex;
  436. flex-direction: column;
  437. height: 100%;
  438. }
  439. body {
  440. padding: 0;
  441. margin: 0;
  442. }
  443. </style>