app.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //app.js
  2. const { formatUrl, throttle } = require('utils/util.js')
  3. const sys = wx.getSystemInfoSync()
  4. App({
  5. onLaunch: function (options) {
  6. this.globalData.options = options
  7. wx.getSystemInfo({
  8. success: e => {
  9. this.globalData.statusBar = e.statusBarHeight; //状态栏高度
  10. // let custom = wx.getMenuButtonBoundingClientRect();//菜单按钮
  11. // this.globalData.custom = custom;
  12. // this.globalData.customBar = custom.bottom + custom.top - e.statusBarHeight;
  13. //计算得到定义的状态栏高度
  14. }
  15. })
  16. },
  17. onShow: function (options) {
  18. this.globalData.options = options
  19. },
  20. onHide: function (e) {
  21. },
  22. onError: function (e) {
  23. wx.showToast({
  24. title: '程序执行失败',
  25. icon: 'none'
  26. })
  27. },
  28. onPageNotFound: function (res) {
  29. wx.showToast({
  30. title: '没有找到页面',
  31. icon: 'none'
  32. })
  33. },
  34. /**
  35. * 初始化
  36. */
  37. init: function () {
  38. const accessToken = this.getGlobalAttributeValue('accessToken')
  39. const userInfo = this.getGlobalAttributeValue('userInfo')
  40. this.getWxUserInfoSetting((type, res) => {
  41. // if (type != 1 || !userInfo) {
  42. // this.redirectCtl({ url: 'wx_authority' }, 1)
  43. // return
  44. // }
  45. this.globalData.userInfo = userInfo
  46. wx.checkSession({
  47. success: res => {
  48. this.globalData.accessToken = accessToken
  49. this.navigatePermissionsCtl()
  50. },
  51. fail: res => {
  52. this.login()
  53. }
  54. })
  55. })
  56. // this.post('/api/user/checkToken').then(res => {
  57. // if (accessToken) {
  58. // this.globalData.accessToken = accessToken
  59. // }
  60. // if (userInfo) {
  61. // this.globalData.userInfo = userInfo
  62. // } else {
  63. // this.redirectCtl({ url: 'wx_authority' }, 1)
  64. // return
  65. // }
  66. // this.navigatePermissionsCtl()
  67. // }).catch(res => {
  68. // this.login()
  69. // })
  70. },
  71. /**
  72. * 获取微信code
  73. */
  74. getWxloginCode: function (cb) {
  75. wx.login({
  76. success: res => {
  77. if (cb) cb(res.code)
  78. },
  79. fail: res => {
  80. wx.showToast({
  81. title: '获取微信code失败',
  82. icon: 'none'
  83. })
  84. }
  85. })
  86. },
  87. /**
  88. * 获取微信用户信息
  89. */
  90. login: function () {
  91. const { appType } = this.globalData
  92. this.getWxloginCode(code => {
  93. this.post('/api/user/tlogin', { code, appType }).then(this.handleLogin).catch(e => {
  94. if (e.data.code == '888') {
  95. this.redirectCtl({ url: 'wx_authority' }, 1)
  96. }
  97. })
  98. })
  99. },
  100. /**
  101. * 获取登录数据
  102. */
  103. handleLogin: function (res) {
  104. const { postData } = this.globalData
  105. const { accessToken } = res.data
  106. if (accessToken) {
  107. this.globalData.accessToken = accessToken
  108. wx.setStorageSync('accessToken', accessToken)
  109. // 判断当前是否有接口报登录失效,存在失效的情况下 接着执行
  110. if (postData) {
  111. const { fn, param } = postData
  112. fn(...param)
  113. this.globalData.postData = null
  114. return
  115. }
  116. this.navigatePermissionsCtl()
  117. }
  118. },
  119. /**
  120. * 权限判断跳转
  121. */
  122. navigatePermissionsCtl: function () {
  123. const { options, tempOptions } = this.globalData
  124. const { query = {}, scene, path } = options || tempOptions
  125. let url = ''
  126. if (query && query.type > 1) {
  127. url = path ? path.split('/')[1] : 'me'
  128. const method = { ...query, url, scene }
  129. this.reLaunchCtl && this.reLaunchCtl({ url, method }, true)
  130. this.globalData.options = tempOptions
  131. } else {
  132. // this.getVipList()
  133. this.redirectCtl && this.redirectCtl({ url: 'me' }, true)
  134. }
  135. },
  136. /**
  137. * 保存微信用户数据
  138. * */
  139. saveUserInfo: function (res, code) {
  140. const { appType } = this.globalData
  141. const { encryptedData, iv, signature, userInfo } = res
  142. const user = Object.assign(userInfo, { encryptedData, iv, signature })
  143. this.post('/api/user/newlogin', { code, appType, ...user }).then(res => {
  144. this.globalData.userInfo = user
  145. wx.setStorageSync('userInfo', user)
  146. this.handleLogin(res)
  147. })
  148. },
  149. /**
  150. * 微信授权接口封装
  151. */
  152. wxSetting: function ({ scope, text }) {
  153. const isEmptyObject = function (e) {
  154. var temp;
  155. for (temp in e)
  156. return !1;
  157. return !0
  158. }
  159. return new Promise((resolve, reject) => {
  160. wx.getSetting({
  161. success: res => {
  162. if (isEmptyObject(res.authSetting)) {
  163. resolve(Object.assign(res, { type: 1, text: `请手动点击${text}` }))
  164. } else if (res.authSetting[scope] === true) {
  165. resolve(Object.assign(res, { type: 2, text: `默认${text}成功` }))
  166. } else if (res.authSetting[scope] === false) {
  167. wx.showModal({
  168. content: `检测到您没打开${text},是否去设置打开?`,
  169. confirmText: "确认",
  170. cancelText: "取消",
  171. success: res => {
  172. if (res.confirm) {
  173. wx.openSetting({
  174. success: res => {
  175. if (res.authSetting[scope]) {
  176. resolve(Object.assign(res, { type: 3, text: `手动设置${text}成功` }))
  177. } else {
  178. reject(Object.assign(res, { type: 5, text: `没有手动设置${text}` }))
  179. }
  180. },
  181. fail: res => {
  182. reject(Object.assign(res, { type: 4, text: `打开手动设置${text}失败` }))
  183. }
  184. })
  185. } else {
  186. reject(Object.assign(res, { type: 3, text: `拒绝打开手动设置${text}` }))
  187. }
  188. },
  189. fail: res => {
  190. reject(Object.assign(res, { type: 2, text: `弹出${text}提示框失败` }))
  191. }
  192. })
  193. } else {
  194. wx.authorize({
  195. scope,
  196. success: res => {
  197. resolve(Object.assign(res, { type: 4, text: `自动获取${text}成功` }))
  198. },
  199. fail: res => {
  200. reject(Object.assign(res, { type: 6, text: `自动获取${text}失败` }))
  201. }
  202. })
  203. }
  204. },
  205. fail: res => {
  206. reject(res, { type: 1, text: `获取${text}失败` })
  207. }
  208. })
  209. })
  210. },
  211. /**
  212. * 获取微信用户信息授权
  213. */
  214. getWxUserInfoSetting: function (cb) {
  215. this.wxSetting({ scope: 'scope.userInfo', text: '微信用户信息授权' }).then((res) => {
  216. wx.setStorageSync('hasUserInfo', 1)
  217. if (typeof cb === 'function') cb(1, res)
  218. }).catch((res) => {
  219. wx.setStorageSync('hasUserInfo', 0)
  220. if (res.type != 6) {
  221. wx.showToast({
  222. title: res.text,
  223. icon: 'none'
  224. })
  225. }
  226. if (typeof cb === 'function') cb(0, res)
  227. setTimeout(() => {
  228. wx.navigateBack({
  229. delta: 1
  230. })
  231. }, 2000)
  232. })
  233. },
  234. /**
  235. * 获取微信定位授权
  236. */
  237. getWxUserLocationSetting: function (cb) {
  238. this.wxSetting({ scope: 'scope.userLocation', text: '微信用户定位授权' }).then((res) => {
  239. wx.setStorageSync('isPosition', 1)
  240. if (typeof cb === 'function') {
  241. cb(res)
  242. }
  243. }).catch((res) => {
  244. wx.setStorageSync('isPosition', 0)
  245. wx.showToast({
  246. title: res.text,
  247. icon: 'none'
  248. })
  249. setTimeout(() => {
  250. wx.navigateBack({
  251. delta: 1
  252. })
  253. }, 1200)
  254. })
  255. },
  256. /**
  257. * 获取全局属性值
  258. */
  259. getGlobalAttributeValue: function (e1, e2 = e1) {
  260. return typeof this.globalData[e1] !== 'undefined' && this.globalData[e1] !== null ? this.globalData[e1] : typeof wx.getStorageSync(e2) !== 'undefined' && wx.getStorageSync(e2) !== null ? wx.getStorageSync(e2) : null
  261. },
  262. /**
  263. * POST 封装
  264. * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj
  265. * @param data{Object} data【自定义传的参数数据】
  266. * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】]
  267. */
  268. post: function (obj, data = {}, head, postData) {
  269. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData
  270. const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken')
  271. let url
  272. if (typeof obj === 'object') {
  273. const { src, method = {}, type } = obj
  274. url = formatUrl(host + src, type == 1 ? method : Object.assign({}, method, { accessToken }))
  275. } else if (typeof obj === 'string') {
  276. url = formatUrl(host + obj, { accessToken })
  277. } else {
  278. throw new Error('请正确填写访问后台接口路径')
  279. return
  280. }
  281. return new Promise((resolve, reject) => {
  282. wx.request({
  283. url,
  284. data,
  285. method: 'POST',
  286. header: head ? {
  287. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  288. "Content-Type": "application/x-www-form-urlencoded"
  289. } : {
  290. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  291. "Content-Type": "application/json"
  292. },
  293. success: e => {
  294. if (e.statusCode == 200 && e.errMsg == 'request:ok') {
  295. if (e.data.code == '999') {
  296. resolve(e.data)
  297. } else {
  298. if (url.indexOf('/api/user/checkToken') == -1) {
  299. wx.showToast({
  300. title: e.data.msg,
  301. icon: 'none'
  302. })
  303. }
  304. reject(e.data)
  305. }
  306. if (loginTime > 0) {
  307. this.globalData.loginTime = 0
  308. }
  309. } else if (e.statusCode == 401) {
  310. this.globalData.loginTime = loginTime + 1
  311. if (loginTime < 2) {
  312. this.globalData.postData = postData || null
  313. this.login()
  314. }
  315. } else {
  316. reject(e)
  317. wx.showToast({
  318. title: '加载失败',
  319. icon: 'none'
  320. })
  321. }
  322. },
  323. fail: e => {
  324. reject(e)
  325. wx.showToast({
  326. title: '加载失败',
  327. icon: 'none'
  328. })
  329. },
  330. complete: e => {
  331. console.log({ url, data })
  332. console.log(e.data)
  333. }
  334. })
  335. })
  336. },
  337. /**
  338. * uploadFile 封装
  339. * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj
  340. * @param file{String} file【微信小程序生成的临时文件资源路径】
  341. * @param data{Object} data【自定义传的参数数据】
  342. * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】]
  343. * @param progress{Function} progress【上传文件进度条回调函数方法】
  344. */
  345. uploadFile: function (obj, file, data = {}, head, progress, postData) {
  346. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData
  347. const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken')
  348. let url
  349. if (typeof obj === 'object') {
  350. const { src, method, type } = obj
  351. url = formatUrl(host + src, type == 1 ? method : Object.assign(method || {}, { accessToken }))
  352. } else if (typeof obj === 'string') {
  353. url = formatUrl(host + obj, { accessToken })
  354. } else {
  355. throw new Error('请正确填写访问后台接口路径')
  356. return
  357. }
  358. wx.showLoading({
  359. title: '上传中...',
  360. })
  361. let uploadTask
  362. return new Promise((resolve, reject) => {
  363. uploadTask = wx.uploadFile({
  364. url,
  365. filePath: file,
  366. name: 'files',
  367. formData: data,
  368. header: head ? {
  369. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  370. "Content-Type": "application/x-www-form-urlencoded"
  371. } : {
  372. wechatsys, phoneimei, phonesys, phonetype, version, platform, build,
  373. "Content-Type": "application/json"
  374. },
  375. success: e => {
  376. if (e.statusCode == 200 && e.errMsg == 'uploadFile:ok') {
  377. resolve(e.data)
  378. if (loginTime > 0) {
  379. this.globalData.loginTime = 0
  380. }
  381. } else if (e.statusCode == 401) {
  382. this.globalData.loginTime = loginTime + 1
  383. if (loginTime < 2) {
  384. this.globalData.postData = postData || null
  385. this.login()
  386. }
  387. } else {
  388. reject(e)
  389. wx.showToast({
  390. title: '加载失败',
  391. icon: 'none'
  392. })
  393. }
  394. },
  395. fail(e) {
  396. reject(e)
  397. wx.showToast({
  398. title: '加载失败',
  399. icon: 'none'
  400. })
  401. },
  402. complete(e) {
  403. console.log({ url, data })
  404. console.log(e.data)
  405. wx.hideLoading()
  406. }
  407. })
  408. })
  409. uploadTask.onProgressUpdate((res) => {
  410. progress && progress(res)
  411. wx.showLoading({
  412. title: ` 已上传(${res.progress}%)`
  413. })
  414. if (res.progress == 100) {
  415. wx.hideLoading()
  416. }
  417. })
  418. },
  419. /**
  420. * reLaunch路由跳转
  421. */
  422. reLaunchCtl: function (e, type) {
  423. const { method, url, msg } = type ? e : e.currentTarget.dataset
  424. if (!url) {
  425. wx.showToast({
  426. title: msg || '暂未开放',
  427. icon: 'none'
  428. })
  429. return
  430. }
  431. let array = []
  432. if (method) {
  433. for (let i in method) {
  434. if (typeof data === 'object') {
  435. array.push(`${i}=${JSON.stringify(method[i])}`)
  436. } else {
  437. array.push(`${i}=${method[i]}`)
  438. }
  439. }
  440. }
  441. wx.reLaunch({
  442. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  443. success: res => { },
  444. fail: res => {
  445. wx.showToast({
  446. title: '跳转失败',
  447. icon: 'none'
  448. })
  449. }
  450. })
  451. },
  452. /**
  453. * navigate路由跳转
  454. */
  455. navigateCtl: throttle(function (e, type) {
  456. const { method, url, msg } = type ? e : e.currentTarget.dataset
  457. if (!url) {
  458. wx.showToast({
  459. title: msg || '暂未开放',
  460. icon: 'none'
  461. })
  462. return
  463. }
  464. let array = []
  465. if (method) {
  466. for (let i in method) {
  467. if (typeof data === 'object') {
  468. array.push(`${i}=${JSON.stringify(method[i])}`)
  469. } else {
  470. array.push(`${i}=${method[i]}`)
  471. }
  472. }
  473. }
  474. wx.navigateTo({
  475. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  476. success: res => { },
  477. fail: res => {
  478. console.log(res)
  479. wx.showToast({
  480. title: '跳转失败',
  481. icon: 'none'
  482. })
  483. }
  484. })
  485. }, 500),
  486. /**
  487. * blockCtl返回上一级页面
  488. */
  489. blockCtl:function(){
  490. wx.navigateBack({
  491. success: function (res) {
  492. // beforePage.onLoad(); // 执行前一个页面的onLoad方法
  493. console.log(res)
  494. }
  495. });
  496. },
  497. /**
  498. * redirect路由跳转
  499. */
  500. redirectCtl: function (e, type) {
  501. const { method, url, msg } = type ? e : e.currentTarget.dataset
  502. if (!url) {
  503. wx.showToast({
  504. title: msg || '暂未开放',
  505. icon: 'none'
  506. })
  507. return
  508. }
  509. let array = []
  510. if (method) {
  511. for (let i in method) {
  512. if (typeof data === 'object') {
  513. array.push(`${i}=${JSON.stringify(method[i])}`)
  514. } else {
  515. array.push(`${i}=${method[i]}`)
  516. }
  517. }
  518. }
  519. wx.redirectTo({
  520. url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`,
  521. success: res => { },
  522. fail: res => {
  523. wx.showToast({
  524. title: '跳转失败',
  525. icon: 'none'
  526. })
  527. }
  528. })
  529. },
  530. /**
  531. * 查看图片
  532. */
  533. viewImageCtl: function (e) {
  534. let { images, index, baseurl, url = 'img' } = e.currentTarget.dataset
  535. let array = images.map((val, key) => {
  536. return baseurl + val[url]
  537. })
  538. wx.previewImage({
  539. current: baseurl + images[index][url], // 当前显示图片的http链接
  540. urls: array // 需要预览的图片http链接列表
  541. })
  542. },
  543. /**
  544. * 分享控制层
  545. */
  546. sharePageDefaultCtl: function () {
  547. return {
  548. title: '探知脑力',
  549. path: 'pages/index/index?type=1',
  550. success: res => {
  551. wx.showToast({
  552. title: '转发成功',
  553. icon: 'success'
  554. })
  555. },
  556. fail: res => {
  557. wx.showToast({
  558. title: '转发失败',
  559. icon: 'none'
  560. })
  561. }
  562. }
  563. },
  564. /**
  565. * 全局变量
  566. */
  567. globalData: {
  568. wechatsys: sys.version + ' ' + sys.SDKVersion,
  569. phoneimei: '',
  570. phonesys: sys.system,
  571. phonetype: sys.brand + ' ' + sys.model,
  572. version: '1.0.4',
  573. platform: '3',
  574. build: '1.0.4',
  575. appType: 22,
  576. initStatus: 0,
  577. loginTime: 0,
  578. // host: 'https://api.sharingschool.com/sz',
  579. // baseImgUrl: 'https://api.sharingschool.com/upload',
  580. host: 'https://xt.sharingschool.com/sz',
  581. baseImgUrl: 'https://xt.sharingschool.com/upload',
  582. thumbnail: '!m300x200.png',
  583. accessToken: null,
  584. parentVipList: null,
  585. parentVipLiIdx: null,
  586. parentVipId: null,
  587. parentInfo: null,
  588. appid: 'wxb85618936c73086b',
  589. userInfo: null,
  590. options: null,
  591. postData: null,
  592. tempOptions: { query: {}, path: 'pages/index/index', scene: 1001 }
  593. }
  594. })