//app.js const { formatUrl, throttle } = require('utils/util.js') const sys = wx.getSystemInfoSync() App({ onLaunch: function (options) { this.globalData.options = options wx.getSystemInfo({ success: e => { this.globalData.statusBar = e.statusBarHeight; //状态栏高度 // let custom = wx.getMenuButtonBoundingClientRect();//菜单按钮 // this.globalData.custom = custom; // this.globalData.customBar = custom.bottom + custom.top - e.statusBarHeight; //计算得到定义的状态栏高度 } }) }, onShow: function (options) { this.globalData.options = options }, onHide: function (e) { }, onError: function (e) { wx.showToast({ title: '程序执行失败', icon: 'none' }) }, onPageNotFound: function (res) { wx.showToast({ title: '没有找到页面', icon: 'none' }) }, /** * 初始化 */ init: function () { const accessToken = this.getGlobalAttributeValue('accessToken') const userInfo = this.getGlobalAttributeValue('userInfo') this.getWxUserInfoSetting((type, res) => { // if (type != 1 || !userInfo) { // this.redirectCtl({ url: 'wx_authority' }, 1) // return // } this.globalData.userInfo = userInfo wx.checkSession({ success: res => { this.globalData.accessToken = accessToken this.navigatePermissionsCtl() }, fail: res => { this.login() } }) }) // this.post('/api/user/checkToken').then(res => { // if (accessToken) { // this.globalData.accessToken = accessToken // } // if (userInfo) { // this.globalData.userInfo = userInfo // } else { // this.redirectCtl({ url: 'wx_authority' }, 1) // return // } // this.navigatePermissionsCtl() // }).catch(res => { // this.login() // }) }, /** * 获取微信code */ getWxloginCode: function (cb) { wx.login({ success: res => { if (cb) cb(res.code) }, fail: res => { wx.showToast({ title: '获取微信code失败', icon: 'none' }) } }) }, /** * 获取微信用户信息 */ login: function () { const { appType } = this.globalData this.getWxloginCode(code => { this.post('/api/user/tlogin', { code, appType }).then(this.handleLogin).catch(e => { if (e.data.code == '888') { this.redirectCtl({ url: 'wx_authority' }, 1) } }) }) }, /** * 获取登录数据 */ handleLogin: function (res) { const { postData } = this.globalData const { accessToken } = res.data if (accessToken) { this.globalData.accessToken = accessToken wx.setStorageSync('accessToken', accessToken) // 判断当前是否有接口报登录失效,存在失效的情况下 接着执行 if (postData) { const { fn, param } = postData fn(...param) this.globalData.postData = null return } this.navigatePermissionsCtl() } }, /** * 权限判断跳转 */ navigatePermissionsCtl: function () { const { options, tempOptions } = this.globalData const { query = {}, scene, path } = options || tempOptions let url = '' if (query && query.type > 1) { url = path ? path.split('/')[1] : 'me' const method = { ...query, url, scene } this.reLaunchCtl && this.reLaunchCtl({ url, method }, true) this.globalData.options = tempOptions } else { // this.getVipList() this.redirectCtl && this.redirectCtl({ url: 'me' }, true) } }, /** * 保存微信用户数据 * */ saveUserInfo: function (res, code) { const { appType } = this.globalData const { encryptedData, iv, signature, userInfo } = res const user = Object.assign(userInfo, { encryptedData, iv, signature }) this.post('/api/user/newlogin', { code, appType, ...user }).then(res => { this.globalData.userInfo = user wx.setStorageSync('userInfo', user) this.handleLogin(res) }) }, /** * 微信授权接口封装 */ wxSetting: function ({ scope, text }) { const isEmptyObject = function (e) { var temp; for (temp in e) return !1; return !0 } return new Promise((resolve, reject) => { wx.getSetting({ success: res => { if (isEmptyObject(res.authSetting)) { resolve(Object.assign(res, { type: 1, text: `请手动点击${text}` })) } else if (res.authSetting[scope] === true) { resolve(Object.assign(res, { type: 2, text: `默认${text}成功` })) } else if (res.authSetting[scope] === false) { wx.showModal({ content: `检测到您没打开${text},是否去设置打开?`, confirmText: "确认", cancelText: "取消", success: res => { if (res.confirm) { wx.openSetting({ success: res => { if (res.authSetting[scope]) { resolve(Object.assign(res, { type: 3, text: `手动设置${text}成功` })) } else { reject(Object.assign(res, { type: 5, text: `没有手动设置${text}` })) } }, fail: res => { reject(Object.assign(res, { type: 4, text: `打开手动设置${text}失败` })) } }) } else { reject(Object.assign(res, { type: 3, text: `拒绝打开手动设置${text}` })) } }, fail: res => { reject(Object.assign(res, { type: 2, text: `弹出${text}提示框失败` })) } }) } else { wx.authorize({ scope, success: res => { resolve(Object.assign(res, { type: 4, text: `自动获取${text}成功` })) }, fail: res => { reject(Object.assign(res, { type: 6, text: `自动获取${text}失败` })) } }) } }, fail: res => { reject(res, { type: 1, text: `获取${text}失败` }) } }) }) }, /** * 获取微信用户信息授权 */ getWxUserInfoSetting: function (cb) { this.wxSetting({ scope: 'scope.userInfo', text: '微信用户信息授权' }).then((res) => { wx.setStorageSync('hasUserInfo', 1) if (typeof cb === 'function') cb(1, res) }).catch((res) => { wx.setStorageSync('hasUserInfo', 0) if (res.type != 6) { wx.showToast({ title: res.text, icon: 'none' }) } if (typeof cb === 'function') cb(0, res) setTimeout(() => { wx.navigateBack({ delta: 1 }) }, 2000) }) }, /** * 获取微信定位授权 */ getWxUserLocationSetting: function (cb) { this.wxSetting({ scope: 'scope.userLocation', text: '微信用户定位授权' }).then((res) => { wx.setStorageSync('isPosition', 1) if (typeof cb === 'function') { cb(res) } }).catch((res) => { wx.setStorageSync('isPosition', 0) wx.showToast({ title: res.text, icon: 'none' }) setTimeout(() => { wx.navigateBack({ delta: 1 }) }, 1200) }) }, /** * 获取全局属性值 */ getGlobalAttributeValue: function (e1, e2 = e1) { 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 }, /** * POST 封装 * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj * @param data{Object} data【自定义传的参数数据】 * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】] */ post: function (obj, data = {}, head, postData) { const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken') let url if (typeof obj === 'object') { const { src, method = {}, type } = obj url = formatUrl(host + src, type == 1 ? method : Object.assign({}, method, { accessToken })) } else if (typeof obj === 'string') { url = formatUrl(host + obj, { accessToken }) } else { throw new Error('请正确填写访问后台接口路径') return } return new Promise((resolve, reject) => { wx.request({ url, data, method: 'POST', header: head ? { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/x-www-form-urlencoded" } : { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/json" }, success: e => { if (e.statusCode == 200 && e.errMsg == 'request:ok') { if (e.data.code == '999') { resolve(e.data) } else { if (url.indexOf('/api/user/checkToken') == -1) { wx.showToast({ title: e.data.msg, icon: 'none' }) } reject(e.data) } if (loginTime > 0) { this.globalData.loginTime = 0 } } else if (e.statusCode == 401) { this.globalData.loginTime = loginTime + 1 if (loginTime < 2) { this.globalData.postData = postData || null this.login() } } else { reject(e) wx.showToast({ title: '加载失败', icon: 'none' }) } }, fail: e => { reject(e) wx.showToast({ title: '加载失败', icon: 'none' }) }, complete: e => { console.log({ url, data }) console.log(e.data) } }) }) }, /** * uploadFile 封装 * @param obj{Object} {src【请求后台路径】, method【拼接在路径的参数对象】, type【判断是否需要把参数拼接在路径后面】} = obj * @param file{String} file【微信小程序生成的临时文件资源路径】 * @param data{Object} data【自定义传的参数数据】 * @param head{Boolean} head[true【data参数类型为json对象】,false【data参数类型为json字符串】] * @param progress{Function} progress【上传文件进度条回调函数方法】 */ uploadFile: function (obj, file, data = {}, head, progress, postData) { const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build } = this.globalData const accessToken = this.globalData.accessToken || wx.getStorageSync('accessToken') let url if (typeof obj === 'object') { const { src, method, type } = obj url = formatUrl(host + src, type == 1 ? method : Object.assign(method || {}, { accessToken })) } else if (typeof obj === 'string') { url = formatUrl(host + obj, { accessToken }) } else { throw new Error('请正确填写访问后台接口路径') return } wx.showLoading({ title: '上传中...', }) let uploadTask return new Promise((resolve, reject) => { uploadTask = wx.uploadFile({ url, filePath: file, name: 'files', formData: data, header: head ? { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/x-www-form-urlencoded" } : { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/json" }, success: e => { if (e.statusCode == 200 && e.errMsg == 'uploadFile:ok') { resolve(e.data) if (loginTime > 0) { this.globalData.loginTime = 0 } } else if (e.statusCode == 401) { this.globalData.loginTime = loginTime + 1 if (loginTime < 2) { this.globalData.postData = postData || null this.login() } } else { reject(e) wx.showToast({ title: '加载失败', icon: 'none' }) } }, fail(e) { reject(e) wx.showToast({ title: '加载失败', icon: 'none' }) }, complete(e) { console.log({ url, data }) console.log(e.data) wx.hideLoading() } }) }) uploadTask.onProgressUpdate((res) => { progress && progress(res) wx.showLoading({ title: ` 已上传(${res.progress}%)` }) if (res.progress == 100) { wx.hideLoading() } }) }, /** * reLaunch路由跳转 */ reLaunchCtl: function (e, type) { const { method, url, msg } = type ? e : e.currentTarget.dataset if (!url) { wx.showToast({ title: msg || '暂未开放', icon: 'none' }) return } let array = [] if (method) { for (let i in method) { if (typeof data === 'object') { array.push(`${i}=${JSON.stringify(method[i])}`) } else { array.push(`${i}=${method[i]}`) } } } wx.reLaunch({ url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`, success: res => { }, fail: res => { wx.showToast({ title: '跳转失败', icon: 'none' }) } }) }, /** * navigate路由跳转 */ navigateCtl: throttle(function (e, type) { const { method, url, msg } = type ? e : e.currentTarget.dataset if (!url) { wx.showToast({ title: msg || '暂未开放', icon: 'none' }) return } let array = [] if (method) { for (let i in method) { if (typeof data === 'object') { array.push(`${i}=${JSON.stringify(method[i])}`) } else { array.push(`${i}=${method[i]}`) } } } wx.navigateTo({ url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`, success: res => { }, fail: res => { console.log(res) wx.showToast({ title: '跳转失败', icon: 'none' }) } }) }, 500), /** * blockCtl返回上一级页面 */ blockCtl:function(){ wx.navigateBack({ success: function (res) { // beforePage.onLoad(); // 执行前一个页面的onLoad方法 console.log(res) } }); }, /** * redirect路由跳转 */ redirectCtl: function (e, type) { const { method, url, msg } = type ? e : e.currentTarget.dataset if (!url) { wx.showToast({ title: msg || '暂未开放', icon: 'none' }) return } let array = [] if (method) { for (let i in method) { if (typeof data === 'object') { array.push(`${i}=${JSON.stringify(method[i])}`) } else { array.push(`${i}=${method[i]}`) } } } wx.redirectTo({ url: `${getCurrentPages().length == 0 ? 'pages' : '..'}/${url}/${url}${array.length > 0 ? '?' + array.join('&') : ''}`, success: res => { }, fail: res => { wx.showToast({ title: '跳转失败', icon: 'none' }) } }) }, /** * 查看图片 */ viewImageCtl: function (e) { let { images, index, baseurl, url = 'img' } = e.currentTarget.dataset let array = images.map((val, key) => { return baseurl + val[url] }) wx.previewImage({ current: baseurl + images[index][url], // 当前显示图片的http链接 urls: array // 需要预览的图片http链接列表 }) }, /** * 分享控制层 */ sharePageDefaultCtl: function () { return { title: '探知脑力', path: 'pages/index/index?type=1', success: res => { wx.showToast({ title: '转发成功', icon: 'success' }) }, fail: res => { wx.showToast({ title: '转发失败', icon: 'none' }) } } }, /** * 全局变量 */ globalData: { wechatsys: sys.version + ' ' + sys.SDKVersion, phoneimei: '', phonesys: sys.system, phonetype: sys.brand + ' ' + sys.model, version: '1.0.4', platform: '3', build: '1.0.4', appType: 22, initStatus: 0, loginTime: 0, // host: 'https://api.sharingschool.com/sz', // baseImgUrl: 'https://api.sharingschool.com/upload', host: 'https://xt.sharingschool.com/sz', baseImgUrl: 'https://xt.sharingschool.com/upload', thumbnail: '!m300x200.png', accessToken: null, parentVipList: null, parentVipLiIdx: null, parentVipId: null, parentInfo: null, appid: 'wxb85618936c73086b', userInfo: null, options: null, postData: null, tempOptions: { query: {}, path: 'pages/index/index', scene: 1001 } } })