App.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <script>
  2. import Vue from 'vue'
  3. import api from 'utils/api'
  4. import util from 'utils/util'
  5. import __config from 'config/env';
  6. //import JMessage from 'public/jmessage-wxapplet-sdk/jmessage-wxapplet-sdk-1.4.0.min.js'
  7. // #ifdef APP-PLUS
  8. import APPUpdate from "@/public/APPUpdate/index.js"; //App版本更新
  9. // #endif
  10. export default {
  11. globalData: {
  12. urlTitle:'',
  13. showPrivacy: false,
  14. isIPad: false,
  15. isIos: false,
  16. isAndroid: false,
  17. systemInfo: {},
  18. shoppingCartCount: 0, //购物车数量
  19. tenantId: null, //租户Id
  20. appId: null, //公众号appId
  21. componentAppId: null, //第三方平台appid
  22. isEnableSwitchToken: false, //是否开启SwitchToken
  23. theme: { //主题定义
  24. backgroundColor: null, //背景颜色,支持渐变色
  25. themeColor: null, //主题颜色
  26. tabbarBackgroundColor: null, //tabbar背景颜色
  27. tabbarColor: null, //tabBar上的文字默认颜色
  28. tabbarSelectedColor: null, //tabBar上的文字选中时的颜色
  29. tabbarBorderStyle: null, //tabBar上边框的颜色
  30. tabbarItem: [] //tabBar明细设置
  31. },
  32. logining: false, //登录loading
  33. },
  34. onLaunch: async function() {
  35. // 微信授权验证
  36. // if (uni.getPrivacySetting) {
  37. // uni.getPrivacySetting({
  38. // success: res => {
  39. // console.log("是否需要授权:", res.needAuthorization, "隐私协议的名称为:", res.privacyContractName)
  40. // if (res.needAuthorization) {
  41. // getApp().globalData.urlTitle = res.privacyContractName
  42. // getApp().globalData.showPrivacy = true;
  43. // } else {
  44. // getApp().globalData.showPrivacy = false;
  45. // }
  46. // },
  47. // fail: () => {
  48. // },
  49. // complete: () => {},
  50. // })
  51. // };
  52. const Decimal = require('decimal.js');
  53. // #ifdef MP
  54. //小程序平台检测新版本
  55. this.updateManager();
  56. //this.doLogin();
  57. // #endif
  58. // 原生app版本更新检测
  59. // #ifdef APP-PLUS
  60. APPUpdate();
  61. // const ToastPlusModule = uni.requireNativePlugin("unitest")
  62. // ToastPlusModule.init();
  63. // #endif
  64. //隐藏原生tabbar
  65. uni.hideTabBar()
  66. // #ifdef H5
  67. // H5平台获取参数中的租户ID、公众号appID,并存入globalData
  68. let local = location.href
  69. let tenantId = util.getUrlParam(local, "tenant_id");
  70. let appId = util.getUrlParam(local, "app_id");
  71. let componentAppId = util.getUrlParam(local, "component_appid");
  72. this.globalData.tenantId = tenantId;
  73. this.globalData.appId = appId;
  74. this.globalData.componentAppId = componentAppId;
  75. // #endif
  76. // #ifdef APP-PLUS
  77. // APP平台需要从配置文件中获取租户ID
  78. let tenantId = __config.tenantId;
  79. this.globalData.tenantId = tenantId;
  80. // #endif
  81. //设置全局样式
  82. this.setGlobalStyle();
  83. if (uni.getStorageSync('wx_token_value')) {}
  84. // 上报设备信息
  85. await this.deviceReport();
  86. },
  87. methods: {
  88. // 同步上报设备信息
  89. async deviceReport() {
  90. let info = uni.$u.sys()
  91. this.globalData.systemInfo = info
  92. this.globalData.deviceId = info.deviceId
  93. this.globalData.isIPad = (info.devicePixelRatio != 3 && info.windowWidth > 420)
  94. if (info.system.toLowerCase().indexOf("ios") > -1) {
  95. this.globalData.isIos = true
  96. }
  97. if (info.system.toLowerCase().indexOf("android") > -1) {
  98. this.globalData.isAndroid = true
  99. }
  100. this.$log('device-id: ' + info.deviceId)
  101. console.log('system: ', info.system)
  102. console.log('model: ', info.model)
  103. console.log('设备像素比: ', info.devicePixelRatio)
  104. /* for (let k in info) {
  105. console.log(k + ': ', info[k])
  106. } */
  107. console.log('globalSystemInfo: ', info)
  108. // APP上报设备信息
  109. let res = await api.deviceReport(info)
  110. //TODO 待处理店铺信息
  111. if (res.data.length > 0) {
  112. //店铺ID放入缓存
  113. uni.setStorageSync(__config.shopIdSessionKey, res.data.shopInfos.id)
  114. uni.setStorageSync(__config.shopInfoSessionKey, res.data.shopInfos ? res.data.shopInfos : [])
  115. uni.setStorageSync("tableList", res.data.sendTableDTOS ? res.data.sendTableDTOS : [])
  116. } else {
  117. uni.removeStorageSync(__config.shopIdSessionKey)
  118. uni.removeStorageSync(__config.shopInfoSessionKey)
  119. uni.removeStorageSync("tableList")
  120. }
  121. console.log('^^^^^^^^^^^^^^^^****************^^^^^^^^^^^^^^^^^')
  122. console.log('isIPad: ', this.globalData.isIPad)
  123. console.log('isIos: ', this.globalData.isIos)
  124. console.log('isAndroid: ', this.globalData.isAndroid)
  125. },
  126. //设置全局样式
  127. setGlobalStyle() {
  128. uni.getSystemInfo({
  129. success: function(e) {
  130. // [2020-08-01]更新ColorUI 修复ios 状态栏错位
  131. // #ifndef MP
  132. Vue.prototype.StatusBar = e.statusBarHeight;
  133. if (e.platform == 'android') {
  134. Vue.prototype.CustomBar = e.statusBarHeight + 50;
  135. } else {
  136. Vue.prototype.CustomBar = e.statusBarHeight + 45;
  137. };
  138. // #endif
  139. // #ifdef MP-WEIXIN || MP-QQ
  140. Vue.prototype.StatusBar = e.statusBarHeight;
  141. let capsule = wx.getMenuButtonBoundingClientRect();
  142. if (capsule) {
  143. Vue.prototype.Custom = capsule;
  144. // Vue.prototype.capsuleSafe = uni.upx2px(750) - capsule.left + uni.upx2px(750) - capsule.right;
  145. Vue.prototype.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
  146. } else {
  147. Vue.prototype.CustomBar = e.statusBarHeight + 50;
  148. }
  149. // #endif
  150. // #ifdef MP-ALIPAY
  151. Vue.prototype.StatusBar = e.statusBarHeight;
  152. Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
  153. // #endif
  154. // 处理IPAD头部高度问题
  155. if (e.devicePixelRatio != 3 && e.windowWidth > 420) {
  156. if (e.system.toLowerCase().indexOf("ios") > -1) {
  157. Vue.prototype.CustomBar = Vue.prototype.CustomBar + 20
  158. }
  159. if (e.system.toLowerCase().indexOf("android") > -1) {
  160. Vue.prototype.CustomBar = Vue.prototype.CustomBar
  161. }
  162. }
  163. }
  164. })
  165. //let themeMobile = res.data;
  166. //定义默认配置
  167. let backgroundColor = 'blue';
  168. let themeColor = 'purple';
  169. let tabbarBackgroundColor = '#ffffff';
  170. let tabbarColor = '#666666';
  171. let tabbarSelectedColor = '#f43f3b';
  172. let tabbarBorderStyle = '#black';
  173. let tabbarItem = [{
  174. index: 0,
  175. text: '首页',
  176. iconPath: '/static/public/img/icon-1/1-001.png',
  177. selectedIconPath: '/static/public/img/icon-1/1-002.png'
  178. },
  179. {
  180. index: 1,
  181. text: '分类',
  182. iconPath: '/static/public/img/icon-1/2-001.png',
  183. selectedIconPath: '/static/public/img/icon-1/2-002.png'
  184. },
  185. {
  186. index: 2,
  187. text: '消息',
  188. iconPath: '/static/public/img/icon-1/3-001.png',
  189. selectedIconPath: '/static/public/img/icon-1/3-002.png'
  190. },
  191. {
  192. index: 3,
  193. text: '购物车',
  194. iconPath: '/static/public/img/icon-1/4-001.png',
  195. selectedIconPath: '/static/public/img/icon-1/4-002.png'
  196. },
  197. {
  198. index: 4,
  199. text: '我的',
  200. iconPath: '/static/public/img/icon-1/5-001.png',
  201. selectedIconPath: '/static/public/img/icon-1/5-002.png'
  202. }
  203. ]
  204. //将默认配置换成后台数据
  205. this.globalData.theme.backgroundColor = backgroundColor
  206. this.globalData.theme.themeColor = themeColor
  207. this.globalData.theme.tabbarBackgroundColor = tabbarBackgroundColor
  208. this.globalData.theme.tabbarColor = tabbarColor
  209. this.globalData.theme.tabbarSelectedColor = tabbarSelectedColor
  210. this.globalData.theme.tabbarBorderStyle = tabbarBorderStyle
  211. //this.globalData.theme.tabbarItem = tabbarItem
  212. },
  213. // #ifdef MP
  214. //小程序平台检测新版本
  215. updateManager() {
  216. const updateManager = uni.getUpdateManager();
  217. updateManager.onUpdateReady(function() {
  218. uni.showModal({
  219. title: '更新提示',
  220. content: '新版本已经准备好,是否重启应用?',
  221. success(res) {
  222. if (res.confirm) {
  223. updateManager.applyUpdate();
  224. }
  225. }
  226. });
  227. });
  228. },
  229. // #endif
  230. /**
  231. * 获取用户信息(接口方式)
  232. */
  233. getAccountInfoSync() {
  234. let params = {}
  235. if (this.getAccountId()) {
  236. params['accountId'] = this.getAccountId()
  237. }
  238. return api.getCurrentUserSync(params)
  239. },
  240. /**
  241. * 获取缓存中用户信息(不存在返回undefined)
  242. */
  243. getAccountInfo() {
  244. let userInfo = uni.getStorageSync(__config.loginWxUserInfoKey)
  245. if (userInfo)
  246. return userInfo;
  247. return undefined
  248. },
  249. /**
  250. * 获取缓存中用户Id(无值返回undefined)
  251. */
  252. getAccountId() {
  253. let account = this.getAccountInfo()
  254. return account ? account.accountId : undefined
  255. },
  256. /**
  257. * 获取缓存中用户手机号(无值返回undefined)
  258. */
  259. getAccountMobile() {
  260. let account = this.getAccountInfo()
  261. return account ? account.mobile : undefined
  262. },
  263. /**
  264. * 获取缓存中用户是否授权过微信自身的用户信息(无值返回false)
  265. */
  266. getAccountIsAuth() {
  267. let retFlag = false
  268. let account = this.getAccountInfo()
  269. if (!account)
  270. return retFlag
  271. if (account.headerImg) {
  272. retFlag = true
  273. }
  274. return retFlag
  275. },
  276. //页面初始化方法,供每个页面调用
  277. initPage() {
  278. let that = this;
  279. return new Promise((resolve, reject) => {
  280. //小程序或公众号H5,每个页面都进行登录校验
  281. if (util.isMiniPg() || (that.globalData.appId && util.isWeiXinBrowser())) {
  282. console.info('initPage : ' + __config.tokenValueKey, uni.getStorageSync(__config
  283. .tokenValueKey))
  284. if (!uni.getStorageSync(__config.tokenValueKey)) {
  285. //resolve("success");
  286. //无thirdSession,进行登录
  287. that.doLogin().then(res => {
  288. resolve("success");
  289. });
  290. } else {
  291. if (util.isMiniPg()) { //小程序需要检查登录态是否过期
  292. uni.checkSession({
  293. success() {
  294. //session_key 未过期,并且在本生命周期一直有效
  295. console.log('session_key 未过期')
  296. resolve("success");
  297. },
  298. fail() {
  299. // session_key 已经失效,需要重新执行登录流程
  300. console.log('session_key 已经失效')
  301. debugger
  302. that.doLogin().then(res => {
  303. resolve("success");
  304. });
  305. }
  306. })
  307. } else {
  308. resolve("success");
  309. }
  310. }
  311. } else {
  312. resolve("success");
  313. }
  314. });
  315. },
  316. //登录操作
  317. doLogin() {
  318. uni.showLoading({
  319. title: '登录中'
  320. });
  321. return new Promise((resolve, reject) => {
  322. // #ifdef MP-WEIXIN
  323. //微信小程序登录
  324. this.loginWxMa().then(res => {
  325. resolve("success");
  326. });
  327. // #endif
  328. // #ifdef H5
  329. //微信公众号H5
  330. if (util.isWeiXinBrowser()) {
  331. let local = location.href
  332. let code = util.getUrlParam(local, "code");
  333. let state = util.getUrlParam(local, "state");
  334. //授权code登录
  335. if (code) { //有code
  336. if (state == 'snsapi_base' || state == 'snsapi_userinfo') { //登录授权
  337. this.loginWxMp(code, state).then(res => {
  338. resolve("success");
  339. });
  340. }
  341. } else { //无code则发起网页授权
  342. //微信公众号H5,页面授权登录
  343. let appId = this.globalData.appId;
  344. let pages = getCurrentPages();
  345. let currentPage = pages[pages.length - 1];
  346. let route = currentPage.route;
  347. let redirectUri = location.href;
  348. let componentAppId_str = this.globalData.componentAppId ? '&component_appid=' + this
  349. .globalData.componentAppId : '';
  350. redirectUri = encodeURIComponent(redirectUri);
  351. let wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId +
  352. '&redirect_uri=' + redirectUri + componentAppId_str +
  353. '&response_type=code&scope=snsapi_base&state=snsapi_base#wechat_redirect';
  354. location.href = wx_url;
  355. }
  356. }
  357. // #endif
  358. });
  359. },
  360. //微信小程序登录
  361. // #ifdef MP-WEIXIN
  362. loginWxMa() {
  363. this.globalData.logining = true
  364. let that = this;
  365. return new Promise((allResolve, allReject) => {
  366. Promise.resolve().then(res => {
  367. return new Promise((resolve, reject) => {
  368. uni.login({
  369. success: function(wxRes) {
  370. resolve(wxRes)
  371. }
  372. });
  373. });
  374. // 只有当第一个then返回了promise对象才会接着调用下一个的then方法
  375. }).then((wxRes) => {
  376. return new Promise((resolve, reject) => {
  377. if (wxRes.code) {
  378. let params = {
  379. jsCode: wxRes.code
  380. }
  381. api.doGet(__config.authConfig.apiLoginUrl, params).then(res => {
  382. resolve(res);
  383. })
  384. }
  385. });
  386. }).then((allRes) => {
  387. console.log('用户登录成功返回结果: ', allRes)
  388. uni.hideLoading();
  389. this.globalData.logining = false
  390. let session = allRes.data;
  391. if (session.isLogin) {
  392. uni.setStorageSync(__config.tokenNameKey, session
  393. .tokenName);
  394. uni.setStorageSync(__config.tokenValueKey, session
  395. .tokenValue);
  396. /**
  397. * 缓存用户信息
  398. */
  399. let wxMemberInfo = util.parseUser(session.userInfo)
  400. uni.setStorageSync(__config.loginWxUserInfoKey,
  401. wxMemberInfo)
  402. }
  403. uni.$emit('loginSuccess', that.getAccountInfo())
  404. allResolve("success");
  405. })
  406. });
  407. // return new Promise((resolve, reject) => {
  408. // let that = this;
  409. // this.uniWxLogin().then(wxRes => {
  410. // if (wxRes.code) {
  411. // let params = {
  412. // jsCode: wxRes.code
  413. // }
  414. // debugger
  415. // api.doGet(__config.authConfig.apiLoginUrl, params).then(res => {
  416. // });
  417. // }
  418. // })
  419. // });
  420. },
  421. /**
  422. * 获取微信 login code
  423. */
  424. uniWxLogin() {
  425. return new Promise((resolve, reject) => {
  426. let that = this;
  427. uni.login({
  428. success: function(res) {
  429. resolve(res)
  430. }
  431. });
  432. });
  433. },
  434. // #endif
  435. //公众号登录
  436. // #ifdef H5
  437. loginWxMp(code, state) {
  438. let that = this;
  439. return new Promise((resolve, reject) => {
  440. let that = this
  441. api.loginWxMp({
  442. jsCode: code,
  443. scope: state
  444. }).then(res => {
  445. //公众号h5网页授权时url会产生code、state参数,防止code、state被复制,需自动剔除
  446. let query = that.$Route.query;
  447. delete query.code;
  448. delete query.state;
  449. util.resetPageUrl(query);
  450. let userInfo = res.data;
  451. uni.setStorageSync('third_session', userInfo.thirdSession);
  452. uni.setStorageSync('user_info', userInfo);
  453. //获取购物车数量
  454. that.shoppingCartCount();
  455. resolve("success");
  456. }).catch(res => {
  457. });
  458. });
  459. },
  460. // #endif
  461. }
  462. };
  463. </script>
  464. <style lang="scss">
  465. /* #ifndef APP-PLUS-NVUE */
  466. @import "./app.css";
  467. /* #endif */
  468. @import './public/animate/animate.css';
  469. /* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
  470. @import "@/uni_modules/uview-ui/index.scss";
  471. </style>