Explorar el Código

格式登录相关代码,准备修改

joe hace 4 años
padre
commit
03e67f2947

+ 1 - 1
view/xcx/README.md

@@ -94,7 +94,7 @@
   │ ├─user_spread_user 我的推广
   │ └─user_vip 会员页面
   ├─utils 工具类目录
-  │ ├─autuLogin.js 自动授权登陆
+  │ ├─autoLogin.js 自动授权登陆
   │ ├─request.js 请求基类
   │ ├─Server.js Socket类
   │ ├─util.js 工具函数

+ 146 - 141
view/xcx/app.js

@@ -3,151 +3,156 @@ import Server from './utils/Server.js';
 import util from './utils/util.js';
 
 App({
-  onLaunch: function (option) {
-    if (HTTP_REQUEST_URL==''){
-      console.error("请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret");
-      return false;
-    }
-    let that = this;
-    let token = wx.getStorageSync(CACHE_TOKEN);
-    let expiresTime = wx.getStorageSync(CACHE_EXPIRES_TIME);
-    let userInfo = wx.getStorageSync(CACHE_USERINFO);
-    this.globalData.isLog = !!userInfo && util.checkLogin(token, expiresTime,true);
-    if (this.globalData.isLog) {
-      this.globalData.token = token;
-      this.globalData.expiresTime = expiresTime;
-      this.globalData.userInfo = userInfo ? JSON.parse(userInfo) : {};
-    }
-    if (option.query.hasOwnProperty('scene')){
-      switch (option.scene) {
-        //扫描小程序码
-        case 1047:
-          that.globalData.code = option.query.scene;
-          break;
-        //长按图片识别小程序码
-        case 1048:
-          that.globalData.code = option.query.scene;
-          break;
-        //手机相册选取小程序码
-        case 1049:
-          that.globalData.code = option.query.scene;
-          break;
-        //直接进入小程序
-        case 1001:
-          that.globalData.spid = option.query.scene;
-          break;
-      }
-    }
-    // 获取导航高度;
-    wx.getSystemInfo({
-      success: res => {
-        //导航高度
-        this.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 97;
+	onLaunch: function (option) {
+    	if (HTTP_REQUEST_URL=='') {
+      		console.error("请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret");
+      		return false;
+    	}
+    	let that = this;
+    	let token = wx.getStorageSync(CACHE_TOKEN);
+    	let expiresTime = wx.getStorageSync(CACHE_EXPIRES_TIME);
+    	let userInfo = wx.getStorageSync(CACHE_USERINFO);
+    	this.globalData.isLog = !!userInfo && util.isLoginValid(token, expiresTime, true);
+    	if (this.globalData.isLog) {
+      		this.globalData.token = token;
+      		this.globalData.expiresTime = expiresTime;
+      		this.globalData.userInfo = userInfo ? JSON.parse(userInfo) : {};
+    	}
+    	if (option.query.hasOwnProperty('scene')){
+      		switch (option.scene) {
+        		//扫描小程序码
+        		case 1047:
+        		  that.globalData.code = option.query.scene;
+        		  break;
+        		//长按图片识别小程序码
+        		case 1048:
+        		  that.globalData.code = option.query.scene;
+        		  break;
+        		//手机相册选取小程序码
+        		case 1049:
+        		  that.globalData.code = option.query.scene;
+        		  break;
+        		//直接进入小程序
+        		case 1001:
+        		  that.globalData.spid = option.query.scene;
+        		  break;
+      		} // switch
+		} // if
+		
+    	// 获取导航高度;
+    	wx.getSystemInfo({
+      		success: res => {
+        		//导航高度
+        		this.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 97;
 
-        var model = res.model;
-        if (/iphone\sx/i.test(model) || (/iphone/i.test(model) && /unknown/.test(model))|| /iphone\s11/i.test(model)){
-            that.globalData.isFixed = true;
-        } else {
-            that.globalData.isFixed = false;
-        }
-      }, fail(err) {}
-    });
-    const updateManager = wx.getUpdateManager();
+        		var model = res.model;
+				if (/iphone\sx/i.test(model) || 
+					(/iphone/i.test(model) && /unknown/.test(model)) || 
+					/iphone\s11/i.test(model)) {
+            		that.globalData.isFixed = true;
+        		} else {
+            		that.globalData.isFixed = false;
+        		}
+			}, 
+			fail(err) {}
+    	});
+    	const updateManager = wx.getUpdateManager();
 
-    updateManager.onCheckForUpdate(function (res) {
-      // 请求完新版本信息的回调
-      
-    })
+    	updateManager.onCheckForUpdate(function (res) {
+      		// 请求完新版本信息的回调
+    	})
 
-    updateManager.onUpdateReady(function () {
-      wx.showModal({
-        title: '更新提示',
-        content: '新版本已经准备好,是否重启应用?',
-        success: function (res) {
-          if (res.confirm) {
-            // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
-            updateManager.applyUpdate()
-          }
-        }
-      })
-    });
+    	updateManager.onUpdateReady(function () {
+      		wx.showModal({
+        		title: '更新提示',
+        		content: '新版本已经准备好,是否重启应用?',
+        		success: function (res) {
+        		  	if (res.confirm) {
+        		    	// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
+        		    	updateManager.applyUpdate()
+        		  	}
+        		}
+      		})
+    	});
 
-    updateManager.onUpdateFailed(function () {
-      return that.Tips({title:'新版本下载失败'});
-    })
-    //实例化聊天服务
-    this.$chat = new Server(this);
-  },
-  $chat:null,
-  globalData: {
-    navHeight: 0,
-    routineStyle: '#ffffff',
-    openPages: '',
-    spid: 0,
-    code:0,
-    urlImages: '',
-    url: HTTP_REQUEST_URL,
-    token: '',
-    isLog:false,    // 是否已登录
-    expiresTime:0,
-    MyMenus:[],
-    userInfo:{},
-    loginType:'routine',
-    isFixed: false,
-    unread: 0,  // 未读消息条数
-  },
-  /**
-   * 聊天事件快捷注册
-   * 
-  */
-  $on: function (name, action){
-    this.$chat.$on(name,action);
-  },
-  /*
-  * 信息提示 + 跳转
-  * @param object opt {title:'提示语',icon:''} | url
-  * @param object to_url 跳转url 有5种跳转方式 {tab:1-5,url:跳转地址}
-  */
-  Tips: function (opt, to_url) { 
-    return util.Tips(opt, to_url);
-  },
-  /**
-   * 快捷调取助手函数
-  */
-  help:function()
-  {
-    return util.$h;
-  },
+    	updateManager.onUpdateFailed(function () {
+      		return that.Tips({title:'新版本下载失败'});
+    	})
+    	//实例化聊天服务
+    	this.$chat = new Server(this);
+	}, // onLaunch
+	  
+	$chat:null,
+	  
+  	globalData: {
+    	navHeight: 0,
+    	routineStyle: '#ffffff',
+    	openPages: '',
+    	spid: 0,
+    	code:0,
+    	urlImages: '',
+    	url: HTTP_REQUEST_URL,
+    	token: '',
+    	isLog:false,    // 是否已登录
+    	expiresTime:0,
+    	MyMenus:[],
+    	userInfo:{},
+    	loginType:'routine',
+    	isFixed: false,
+    	unread: 0,  // 未读消息条数
+	},
+	  
+  	/**
+   	 * 聊天事件快捷注册
+     */
+   	$on: function (name, action){
+    	this.$chat.$on(name,action);
+	},
 
-  setUnread: function(newVal)
-  {
-    this.globalData.unread = newVal
-    this.updateUnread();
-  },
+	/**
+	 * 信息提示 + 跳转
+  	 * @param object opt {title:'提示语',icon:''} | url
+     * @param object to_url 跳转url 有5种跳转方式 {tab:1-5,url:跳转地址}
+	 */
+  	Tips: function (opt, to_url) { 
+    	return util.Tips(opt, to_url);
+  	},
+  	/**
+     * 快捷调取助手函数
+     */
+  	help:function() {
+    	return util.$h;
+  	},
 
-  /**
-   * update unread message tip
-   * @param {int} newval 
-   */
-  updateUnread: function()
-  {
-    if (this.globalData.unread != undefined && this.globalData.unread > 0) {
-      wx.setTabBarBadge({
-        index: 2,
-        text: this.globalData.unread.toString(),
-      });
-    } else {
-      wx.removeTabBarBadge({
-        index: 2,
-      });
-    }
-  },
+  	setUnread: function(newVal) {
+    	this.globalData.unread = newVal
+    	this.updateUnread();
+  	},
 
-  /*
-  * 合并数组
-  * @param array list 请求返回数据
-  * @param array sp 原始数组
-  * @return array
-  */
-  SplitArray: function (list, sp) { return util.SplitArray(list, sp)},
-})
+  	/**
+     * update unread message tip
+     * @param {int} newval 
+     */
+  	updateUnread: function() {
+    	if (this.globalData.unread != undefined && this.globalData.unread > 0) {
+      		wx.setTabBarBadge({
+        		index: 2,
+        		text: this.globalData.unread.toString(),
+      		});
+    	} else {
+      		wx.removeTabBarBadge({
+        		index: 2,
+      		});
+    	}
+  	}, // updateUnread
+
+  	/**
+     * 合并数组
+     * @param array list 请求返回数据
+     * @param array sp 原始数组
+     * @return array
+     */
+  	SplitArray: function (list, sp) { 
+		  return util.SplitArray(list, sp)
+	},
+}) // App

+ 182 - 189
view/xcx/components/authorize/authorize.js

@@ -6,199 +6,192 @@ import { login } from '../../api/user.js';
 let app = getApp();
 
 Component({
-  properties: {
-    iShidden: {
-      type: Boolean,
-      value: true,
-    },
-    //是否自动登录
-    isAuto: {
-      type: Boolean,
-      value: true,
-    },
-    isGoIndex:{
-      type: Boolean,
-      value:true,
-    },
-  },
-  data: {
-    cloneIner: null,
-    loading:false,
-    errorSum:0,
-    errorNum:3,
-    code: null, // wx login code
-	  canIUseGetUserProfile: false // 判断是否为最新获取用户信息函数
-  },
-  attached() {
-    this.get_logo_url();
-    this.setAuthStatus();
-	  if (wx.getUserProfile) {
-	    this.setData({
-	      canIUseGetUserProfile: true
-	    })
-	  }
-  },
-  methods: {
-    close(){
-      let pages = getCurrentPages();
-      let currPage  = pages[pages.length - 1];
-      if(this.data.isGoIndex){
-        wx.switchTab({url:'/pages/index/index'});
-      }else{
-        this.setData({
-          iShidden: true
-        });
-        if (currPage && currPage.data.iShidden != undefined){
-          currPage.setData({ iShidden:true});
-        }
-      }
-    },
-    get_logo_url: function () {
-      var that = this;
-      if (wx.getStorageSync('logo_url')) return this.setData({ logo_url: wx.getStorageSync('logo_url') });
-      getLogo().then(res=>{
-        wx.setStorageSync('logo_url', res.data.logo_url);
-        that.setData({ logo_url: res.data.logo_url });
-      });
-    },
-    //检测登录状态并执行自动登录
-    setAuthStatus() {
-      var that = this;
-      Util.chekWxLogin().then((res)=> {
-        let pages = getCurrentPages();
-        let currPage = pages[pages.length - 1];
-        if (currPage && currPage.data.iShidden != undefined) { 
-          currPage.setData({ iShidden:true});
-        }
-        if (res.isLogin) {
-          if (!Util.checkLogin()) return Promise.reject({ authSetting: true, msg: '用户token失效', userInfo: res.userInfo});
-          that.triggerEvent('onLoadFun', app.globalData.userInfo);
-        }else{
-          wx.showLoading({ title: '正在登录中' });
-          that.setUserInfo(res.userInfo,true);
+    properties: {
+        // 当前授权窗口是否隐藏
+        iShidden: {
+          type: Boolean,
+          value: true,
+        },
+        // 是否自动登录
+        isAuto: {
+          type: Boolean,
+          value: true,
+        },
+        // 是否跳转到首页
+        isGoIndex:{
+          type: Boolean,
+          value:true,
+        },
+    }, // properties
+
+    data: {
+        errorCount:0,
+        errorMaxNum:3,
+        code: null, // wx login code
+        canIUseGetUserProfile: false, // 判断是否为最新获取用户信息函数
+        canIUseGetUserInfo: false
+    }, // data
+
+    attached() {
+        this.get_logo_url();
+        this.setAuthStatus();
+	    if (wx.getUserProfile) {
+	        this.setData({
+	            canIUseGetUserProfile: true
+	        })
         }
-      }).catch(res=>{
-        if (res.authSetting === false) {
-          //没有授权不会自动弹出登录框
-          if (that.data.isAuto === false) return;
-          //自动弹出授权
-          that.setData({ iShidden: false });
-        } else if (res.authSetting){
-          //授权后登录token失效了
-          that.setUserInfo(res.userInfo);
+        if (wx.getUserInfo) {
+            this.setData({
+                canIUseGetUserInfo: true
+            })
         }
-      })
-    },
+    }, // attached
 
-    wxSilentLogin: function () {
-      return new Promise((resolve, reject) => {
-        wx.login({
-          success (res) {
-            resolve(res.code)
-          },
-          fail (err) {
-            reject(err)
-          }
-        })
-      })
-    },
-    wxGetUserProfile: function () {
-      return new Promise((resolve, reject) => {
-        wx.getUserProfile({
-          desc: '用于完善会员资料',
-          success: (res) => {
-            resolve(res)
-          },
-          fail: (err) => {
-            reject(err)
-          }
-        })
-      })
-    },
-    // 获取用户信息
-  	getUserProfile() {
-  	  let that = this;
-      wx.showLoading({ title: '正在登录中' });
-      let p1 = this.wxSilentLogin()
-      let p2 = this.wxGetUserProfile()
-      Promise.all([p1, p2]).then((res) => {
-        let userInfo = res[1];
-        userInfo.code = res[0];
-        that.getWxUserInfo(userInfo);
-      }).catch((err) => {
-        console.log(err)
-      })
-      // wx.getUserProfile({
-  	  // 	desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
-  	  // 	success: (res) => {
-  		// 		Util.getCodeLogin((code)=>{
-  		// 			let userInfo = res;
-  		// 			userInfo.code = code.code;
-  		// 			that.getWxUserInfo(userInfo);
-  		// 		})
-  	  //   }, // success
-  	  // 	fail: (err) => {
-  		// 		wx.hideLoading();
-  	  // 	}
-  	  // });
-    }, //getUserProfile
-    
-    //授权
-    setUserInfo(userInfo,isLogin) {
-      let that = this;
-      wx.showLoading({ title: '正在登录中' });
-      if (isLogin){
-        that.getWxUserInfo(userInfo);
-      }else{
-        Util.getCodeLogin((res)=>{
-            Util.wxgetUserInfo().then(userInfo=>{
-              userInfo.code = res.code;
-              that.getWxUserInfo(userInfo);
-            }).catch(res=>{
-              wx.hideLoading();
+    methods: {
+        close() {
+            let pages = getCurrentPages();
+            let currPage  = pages[pages.length - 1];
+            if (this.data.isGoIndex) {
+                wx.switchTab({url: '/pages/index/index'});
+            } else {
+                this.setData({
+                  iShidden: true
+                });
+                if (currPage && currPage.data.iShidden != undefined){
+                  currPage.setData({ iShidden:true});
+                }
+            }
+        }, // close()
+
+        get_logo_url: function () {
+            var that = this;
+            if (wx.getStorageSync('logo_url')) {
+                return this.setData({ logo_url: wx.getStorageSync('logo_url') });
+            }
+            getLogo().then(res => {
+                wx.setStorageSync('logo_url', res.data.logo_url);
+                that.setData({ logo_url: res.data.logo_url });
             });
-        });
-      }
-    },
+        }, // get_logo_url()
 
-    // 从后台获取详细信息
-    getWxUserInfo: function (userInfo){
-      let that = this;
-      userInfo.spread_spid = app.globalData.spid;//获取推广人ID
-      userInfo.spread_code = app.globalData.code;//获取推广人分享二维码ID
-      // 发送到后台
-      login(userInfo).then(res => {
-        app.globalData.token = res.data.token;
-        app.globalData.isLog = true;
-        app.globalData.userInfo = res.data.userInfo;
-        app.globalData.expiresTime = res.data.expires_time;
-        wx.setStorageSync(CACHE_TOKEN, res.data.token);
-        wx.setStorageSync(CACHE_EXPIRES_TIME, res.data.expires_time);
-        wx.setStorageSync(CACHE_USERINFO, JSON.stringify(res.data.userInfo));
-        if (res.data.cache_key) wx.setStorage({ key: 'cache_key', data: res.data.cache_key });
-        //取消登录提示
-        wx.hideLoading();
-        //关闭登录弹出窗口
-        that.setData({ iShidden: true, errorSum: 0 });
-        //执行登录完成回调
-        that.triggerEvent('onLoadFun', app.globalData.userInfo);
-      }).catch((err) => {
-        wx.hideLoading();
-        that.data.errorSum++;
-        that.setData({ errorSum: that.data.errorSum });
-        if (that.data.errorSum >= that.data.errorNum) {
-          Util.Tips({ title: err });
-        } else {
-          that.setUserInfo(userInfo);
-        }
-      });
-    },
+        //检测登录状态并执行自动登录
+        setAuthStatus() {
+            var that = this;
+            Util.checkWxLogin().then((res) => {
+                let pages = getCurrentPages();
+                let currPage = pages[pages.length - 1];
+                if (currPage && currPage.data.iShidden != undefined) { 
+                    currPage.setData({ iShidden:true});
+                }
+                if (res.isLogin) {
+                    if (!Util.isLoginValid()) {
+                        return Promise.reject({ authSetting: true, msg: '用户token失效', userInfo: res.userInfo}  );
+                    }
+                    that.triggerEvent('onLoadFun', app.globalData.userInfo);
+                } else {
+                    wx.showLoading({ title: '正在登录中' });
+                    that.setUserInfo(res.userInfo,true);
+                }
+            }).catch(res => {
+                if (res.authSetting === false) {
+                    //没有授权不会自动弹出登录框
+                    if (that.data.isAuto === false) return;
+                    //自动弹出授权
+                    that.setData({ iShidden: false });
+                } else if (res.authSetting) {
+                    //授权后登录token失效了
+                    that.setUserInfo(res.userInfo);
+                }
+            })
+        }, // setAuthStatus()
+
+        wxSilentLogin: function () {
+            return new Promise((resolve, reject) => {
+                wx.login({
+                    success (res) {
+                        resolve(res.code)
+                    },
+                    fail (err) {
+                        reject(err)
+                    }
+                })
+            })
+        }, // wxSilentLogin
+
+        // 获取用户信息
+    	agreeAndAuth() {
+  	        let that = this;
+            wx.showLoading({ title: '正在登录中' });
+            let p1 = this.wxSilentLogin()
+            let p2 = Util.wxGetUserProfile()
+            Promise.all([p1, p2]).then((res) => {
+                let userInfo = res[1];
+                userInfo.code = res[0];
+                // console.log(userInfo);
+                that.loginAuth(userInfo);
+            }).catch((err) => {
+                console.log(err)
+            })
+        }, // agreeAndAuth
+    
+        //授权
+        setUserInfo(userInfo, isLogin) {
+            let that = this;
+            wx.showLoading({ title: '正在登录中' });
+            if (isLogin) {
+                that.loginAuth(userInfo);
+            } else {
+                Util.getAuthCode((res) => {
+                    Util.wxGetUserProfile().then(userInfo=>{
+                        userInfo.code = res.code;
+                        that.loginAuth(userInfo);
+                    }).catch(res => {
+                        wx.hideLoading();
+                    });
+                });
+            }
+        }, // setUserInfo()
+
+        // 从后台获取详细信息
+        loginAuth: function (userInfo) {
+            let that = this;
+            userInfo.spread_spid = app.globalData.spid;//获取推广人ID
+            userInfo.spread_code = app.globalData.code;//获取推广人分享二维码ID
+            // 发送到后台
+            login(userInfo).then(res => {
+                app.globalData.token = res.data.token;
+                app.globalData.isLog = true;
+                app.globalData.userInfo = res.data.userInfo;
+                app.globalData.expiresTime = res.data.expires_time;
+                wx.setStorageSync(CACHE_TOKEN, res.data.token);
+                wx.setStorageSync(CACHE_EXPIRES_TIME, res.data.expires_time);
+                wx.setStorageSync(CACHE_USERINFO, JSON.stringify(res.data.userInfo));
+                if (res.data.cache_key) {
+                    wx.setStorage({ key: 'cache_key', data: res.data.cache_key });
+                }
+                //取消登录提示
+                wx.hideLoading();
+                //关闭登录弹出窗口
+                that.setData({ iShidden: true, errorCount: 0 });
+                //执行登录完成回调
+                that.triggerEvent('onLoadFun', app.globalData.userInfo);
+            }).catch((err) => {
+                wx.hideLoading();
+                that.data.errorCount++;
+                that.setData({ errorCount: that.data.errorCount });
+                if (that.data.errorCount >= that.data.errorMaxNum) {
+                    Util.Tips({ title: err });
+                } else {
+                    that.setUserInfo(userInfo);
+                }
+            });
+        }, // loginAuth()
 
-    // 点击打开用户协议
-    onTabRegular: function() {
-      wx.navigateTo({
-        url: `/pages/user_license/license`
-      })
-    } //onTabRegular
-  },
+        // 点击打开用户协议
+        onTabRegular: function() {
+            wx.navigateTo({
+                url: `/pages/user_license/license`
+            })
+        } //onTabRegular
+    }, // methods
 })

+ 2 - 2
view/xcx/components/authorize/authorize.wxml

@@ -9,8 +9,8 @@
    <view class='bottom flex'>
       <view class='item' bindtap='close'>随便逛逛</view>
       <!-- 在高版本中获取用户信息已改成uni.getUserProfile-->
-	  <button class='item grant'  type="primary" wx:if="{{canIUseGetUserProfile}}" lang="zh_CN" bindtap="getUserProfile">同意并授权</button>
-	  <button class='item grant'  type="primary" wx:else open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="setUserInfo">同意并授权</button>
+	   <button class='item grant'  type="primary" wx:if="{{canIUseGetUserProfile}}" lang="zh_CN" bindtap="agreeAndAuth">同意并授权</button>
+	   <button class='item grant'  type="primary" wx:else open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="setUserInfo">同意并授权</button>
    </view>
 </view>
 <view class='mask' hidden='{{iShidden}}' catchtouchmove="true" bindtap='close'></view>

+ 1 - 1
view/xcx/pages/user/user.js

@@ -2,7 +2,7 @@ const app = getApp();
 
 import { getMenuList, getUserInfo} from '../../api/user.js';
 import { switchH5Login } from '../../api/api.js';
-import authLogin from '../../utils/autuLogin.js';
+import authLogin from '../../utils/autoLogin.js';
 import util from '../../utils/util.js';
 import wxh from '../../utils/wxh.js';
 Page({

+ 1 - 1
view/xcx/pages/user_info/index.js

@@ -1,6 +1,6 @@
 import { getUserInfo, userEdit} from '../../api/user.js';
 import { switchH5Login } from '../../api/api.js';
-import authLogin from '../../utils/autuLogin.js';
+import authLogin from '../../utils/autoLogin.js';
 import util from '../../utils/util.js';
 
 const app = getApp();

+ 27 - 0
view/xcx/utils/autoLogin.js

@@ -0,0 +1,27 @@
+import util from './util.js';
+import { login } from '../api/user.js';
+import { logout } from '../api/api.js';
+
+export default function authLogin(login_type) {
+  	return new Promise((reslove, reject) => {
+    	util.autoLogin().then(userInfo => {
+      		if (login_type !== undefined) {
+				userInfo.login_type = 'routine';
+			}
+      		login(userInfo).then(res => {
+        		getApp().globalData.token = res.data.token;
+        		getApp().globalData.userInfo = res.data.userInfo;
+        		getApp().globalData.isLog = true;
+        		getApp().globalData.expiresTime = res.data.expires_time;
+        		if (res.data.cache_key) {
+					wx.setStorage({ key: 'cache_key', data: res.data.cache_key });
+				}
+        		reslove();
+      		}).catch(err => {
+        		reject();
+      		});
+    	}).catch(err=>{
+      		reject();
+    	});
+  	})
+}

+ 0 - 23
view/xcx/utils/autuLogin.js

@@ -1,23 +0,0 @@
-import util from './util.js';
-import { login } from './../api/user.js';
-import { logout } from './../api/api.js';
-
-export default function authLogin(login_type){
-  return new Promise((reslove, reject) => {
-    util.autoLogin().then(userInfo => {
-      if (login_type !== undefined) userInfo.login_type = 'routine';
-      login(userInfo).then(res => {
-        getApp().globalData.token = res.data.token;
-        getApp().globalData.userInfo = res.data.userInfo;
-        getApp().globalData.isLog = true;
-        getApp().globalData.expiresTime = res.data.expires_time;
-        if (res.data.cache_key) wx.setStorage({ key: 'cache_key', data: res.data.cache_key });
-        reslove();
-      }).catch(err=>{
-        reject();
-      });
-    }).catch(err=>{
-      reject();
-    });
-  })
-}

+ 43 - 34
view/xcx/utils/request.js

@@ -1,46 +1,55 @@
 import util from './util.js';
-import authLogin from './autuLogin.js';
+import authLogin from './autoLogin.js';
 import { HEADER , TOKENNAME} from './../config.js';
+
 /**
  * 发送请求
  */
-export default function request(api, method, data, {noAuth = false, noVerify = false})
-{
-  let Url = getApp().globalData.url, header = HEADER;
-  if (!noAuth) {
-    //登录过期自动登录
-    if (!util.checkLogin()) return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify}); });
-  }
+export default function request(api, method, data, {noAuth = false, noVerify = false}) {
+  	let Url = getApp().globalData.url, header = HEADER;
+  	if (!noAuth) {
+    	//登录过期自动登录
+		if (!util.isLoginValid()) {
+			return authLogin().then(res => { 
+				return request(api, method, data, { noAuth, noVerify}); 
+			});
+		}
+  	}
   
-  if (getApp().globalData.token) header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
+  	if (getApp().globalData.token) {
+		header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
+	}
 
-  return new Promise((reslove, reject) => {
-    wx.request({
-      url: Url + '/api/' + api,
-      method: method || 'GET',
-      header: header,
-      data: data || {},
-      success: (res) => {
-        if (noVerify)
-          reslove(res.data, res);
-        else if (res.data.status == 200)
-          reslove(res.data, res);
-        else if (res.data.status == 402)
-          reslove(res.data, res);
-        else if ([410000, 410001, 410002].indexOf(res.data.status) !== -1) {
-          util.logout()
-          return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify }); });
-        } else
-          reject(res.data.msg || '系统错误');
-      },
-      fail: (msg) => {
-        reject('请求失败');
-      }
-    })
-  });
+  	return new Promise((reslove, reject) => {
+    	wx.request({
+      		url: Url + '/api/' + api,
+      		method: method || 'GET',
+      		header: header,
+      		data: data || {},
+      		success: (res) => {
+        		if (noVerify) {
+        		  	reslove(res.data, res);
+				} else if (res.data.status == 200) {
+        		  	reslove(res.data, res);
+			  	} else if (res.data.status == 402) {
+        		  	reslove(res.data, res);
+				} else if ([410000, 410001, 410002].indexOf(res.data.status) !== -1) {
+        		  	util.logout()
+        		  	return authLogin().then(res => { 
+						return request(api, method, data, { noAuth, noVerify }); 
+					});
+        		} else {
+				  reject(res.data.msg || '系统错误');
+				}
+      		},
+      		fail: (msg) => {
+        		reject('请求失败');
+      		}
+    	})
+  	});
 }
 
 ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
-  request[method] = (api, data, opt) => request(api, method, data, opt || {})
+  	request[method] = (api, data, opt) => request(api, method, data, opt || {})
 });
 

+ 502 - 504
view/xcx/utils/util.js

@@ -1,100 +1,105 @@
 import { TOKENNAME } from './../config.js';
-const formatTime = date => {
-  const year = date.getFullYear()
-  const month = date.getMonth() + 1
-  const day = date.getDate()
-  const hour = date.getHours()
-  const minute = date.getMinutes()
-  const second = date.getSeconds()
 
-  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
+
+const formatTime = (date) => {
+    const year = date.getFullYear()
+    const month = date.getMonth() + 1
+    const day = date.getDate()
+    const hour = date.getHours()
+    const minute = date.getMinutes()
+    const second = date.getSeconds()
+
+    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
 }
 
 const tsToString = (ts) => {
-  var date = new Date(ts * 1000);
-  var y = date.getFullYear();
-  var m = date.getMonth() + 1;
-  m = m < 10 ? ('0' + m) : m;
-  var d = date.getDate();
-  d = d < 10 ? ('0' + d) : d;
-  var h = date.getHours();
-  h=h < 10 ? ('0' + h) : h;
-  var minute = date.getMinutes();
-  minute = minute < 10 ? ('0' + minute) : minute;
-  var second=date.getSeconds();
-  second=second < 10 ? ('0' + second) : second;
-  return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 
+    var date = new Date(ts * 1000);
+    var y = date.getFullYear();
+    var m = date.getMonth() + 1;
+    m = m < 10 ? ('0' + m) : m;
+    var d = date.getDate();
+    d = d < 10 ? ('0' + d) : d;
+    var h = date.getHours();
+    h=h < 10 ? ('0' + h) : h;
+    var minute = date.getMinutes();
+    minute = minute < 10 ? ('0' + minute) : minute;
+    var second = date.getSeconds();
+    second = second < 10 ? ('0' + second) : second;
+    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second; 
 }
 
 const tsToStringDate = (ts) => {
-  var date = new Date(ts * 1000);
-  var y = date.getFullYear();
-  var m = date.getMonth() + 1;
-  m = m < 10 ? ('0' + m) : m;
-  var d = date.getDate();
-  d = d < 10 ? ('0' + d) : d;
-  return y + '-' + m + '-' + d; 
+    var date = new Date(ts * 1000);
+    var y = date.getFullYear();
+    var m = date.getMonth() + 1;
+    m = m < 10 ? ('0' + m) : m;
+    var d = date.getDate();
+    d = d < 10 ? ('0' + d) : d;
+    return y + '-' + m + '-' + d; 
 }
 
-const $h={
-  //除法函数,用来得到精确的除法结果
-  //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
-  //调用:$h.Div(arg1,arg2)
-  //返回值:arg1除以arg2的精确结果
-  Div:function (arg1, arg2) {
-    arg1 = parseFloat(arg1);
-    arg2 = parseFloat(arg2);
-    var t1 = 0, t2 = 0, r1, r2;
-    try { t1 = arg1.toString().split(".")[1].length; } catch (e) { }
-    try { t2 = arg2.toString().split(".")[1].length; } catch (e) { }
-    r1 = Number(arg1.toString().replace(".", ""));
-    r2 = Number(arg2.toString().replace(".", ""));
-    return this.Mul(r1 / r2 , Math.pow(10, t2 - t1));
-  },
-  //加法函数,用来得到精确的加法结果
-  //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
-  //调用:$h.Add(arg1,arg2)
-  //返回值:arg1加上arg2的精确结果
-  Add: function (arg1, arg2) {
-    arg2 = parseFloat(arg2);
-    var r1, r2, m;
-    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
-    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
-    m = Math.pow(100, Math.max(r1, r2));
-    return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
-  },
-  //减法函数,用来得到精确的减法结果
-  //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
-  //调用:$h.Sub(arg1,arg2)
-  //返回值:arg1减去arg2的精确结果
-  Sub: function (arg1, arg2) {
-    arg1 = parseFloat(arg1);
-    arg2 = parseFloat(arg2);
-    var r1, r2, m, n;
-    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
-    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
-    m = Math.pow(10, Math.max(r1, r2));
-    //动态控制精度长度
-    n = (r1 >= r2) ? r1 : r2;
-    return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
-  },
-  //乘法函数,用来得到精确的乘法结果
-  //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
-  //调用:$h.Mul(arg1,arg2)
-  //返回值:arg1乘以arg2的精确结果
-  Mul: function (arg1, arg2) {
-    arg1 = parseFloat(arg1);
-    arg2 = parseFloat(arg2);
-    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
-    try { m += s1.split(".")[1].length } catch (e) { }
-    try { m += s2.split(".")[1].length } catch (e) { }
-    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
-  },
-}
+const $h = {
+    //除法函数,用来得到精确的除法结果
+    //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
+    //调用:$h.Div(arg1,arg2)
+    //返回值:arg1除以arg2的精确结果
+    Div:function (arg1, arg2) {
+        arg1 = parseFloat(arg1);
+        arg2 = parseFloat(arg2);
+        var t1 = 0, t2 = 0, r1, r2;
+        try { t1 = arg1.toString().split(".")[1].length; } catch (e) { }
+        try { t2 = arg2.toString().split(".")[1].length; } catch (e) { }
+        r1 = Number(arg1.toString().replace(".", ""));
+        r2 = Number(arg2.toString().replace(".", ""));
+        return this.Mul(r1 / r2 , Math.pow(10, t2 - t1));
+    },
+
+    //加法函数,用来得到精确的加法结果
+    //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
+    //调用:$h.Add(arg1,arg2)
+    //返回值:arg1加上arg2的精确结果
+    Add: function (arg1, arg2) {
+        arg2 = parseFloat(arg2);
+        var r1, r2, m;
+        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
+        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
+        m = Math.pow(100, Math.max(r1, r2));
+        return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
+    },
+
+    //减法函数,用来得到精确的减法结果
+    //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
+    //调用:$h.Sub(arg1,arg2)
+    //返回值:arg1减去arg2的精确结果
+    Sub: function (arg1, arg2) {
+        arg1 = parseFloat(arg1);
+        arg2 = parseFloat(arg2);
+        var r1, r2, m, n;
+        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
+        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
+        m = Math.pow(10, Math.max(r1, r2));
+        //动态控制精度长度
+        n = (r1 >= r2) ? r1 : r2;
+        return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
+    },
+
+    //乘法函数,用来得到精确的乘法结果
+    //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
+    //调用:$h.Mul(arg1,arg2)
+    //返回值:arg1乘以arg2的精确结果
+    Mul: function (arg1, arg2) {
+        arg1 = parseFloat(arg1);
+        arg2 = parseFloat(arg2);
+        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
+        try { m += s1.split(".")[1].length } catch (e) { }
+        try { m += s2.split(".")[1].length } catch (e) { }
+        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
+    },
+} // $h 
 
-const formatNumber = n => {
-  n = n.toString()
-  return n[1] ? n : '0' + n
+const formatNumber = (n) => {
+    n = n.toString()
+    return n[1] ? n : '0' + n
 }
 
 /**
@@ -105,296 +110,293 @@ const formatNumber = n => {
  * @return object
  * 
 */
-const getUrlParams = (param,k,p) => {
-  if (typeof param!='string') return {};
-  k = k ? k : '&';//整体参数分隔符
-  p = p ? p : '=';//单个参数分隔符
-  var value = {};
-  if (param.indexOf(k) !== -1) {
-    param = param.split(k);
-    for (var val in param) {
-      if (param[val].indexOf(p) !== -1) {
-        var item = param[val].split(p);
+const getUrlParams = (param, k, p) => {
+    if (typeof param!='string') return {};
+    k = k ? k : '&';//整体参数分隔符
+    p = p ? p : '=';//单个参数分隔符
+    var value = {};
+    if (param.indexOf(k) !== -1) {
+        param = param.split(k);
+        for (var val in param) {
+            if (param[val].indexOf(p) !== -1) {
+                var item = param[val].split(p);
+                value[item[0]] = item[1];
+            }
+        } // for
+    } else if (param.indexOf(p) !== -1){
+        var item = param.split(p);
         value[item[0]] = item[1];
-      }
+    } else {
+        return param;
     }
-  } else if (param.indexOf(p) !== -1){
-    var item = param.split(p);
-    value[item[0]] = item[1];
-  }else{
-    return param;
-  }
-  return value;
-}
+    return value;
+} // getUrlParams
 
-const wxgetUserInfo = function()
-{
-  return new Promise((resolve, reject) =>{
-    wx.getUserProfile({
-      lang: 'zh_CN',
-      desc: '用于完善会员资料',
-      success(res) {
-        resolve(res);
-      },
-      fail(res){
-        reject(res);
-      }
-    })
-  });
-}
+const wxGetUserProfile = function() {
+    return new Promise((resolve, reject) => {
+        wx.getUserProfile({
+            lang: 'zh_CN',
+            desc: '用于完善会员资料',
+            success(res) {
+                resolve(res);
+            },
+            fail(res){
+                reject(res);
+            }
+        })
+    });
+} // wxGetUserProfile
 
-const checkLogin = function (token, expiresTime, isLog)
-{
-  if (getApp()){
-    token = getApp().globalData.token;
-    expiresTime = getApp().globalData.expiresTime;
-    isLog = getApp().globalData.isLog;
-  }
-  let res = token ? true : false;
-  let res1 = isLog;
-  let res2 = res && res1;
-  if (res2){
-    let newTime=Math.round(new Date() / 1000);
-    if (expiresTime < newTime) return false;
-  }
-  return res2;
-}
+/**
+ * 检查登录状态是否有效
+ * @param {string} token 
+ * @param {int} expiresTime 
+ * @param {bool} isLog 
+ */
+const isLoginValid = function (token, expiresTime, isLog) {
+    if (getApp()) {
+        token = getApp().globalData.token;
+        expiresTime = getApp().globalData.expiresTime;
+        isLog = getApp().globalData.isLog;
+    }
+    let res = token ? true : false;
+    let res2 = res && isLog;
+    if (res2) {
+        let newTime = Math.round(new Date() / 1000);
+        if (expiresTime < newTime) {
+			return false;
+		}
+    }
+    return res2;
+} // isLoginValid
 
-const logout = function()
-{
-  getApp().globalData.token = '';
-  getApp().globalData.isLog = false;
-}
+const logout = function() {
+    getApp().globalData.token = '';
+    getApp().globalData.isLog = false;
+} // logout
 
-const chekWxLogin = function()
-{
-  return new Promise((resolve, reject)=>{
-    if (checkLogin()) 
-      return resolve({ userinfo: getApp().globalData.userInfo, isLogin: true });
-    wx.getSetting({
-      success(res) {
-        if (!res.authSetting['scope.userInfo']) {
-          return reject({authSetting:false});
-        } else {
-          wx.getStorage({
-            key: 'cache_key',
-            success(res){
-              wxgetUserInfo().then(userInfo => {
-                userInfo.cache_key = res.data;
-                return resolve({ userInfo: userInfo, isLogin: false });
-              }).catch(res => {
-                return reject(res);
-              });
+const checkWxLogin = function() {
+    return new Promise((resolve, reject) => {
+        if (isLoginValid()) {
+            return resolve({ userinfo: getApp().globalData.userInfo, isLogin: true });
+        }
+        wx.getSetting({
+            success(res) {
+                if (!res.authSetting['scope.userInfo']) {
+                    return reject({authSetting:false});
+                } else {
+                    wx.getStorage({
+                        key: 'cache_key',
+                        success(res) {
+                            wxGetUserProfile().then(userInfo => {
+                                userInfo.cache_key = res.data;
+                                return resolve({ userInfo: userInfo, isLogin: false });
+                            }).catch(res => {
+                                return reject(res);
+                            });
+                        },
+                        fail() {
+                            getAuthCode((code) => {
+                                wxGetUserProfile().then(userInfo => {
+                                    userInfo.code = code;
+                                    return resolve({ userInfo: userInfo, isLogin: false });
+                                }).catch(res => {
+                                    return reject(res);
+                                })
+                            });
+                        }
+                    })
+         
+                }
             },
-            fail(){
-              getCodeLogin((code) => {
-                wxgetUserInfo().then(userInfo => {
-                  userInfo.code = code;
-                  return resolve({ userInfo: userInfo, isLogin: false });
-                }).catch(res => {
-                  return reject(res);
-                })
-              });
+            fail(res) {
+                return reject(res);
             }
-          })
-         
-        }
-      },
-      fail(res) {
-        return reject(res);
-      }
+        })
     })
-  })
-}
+} // checkWxLogin
 
 
 /**
- * 
  * 授权过后自动登录
-*/
-const autoLogin = function()
-{
-  return new Promise((resolve, reject) => {
-    wx.getStorage({
-      key: 'cache_key',
-      success(res) {
-        wxgetUserInfo().then(userInfo => {
-          userInfo.cache_key = res.data;
-          return resolve(userInfo);
-        }).catch(res => {
-          return reject(res);
-        })
-      },
-      fail(){
-        getCodeLogin((code) => {
-          wxgetUserInfo().then(userInfo => {
-            userInfo.code = code;
-            return resolve(userInfo);
-          }).catch(res => {
-            return reject(res);
-          })
+ */
+const autoLogin = function() {
+    return new Promise((resolve, reject) => {
+        wx.getStorage({
+            key: 'cache_key',
+            success(res) {
+                wxGetUserProfile().then(userInfo => {
+                    userInfo.cache_key = res.data;
+                    return resolve(userInfo);
+                }).catch(res => {
+                    return reject(res);
+                })
+             },
+            fail() {
+                getAuthCode((code) => {
+                    wxGetUserProfile().then(userInfo => {
+                        userInfo.code = code;
+                        return resolve(userInfo);
+                    }).catch(res => {
+                        return reject(res);
+                    })
+                });
+            }
         });
-      }
-    });
-  })
-}
+    })
+} // autoLogin
+
+const getAuthCode = function(successFn) {
+    wx.login({
+        success(res){
+            successFn(res);
+        }
+    })
+} // getAuthCode
 
-const getCodeLogin = function(successFn)
-{
-  wx.login({
-    success(res){
-      successFn(res);
+/**
+ * 合并数组
+ */
+const SplitArray = function (list, sp) {
+    if (typeof list != 'object') return [];
+    if (sp === undefined) sp = [];
+    for (var i = 0; i < list.length; i++) {
+        sp.push(list[i]);
     }
-  })
-}
+    return sp;
+} // SplitArray
 
-/*
-* 合并数组
-*/
-const SplitArray= function (list, sp) {
-  if (typeof list != 'object') return [];
-  if (sp === undefined) sp = [];
-  for (var i = 0; i < list.length; i++) {
-    sp.push(list[i]);
-  }
-  return sp;
-}
+/**
+ * opt  object | string
+ * to_url object | string
+ * 例:
+ * this.Tips('/pages/test/test'); 跳转不提示
+ * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
+ * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
+ * tab=1 一定时间后跳转至 table上
+ * tab=2 一定时间后跳转至非 table上
+ * tab=3 一定时间后返回上页面
+ * tab=4 关闭所有页面跳转至非table上
+ * tab=5 关闭当前页面跳转至table上
+ */
+const Tips = function (opt, to_url) {
+    if (typeof opt == 'string') {
+        to_url = opt;
+        opt = {};
+    }
+    var title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000;
+    if (title) {
+        wx.showToast({ title: title, icon: icon, duration: endtime })
+    }
+    if (to_url != undefined) {
+        if (typeof to_url == 'object') {
+            var tab = to_url.tab || 1, url = to_url.url || '';
+            switch (tab) {
+                case 1:
+                    //一定时间后跳转至 table
+                    setTimeout(function () {
+                        wx.switchTab({ url: url })
+                    }, endtime);
+                    break;
+                case 2:
+                    //跳转至非table页面
+                    setTimeout(function () {
+                      wx.navigateTo({ url: url })
+                    }, endtime);
+                    break;
+                case 3:
+                    //返回上页面
+                    setTimeout(function () {
+                      wx.navigateBack({ delta: parseInt(url) })
+                    }, endtime);
+                    break;
+                case 4:
+                    //关闭当前所有页面跳转至非table页面
+                    setTimeout(function () {
+                      wx.reLaunch({ url: url })
+                    }, endtime);
+                    break;
+                case 5:
+                    //关闭当前页面跳转至非table页面
+                    setTimeout(function () {
+                      wx.redirectTo({ url: url })
+                    }, endtime);
+                    break;
+            } // switch
 
- /**
-   * opt  object | string
-   * to_url object | string
-   * 例:
-   * this.Tips('/pages/test/test'); 跳转不提示
-   * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
-   * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
-   * tab=1 一定时间后跳转至 table上
-   * tab=2 一定时间后跳转至非 table上
-   * tab=3 一定时间后返回上页面
-   * tab=4 关闭所有页面跳转至非table上
-   * tab=5 关闭当前页面跳转至table上
-   */
-const Tips= function (opt, to_url) {
-  if (typeof opt == 'string') {
-    to_url = opt;
-    opt = {};
-  }
-  var title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000;
-  if (title) wx.showToast({ title: title, icon: icon, duration: endtime })
-  if (to_url != undefined) {
-    if (typeof to_url == 'object') {
-      var tab = to_url.tab || 1, url = to_url.url || '';
-      switch (tab) {
-        case 1:
-          //一定时间后跳转至 table
-          setTimeout(function () {
-            wx.switchTab({
-              url: url
-            })
-          }, endtime);
-          break;
-        case 2:
-          //跳转至非table页面
-          setTimeout(function () {
-            wx.navigateTo({
-              url: url,
-            })
-          }, endtime);
-          break;
-        case 3:
-          //返回上页面
-          setTimeout(function () {
-            wx.navigateBack({
-              delta: parseInt(url),
-            })
-          }, endtime);
-          break;
-        case 4:
-          //关闭当前所有页面跳转至非table页面
-          setTimeout(function () {
-            wx.reLaunch({
-              url: url,
-            })
-          }, endtime);
-          break;
-        case 5:
-          //关闭当前页面跳转至非table页面
-          setTimeout(function () {
-            wx.redirectTo({
-              url: url,
-            })
-          }, endtime);
-          break;
-      }
+        } else if (typeof to_url == 'function'){
+            setTimeout(function () { 
+                to_url && to_url();
+            }, endtime);
+        } else {
+            //没有提示时跳转不延迟
+            setTimeout(function () {
+                wx.navigateTo({ url: to_url })
+            }, title ? endtime : 0);
+        }
+    } // if
+} // Tips
 
-    }else if(typeof to_url == 'function'){
-      setTimeout(function () { 
-        to_url && to_url();
-      }, endtime);
-    }else{
-      //没有提示时跳转不延迟
-      setTimeout(function () {
-        wx.navigateTo({
-          url: to_url,
-        })
-      }, title ? endtime : 0);
+/**
+ * 单图上传
+ * @param object opt
+ * @param callable successCallback 成功执行方法 data 
+ * @param callable errorCallback 失败执行方法 
+ */
+const uploadImageOne = function (opt, successCallback, errorCallback) {
+    if (typeof opt === 'string') {
+        var url = opt;
+        opt = {};
+        opt.url = url;
     }
-  }
-}
-/*
-* 单图上传
-* @param object opt
-* @param callable successCallback 成功执行方法 data 
-* @param callable errorCallback 失败执行方法 
-*/
-const uploadImageOne=function (opt, successCallback, errorCallback) {
-  if (typeof opt === 'string') {
-    var url = opt;
-    opt = {};
-    opt.url = url;
-  }
-  var count = opt.count || 1, sizeType = opt.sizeType || ['compressed'], sourceType = opt.sourceType || ['album', 'camera'],
-    is_load = opt.is_load || true, uploadUrl = opt.url || '', inputName = opt.name || 'pics';
-  wx.chooseImage({
-    count: count,  //最多可以选择的图片总数  
-    sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
-    sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
-    success: function (res) {
-      //启动上传等待中...  
-      wx.showLoading({
-        title: '图片上传中',
-      });
-      wx.uploadFile({
-        url: getApp().globalData.url+'/api/'+uploadUrl,
-        filePath: res.tempFilePaths[0],
-        name: inputName,
-        formData: {
-          'filename': inputName
-        },
-        header: {
-          "Content-Type": "multipart/form-data",
-          [TOKENNAME]: 'Bearer '+getApp().globalData.token
-        },
+    var count = opt.count || 1, 
+        sizeType = opt.sizeType || ['compressed'], 
+        sourceType = opt.sourceType || ['album', 'camera'],
+        is_load = opt.is_load || true, 
+        uploadUrl = opt.url || '', 
+        inputName = opt.name || 'pics';
+    wx.chooseImage({
+        count: count,  //最多可以选择的图片总数  
+        sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
+        sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
         success: function (res) {
-          wx.hideLoading();
-          if (res.statusCode == 403) {
-            Tips({ title: res.data });
-          } else {
-            var data = res.data ? JSON.parse(res.data) : {};
-            if (data.status == 200) {
-              successCallback && successCallback(data)
-            } else {
-              errorCallback && errorCallback(data);
-              Tips({ title: data.msg });
-            }
-          }
-        }, fail: function (res) {
-          wx.hideLoading();
-          Tips({ title: '上传图片失败' });
+            //启动上传等待中...  
+            wx.showLoading({
+              title: '图片上传中',
+            });
+             wx.uploadFile({
+                url: getApp().globalData.url+'/api/'+uploadUrl,
+                filePath: res.tempFilePaths[0],
+                name: inputName,
+                formData: {
+                    'filename': inputName
+                },
+                header: {
+                    "Content-Type": "multipart/form-data",
+                    [TOKENNAME]: 'Bearer '+getApp().globalData.token
+                 },
+                success: function (res) {
+                    wx.hideLoading();
+                    if (res.statusCode == 403) {
+                        Tips({ title: res.data });
+                    } else {
+                        var data = res.data ? JSON.parse(res.data) : {};
+                        if (data.status == 200) {
+                            successCallback && successCallback(data)
+                        } else {
+                            errorCallback && errorCallback(data);
+                             Tips({ title: data.msg });
+                        }
+                    }
+                }, 
+                fail: function (res) {
+                    wx.hideLoading();
+                    Tips({ title: '上传图片失败' });
+                }
+            }) // uploadFile
         }
-      })
-    }
-  })
-}
+    }) // wx.chooseImage
+} // uploadImageOne
 
 /**
  * 移除数组中的某个数组并组成新的数组返回
@@ -402,53 +404,53 @@ const uploadImageOne=function (opt, successCallback, errorCallback) {
  * @param int index 需要移除的数组的键值
  * @param string | int 值
  * @return array
- * 
-*/
-const ArrayRemove= (array,index,value) =>{
-  const valueArray=[];
-  if (array instanceof Array){
-    for (let i = 0; i < array.length;i++){
-      if (typeof index == 'number' && array[index] != i){
-        valueArray.push(array[i]);
-      } else if (typeof index == 'string' && array[i][index] != value){
-        valueArray.push(array[i]);
-      }
-    }
-  }
-  return valueArray;
-}
- /**
-  * 生成海报获取文字
-  * @param string text 为传入的文本
-  * @param int num 为单行显示的字节长度
-  * @return array 
  */
-const textByteLength = (text, num) =>{
-  let strLength = 0;
-  let rows = 1;
-  let str = 0;
-  let arr = [];
-  for (let j = 0; j < text.length; j++) {
-    if (text.charCodeAt(j) > 255) {
-      strLength += 2;
-      if (strLength > rows * num) {
-        strLength++;
-        arr.push(text.slice(str, j));
-        str = j;
-        rows++;
-      }
-    } else {
-      strLength++;
-      if (strLength > rows * num) {
-        arr.push(text.slice(str, j));
-        str = j;
-        rows++;
-      }
+const ArrayRemove = (array,index,value) => {
+    const valueArray=[];
+    if (array instanceof Array){
+        for (let i = 0; i < array.length; i++) {
+            if (typeof index == 'number' && array[index] != i){
+                valueArray.push(array[i]);
+            } else if (typeof index == 'string' && array[i][index] != value) {
+                    valueArray.push(array[i]);
+            }
+         }
     }
-  }
-  arr.push(text.slice(str, text.length));
-  return [strLength, arr, rows]   //  [处理文字的总字节长度,每行显示内容的数组,行数]
-}
+    return valueArray;
+} // ArrayRemove
+
+/**
+ * 生成海报获取文字
+ * @param string text 为传入的文本
+ * @param int num 为单行显示的字节长度
+ * @return array 
+ */
+const textByteLength = (text, num) => {
+    let strLength = 0;
+    let rows = 1;
+    let str = 0;
+    let arr = [];
+    for (let j = 0; j < text.length; j++) {
+        if (text.charCodeAt(j) > 255) {
+            strLength += 2;
+            if (strLength > rows * num) {
+                strLength++;
+                arr.push(text.slice(str, j));
+                str = j;
+                rows++;
+            }
+        } else {
+            strLength++;
+            if (strLength > rows * num) {
+                arr.push(text.slice(str, j));
+                str = j;
+                rows++;
+            }
+        }
+    } // for
+    arr.push(text.slice(str, text.length));
+    return [strLength, arr, rows]   //  [处理文字的总字节长度,每行显示内容的数组,行数]
+} // textByteLength
 
 /**
  * 获取分享海报
@@ -456,70 +458,66 @@ const textByteLength = (text, num) =>{
  * @param string store_name 素材文字
  * @param string price 价格
  * @param function successFn 回调函数
- * 
- * 
-*/
-const PosterCanvas = (arr2, store_name, price,successFn) =>{
-  wx.showLoading({ title: '海报生成中', mask: true });
-  const ctx = wx.createCanvasContext('myCanvas');
-  ctx.clearRect(0, 0, 0, 0);
-  /**
-   * 只能获取合法域名下的图片信息,本地调试无法获取
-   * 
-  */
-  wx.getImageInfo({
-    src: arr2[0],
-    success: function (res) {
-      const WIDTH = res.width;
-      const HEIGHT = res.height;
-      ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
-      ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
-      ctx.save();
-      let r = 90;
-      let d = r * 2;
-      let cx = 40;
-      let cy = 990;
-      ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
-      ctx.clip();
-      ctx.drawImage(arr2[2], cx, cy, d, d);
-      ctx.restore();
-      const CONTENT_ROW_LENGTH = 40;
-      let [contentLeng, contentArray, contentRows] = textByteLength(store_name, CONTENT_ROW_LENGTH);
-      if (contentRows > 2) {
-        contentRows =2;
-        let textArray=contentArray.slice(0,2);
-        textArray[textArray.length-1]+='……';
-        contentArray = textArray;
-      }
-      ctx.setTextAlign('center');
-      ctx.setFontSize(32);
-      let contentHh = 32 * 1.3;
-      for (let m = 0; m < contentArray.length; m++) {
-        ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
-      }
-      ctx.setTextAlign('center')
-      ctx.setFontSize(48);
-      ctx.setFillStyle('red');
-      ctx.fillText('¥' + price, WIDTH / 2, 860 + contentHh);
-      ctx.draw(true, function () {
-        wx.canvasToTempFilePath({
-          canvasId: 'myCanvas',
-          fileType: 'png',
-          destWidth: WIDTH,
-          destHeight: HEIGHT,
-          success: function (res) {
+ */
+const PosterCanvas = (arr2, store_name, price,successFn) => {
+    wx.showLoading({ title: '海报生成中', mask: true });
+    const ctx = wx.createCanvasContext('myCanvas');
+    ctx.clearRect(0, 0, 0, 0);
+
+    //只能获取合法域名下的图片信息,本地调试无法获取
+    wx.getImageInfo({
+        src: arr2[0],
+        success: function (res) {
+            const WIDTH = res.width;
+            const HEIGHT = res.height;
+            ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
+            ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
+            ctx.save();
+            let r = 90;
+            let d = r * 2;
+            let cx = 40;
+            let cy = 990;
+            ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
+            ctx.clip();
+            ctx.drawImage(arr2[2], cx, cy, d, d);
+            ctx.restore();
+            const CONTENT_ROW_LENGTH = 40;
+            let [contentLeng, contentArray, contentRows] = textByteLength(store_name, CONTENT_ROW_LENGTH);
+            if (contentRows > 2) {
+                contentRows =2;
+                let textArray=contentArray.slice(0,2);
+                textArray[textArray.length-1] += '……';
+                contentArray = textArray;
+            }
+            ctx.setTextAlign('center');
+            ctx.setFontSize(32);
+            let contentHh = 32 * 1.3;
+            for (let m = 0; m < contentArray.length; m++) {
+                ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
+            }
+            ctx.setTextAlign('center')
+            ctx.setFontSize(48);
+            ctx.setFillStyle('red');
+            ctx.fillText('¥' + price, WIDTH / 2, 860 + contentHh);
+            ctx.draw(true, function () {
+                wx.canvasToTempFilePath({
+                    canvasId: 'myCanvas',
+                    fileType: 'png',
+                    destWidth: WIDTH,
+                    destHeight: HEIGHT,
+                    success: function (res) {
+                        wx.hideLoading();
+                        successFn && successFn(res.tempFilePath);
+                    }
+                })
+            });
+        },
+        fail: function() {
             wx.hideLoading();
-            successFn && successFn(res.tempFilePath);
-          }
-        })
-      });
-    },
-    fail:function(){
-      wx.hideLoading();
-      Tips({title:'无法获取图片信息'});
-    }
-  })
-}
+            Tips({title:'无法获取图片信息'});
+        }
+    }) // wx.getImageInfo
+} // PosterCanvas
 
 /**
  * 数字变动动画效果
@@ -527,52 +525,52 @@ const PosterCanvas = (arr2, store_name, price,successFn) =>{
  * @param float ChangeNumber 变动后的数字
  * @param object that 当前this
  * @param string name 变动字段名称
- * */
+ */
 const AnimationNumber = (BaseNumber,ChangeNumber,that,name) => {
-  var difference = $h.Sub(ChangeNumber,BaseNumber) //与原数字的差
-  var absDifferent = Math.abs(difference) //差取绝对值
-  var changeTimes = absDifferent < 6 ? absDifferent : 6 //最多变化6次
-  var changeUnit = absDifferent < 6 ? 1 : Math.floor(difference/6);
-  // 依次变化
-  for (var i = 0; i < changeTimes; i += 1) {
-    // 使用闭包传入i值,用来判断是不是最后一次变化
-    (function (i) {
-      setTimeout(() => {
-        that.setData({
-          [name]: $h.Add(BaseNumber,changeUnit)
-        })
-        // 差值除以变化次数时,并不都是整除的,所以最后一步要精确设置新数字
-        if (i == changeTimes - 1) {
-          that.setData({
-            [name]: $h.Add(BaseNumber, difference)
-          })
-        }
-      }, 100 * (i + 1))
-    })(i)
-  }
-}
+    var difference = $h.Sub(ChangeNumber,BaseNumber) //与原数字的差
+    var absDifferent = Math.abs(difference) //差取绝对值
+    var changeTimes = absDifferent < 6 ? absDifferent : 6 //最多变化6次
+    var changeUnit = absDifferent < 6 ? 1 : Math.floor(difference/6);
+    // 依次变化
+    for (var i = 0; i < changeTimes; i += 1) {
+        // 使用闭包传入i值,用来判断是不是最后一次变化
+        (function (i) {
+            setTimeout(() => {
+                that.setData({
+                    [name]: $h.Add(BaseNumber,changeUnit)
+                })
+                // 差值除以变化次数时,并不都是整除的,所以最后一步要精确设置新数字
+                if (i == changeTimes - 1) {
+                    that.setData({
+                        [name]: $h.Add(BaseNumber, difference)
+                    })
+                }
+            }, 100 * (i + 1))
+         })(i)
+    } // for
+} // AnimationNumber
 
 const strip = (num, precision = 12) => {
-  return +parseFloat(num.toPrecision(precision));
+    return +parseFloat(num.toPrecision(precision));
 }
 
 module.exports = {
-  formatTime: formatTime,
-  tsToString: tsToString,
-  tsToStringDate: tsToStringDate,
-  strip: strip,
-  $h:$h,
-  Tips: Tips,
-  uploadImageOne: uploadImageOne,
-  SplitArray: SplitArray,
-  ArrayRemove: ArrayRemove,
-  PosterCanvas: PosterCanvas,
-  AnimationNumber: AnimationNumber,
-  getUrlParams: getUrlParams,
-  chekWxLogin: chekWxLogin,
-  getCodeLogin: getCodeLogin,
-  checkLogin: checkLogin,
-  wxgetUserInfo: wxgetUserInfo,
-  autoLogin: autoLogin,
-  logout: logout
+  	formatTime: formatTime,
+  	tsToString: tsToString,
+  	tsToStringDate: tsToStringDate,
+  	strip: strip,
+  	$h:$h,
+  	Tips: Tips,
+  	uploadImageOne: uploadImageOne,
+  	SplitArray: SplitArray,
+  	ArrayRemove: ArrayRemove,
+  	PosterCanvas: PosterCanvas,
+  	AnimationNumber: AnimationNumber,
+  	getUrlParams: getUrlParams,
+  	checkWxLogin: checkWxLogin,
+  	getAuthCode: getAuthCode,
+  	isLoginValid: isLoginValid,
+  	wxGetUserProfile: wxGetUserProfile,
+  	autoLogin: autoLogin,
+  	logout: logout
 }