Bladeren bron

feature: 处理登录异常问题

Damon 8 maanden geleden
bovenliggende
commit
c5bbd2afd8
6 gewijzigde bestanden met toevoegingen van 211 en 266 verwijderingen
  1. 42 127
      pages/index/index.js
  2. 2 2
      pages/index/index.wxml
  3. 65 87
      pages/login/login.js
  4. 17 0
      utils/strings.js
  5. 17 0
      utils/time_util.js
  6. 68 50
      utils/util.js

+ 42 - 127
pages/index/index.js

@@ -1,11 +1,11 @@
 const app = getApp();
 const {
   getBanner,
-  login,
   listByDevice
 } = require('../../utils/api.js');
 
 import timeUtil from '../../utils/time_util.js';
+import strings from '../../utils/strings.js';
 
 Page({
   data: {
@@ -14,9 +14,8 @@ Page({
       title: 'OhPlay', //导航栏 中间的标题
     },
     ///下午好
+    isLogin: false,
     greeting: "",
-    ///用来判断是否已登录
-    phone: "",
     bannerList: [],
     autoplay: true,
     interval: 3000, // 切换时间间隔
@@ -34,7 +33,6 @@ Page({
     channelData: [],
     deviceList: [],
     deviceListIndex: null,
-    showLogin: false,
     isOneLoading: true,
     uid: null,
     isSetWake: false,
@@ -44,33 +42,24 @@ Page({
     ////我的界面
     loginStatus: true,
     nickName: "未登录",
-    userPic: './../../img/head_pic.png',
-    islogin: false,
+    userPic: './../../img/head_pic.png'
   },
 
   onLoad(options) {
     var that = this;
-    that.onGreetLoad();
-    that.onBannerLoad();
+    that.onUserInfoLoad();
     that.onHomeLoad();
-    that.onMeLoad();
+    that.onBannerLoad();
   },
 
   onShow() {
     var that = this;
     that.onHomeShow();
-    that.onMeLoad();
     that.onBannerShow();
   },
 
-
-
   onHomeLoad() {
     var that = this;
-    // wx.showLoading({
-    //   title: '加载中',
-    // });
-
     const str = setTimeout(() => {
       clearTimeout(str);
       if (that.data.isOneLoading) {
@@ -79,42 +68,6 @@ Page({
         });
       }
     }, 500);
-
-    // 获取缓存的频道数据
-    wx.getStorage({
-      key: "channelData",
-      success(res) {
-        that.setData({
-          channelData: res.data
-        })
-      }
-    });
-    // 登录
-    that.login();
-  },
-
-  onMeLoad() {
-    var that = this;
-    wx.getStorage({
-      key: "userInfo",
-      success(res) {
-        var phone = res.data.phone;
-        if (!phone) {
-          return;
-        };
-
-        var nickName = res.data.nickName || "";
-        var greeting = that.getGreetBuNickName(nickName);
-
-        that.setData({
-          phone: phone,
-          greeting: greeting,
-          nickName: nickName,
-          userPic: res.data.headUrl || "",
-          islogin: true,
-        });
-      }
-    })
   },
 
   onHomeShow() {
@@ -127,9 +80,6 @@ Page({
           if (that.data.thisDeviceMac !== null) {
             app.unsubscribe(`/${that.data.thisDeviceMac}/user/pub_response`);
           };
-          that.setData({
-            showLogin: true,
-          });
         },
         success() {
           if (app.globalData.newDeviceId) {
@@ -144,54 +94,9 @@ Page({
     };
   },
 
-  ////开始是home的
-  login() {
-    var that = this;
-    wx.login({
-      success: res => {
-        let phone = undefined;
-        try {
-          var value = wx.getStorageSync('userInfo')
-          if (value) {
-            phone = value.phone || undefined;
-          };
-        } catch (e) {
-          // Do something when catch error
-        };
-        // 请求登录
-        login({
-          code: res.code,
-          phone
-        }).then((res) => {
-
-          app.globalData.userInfo = res;
-          wx.setStorage({
-            key: "userInfo",
-            data: res
-          });
-          // 需要用授权登录
-          if ((res.isNewUser && res.isNewUser === true) || !phone) {
-            that.setData({
-              showLogin: true,
-            });
-            return;
-          };
-          // 获取设备本地数据
-          that.getDeviceData();
+  ////登录界面登录成功回调用
+  loginSucceed() {
 
-          that.setData({
-            showLogin: false,
-          });
-          wx.setStorage({
-            key: "token",
-            data: JSON.stringify({
-              id: res.userId,
-              token: res.accessToken,
-            }),
-          });
-        });
-      },
-    })
   },
 
   ///开始时home的
@@ -582,7 +487,7 @@ Page({
 
   goMeLogin() {
     var that = this;
-    if (that.data.islogin) {
+    if (that.data.isLogin) {
       // 退出登录
       wx.removeStorage({
         key: 'userInfo',
@@ -591,15 +496,11 @@ Page({
           var greeting = that.getGreetBuNickName(nickName);
 
           that.setData({
-            phone: "",
+            isLogin: false,
             greeting: greeting,
-            islogin: false,
             nickName: nickName,
             userPic: "./../../img/head_pic.png",
           });
-          // wx.switchTab({
-          //   url: `./../index/index`
-          // });
         }
       });
       wx.removeStorage({
@@ -615,9 +516,7 @@ Page({
 
   addDevice() {
     var that = this;
-    var phone = that.data.phone;
-    var showLogin = that.data.showLogin;
-    if (phone == "" || showLogin) {
+    if (!that.data.isLogin) {
       wx.navigateTo({
         url: './../login/login'
       });
@@ -917,13 +816,37 @@ Page({
   },
 
   ///******************************* 可折叠 ********************************************///
-  onGreetLoad() {
+  onUserInfoLoad() {
     var that = this;
-    var nickName = that.data.nickName;
-    var greeting = that.getGreetBuNickName(nickName);
-    that.setData({
-      greeting: greeting
-    });
+    var userInfo = wx.getStorageSync("userInfo") || "";
+    if (!strings.isEmpty(userInfo)) {
+      var phone = userInfo.phone;
+      if (!phone) {
+        return;
+      };
+
+      var nickName = userInfo.nickname || "";
+      var greeting = that.getGreetBuNickName(nickName);
+      // 获取缓存的频道数据
+      var channelData = wx.getStorageSync("channelData") || "";
+      if (!strings.isEmpty(channelData)) {
+        that.setData({
+          channelData: channelData,
+          greeting: greeting,
+          nickName: nickName,
+          userPic: userInfo.headUrl || "",
+          isLogin: true,
+        })
+      } else {
+        that.setData({
+          greeting: greeting,
+          nickName: nickName,
+          userPic: userInfo.headUrl || "",
+          isLogin: true,
+        });
+      }
+      that.getDeviceData();
+    }
   },
 
   getGreetBuNickName(nickName) {
@@ -943,6 +866,7 @@ Page({
       });
     }
   },
+
   onBannerShow() {
     var that = this;
     getBanner({}).then((res) => {
@@ -952,13 +876,4 @@ Page({
       wx.setStorageSync("homeBanner", res);
     })
   },
-
-})
-
-
-// updataClone() {
-//   var that = this;
-//   that.setData({
-//     newVersion: false
-//   })
-// },
+})

+ 2 - 2
pages/index/index.wxml

@@ -152,8 +152,8 @@
             </view>
           </view>
         </view>
-        <view wx:if="{{islogin}}" class="login">
-          <view bindtap="goMeLogin" class="{{!islogin ? 'action' : ''}}">{{islogin ? '退出登录' : "登录"}}</view>
+        <view wx:if="{{isLogin}}" class="login">
+          <view bindtap="goMeLogin" class="{{!isLogin ? 'action' : ''}}">{{isLogin ? '退出登录' : "登录"}}</view>
         </view>
       </view>
     </view>

+ 65 - 87
pages/login/login.js

@@ -1,13 +1,12 @@
 // pages/login/login.ts;
 const app = getApp();
 const {
+  login,
   register
 } = require('./../../utils/api.js')
+
 Page({
 
-  /**
-   * 页面的初始数据
-   */
   data: {
     nvabarData: {
       showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
@@ -16,73 +15,20 @@ Page({
     isYs: false,
     isAgree: false,
   },
+
   egree() {
     this.setData({
       isAgree: !this.data.isAgree
     })
   },
+
   goabout(e) {
     wx.navigateTo({
       url: './../aboutInfo/aboutInfo?type=' + e.currentTarget.dataset.index,
     })
   },
-  /**
-   * 生命周期函数--监听页面加载
-   */
-  onLoad() {
-
-  },
-
-  /**
-   * 生命周期函数--监听页面初次渲染完成
-   */
-  onReady() {
-
-  },
-
-  /**
-   * 生命周期函数--监听页面显示
-   */
-  onShow() {
-
-  },
-
-  /**
-   * 生命周期函数--监听页面隐藏
-   */
-  onHide() {
-
-  },
 
-  /**
-   * 生命周期函数--监听页面卸载
-   */
-  onUnload() {
-
-  },
-
-  /**
-   * 页面相关事件处理函数--监听用户下拉动作
-   */
-  onPullDownRefresh() {
-
-  },
-
-  /**
-   * 页面上拉触底事件的处理函数
-   */
-  onReachBottom() {
-
-  },
-
-  /**
-   * 用户点击右上角分享
-   */
-  onShareAppMessage() {
-
-  },
   getPhoneNumber(e) {
-    console.log(e)
     if (e.detail.errMsg != "getPhoneNumber:ok") {
       wx.showToast({
         title: "获取手机号失败",
@@ -91,39 +37,71 @@ Page({
       });
       return;
     }
-    if (e.detail.code) {
-      register({
-        openid: app.globalData.userInfo.openid,
-        code: e.detail.code,
-      }).then((res) => {
 
-        wx.showToast({
-          title: "登陆成功",
-          icon: 'success',
-          duration: 2000
-        });
-        wx.setStorage({
-          key: "userInfo",
-          data: res,
-          success() {
-            setTimeout(() => {
-              // 重新登录
-              getCurrentPages()[0].login();
-              // wx.redirectTo({
-              //   url: './../deviceConnect0/deviceConnect0?isLognlink=0'
-              // });
-              wx.redirectTo({
-                url: './../deviceList/deviceList'
+    var phoneCode = e.detail.code;
+    if (phoneCode) {
+      wx.login({
+        success: res1 => {
+          wx.showLoading({
+            title: '加载中',
+          });
+
+          // {"openid":"oZHPJ5JcNem2och3ToaocggmUENw","unionid":null,"userId":null,"deviceUid":null,"accessToken":null,"phone":null,"headUrl":"","nickname":"","isNewUser":true}
+          login({
+            code: res1.code,
+            unShowLoad: true,
+          }).then((res2) => {
+            register({
+              openid: res2.openid,
+              code: phoneCode,
+              unShowLoad: true,
+            }).then((res3) => {
+              // {"openid":"oZHPJ5JcNem2och3ToaocggmUENw","userId":933625,"deviceUid":1,"accessToken":"PUK8WVnLbIFsWYjSteitmg3OhllpbUMvIPKUtfJgwhRtpl1jx4Fm1NkHQIiZYhHz","phone":"15915390284","headUrl":"https://music-play.oss-cn-shenzhen.aliyuncs.com/user/headurl/20220316194115703366576.png","nickname":"儿子的爸爸叫啥"}
+              wx.login({
+                success: res4 => {
+                  // {"openid":"oZHPJ5JcNem2och3ToaocggmUENw","unionid":null,"userId":933625,"deviceUid":1,"accessToken":"kaKdNAb9eO0iUGKsaLP18UE0wRwrvoCr4opjNC3AieaigH4Fu1IspQKi2zTPgLNG","phone":"15915390284","headUrl":"https://music-play.oss-cn-shenzhen.aliyuncs.com/user/headurl/20220316194115703366576.png","nickname":"儿子的爸爸叫啥","isNewUser":false}
+                  login({
+                    code: res4.code,
+                    phone: res3.phone,
+                  }).then((res5) => {
+                    wx.showToast({
+                      title: "登录成功",
+                      icon: 'success',
+                      duration: 2000
+                    });
+                    app.globalData.userInfo = res5;
+                    wx.setStorageSync("userInfo", res5);
+                    wx.setStorageSync("token", JSON.stringify({
+                      id: res5.userId,
+                      token: res5.accessToken,
+                    }));
+                    getCurrentPages()[0].onUserInfoLoad();
+                    setTimeout(() => {
+                      wx.redirectTo({
+                        url: './../deviceList/deviceList'
+                      });
+                    }, 2000);
+
+                    // 需要用授权登录
+                    // if ((res.isNewUser && res.isNewUser === true) || !phone) {
+                    //   return;
+                    // };
+                  });
+                },
+                fail(fail4) {
+                  wx.hideLoading();
+                },
               });
-              // wx.navigateTo({
-              //   url: './../deviceList/deviceList'
-              // });
-            }, 2000);
-          }
-        });
-      })
+            });
+          });
+        },
+        fail(fail1) {
+          wx.hideLoading();
+        },
+      });
     }
   },
+
   notlogin() {
     wx.showToast({
       title: '请同意协议',

+ 17 - 0
utils/strings.js

@@ -0,0 +1,17 @@
+module.exports = {
+  isEmpty: isEmpty,
+  length: length,
+  isTrue: isTrue,
+}
+
+function isEmpty(e) {
+  return e == undefined || e.length == 0 || e == [];
+};
+
+function length(e) {
+  return e.length;
+};
+
+function isTrue(e) {
+  return e != undefined && e == true;
+};

+ 17 - 0
utils/time_util.js

@@ -0,0 +1,17 @@
+module.exports = {
+  getGreet: getGreet
+}
+
+function getGreet() {
+  const now = new Date();
+  const hour = now.getHours();
+  var greeting;
+  if (hour >= 5 && hour < 12) {
+    greeting = '上午好';
+  } else if (hour >= 12 && hour < 18) {
+    greeting = '下午好';
+  } else {
+    greeting = '晚上好';
+  }
+  return greeting;
+};

+ 68 - 50
utils/util.js

@@ -1,10 +1,18 @@
 // const { baseUrl } = require('./env.js').prod; // 正式
-const { baseUrl } = require('./env.js').test; // 测试
+const {
+  baseUrl
+} = require('./env.js').test; // 测试
 
 // token
 let Authorization = "";
-const jsonType = {"content-type":"application/json"}
-const urlencodeType = {"content-type":"application/x-www-form-urlencoded"}
+const jsonType = {
+  "content-type": "application/json"
+}
+const urlencodeType = {
+  "content-type": "application/x-www-form-urlencoded"
+}
+
+import strings from '../utils/strings.js';
 
 // 错误类型
 let statusCode = {
@@ -47,9 +55,8 @@ function _show_error(error_code) {
 }
 
 // 
-function request(url,data={},method="GET", header=urlencodeType, isToken=true) {
-
-  if(isToken) {
+function request(url, data = {}, method = "GET", header = urlencodeType, isToken = true) {
+  if (isToken) {
     try {
       var value = wx.getStorageSync('token')
       if (value) {
@@ -61,53 +68,64 @@ function request(url,data={},method="GET", header=urlencodeType, isToken=true) {
     }
   }
   // 拼接地址
-  let fullurl = `${baseUrl}${url}`
+  let fullurl = `${baseUrl}${url}`;
+
   //返回异步操作成功的结果和返回异步操作失败的结果
-  wx.showLoading({
-    title: '加载中',
-  });
-  return new Promise((resolve,reject)=>{
-      wx.request({
-        url: fullurl,
-        method,
-        data,
-        header:Object.assign({
-          "content-type":"application/x-www-form-urlencoded",
-          "appid": "wx08f94a3e90881910",
-          "Authorization": isToken ? Authorization : undefined
-        }, header),
-        success(res){
-          // console.log("接口:",fullurl, res)
+  console.log("gadfadfqwwerqewrqwr===aaaaa=" + data.disShowLoading);
+  if (!strings.isTrue(data.unShowLoad)) {
+    console.log("gadfadfqwwerqewrqwr===bbb=" + data.disShowLoading);
+    wx.showLoading({
+      title: '加载中',
+    });
+  }
+
+  return new Promise((resolve, reject) => {
+    wx.request({
+      url: fullurl,
+      method,
+      data,
+      header: Object.assign({
+        "content-type": "application/x-www-form-urlencoded",
+        "appid": "wx08f94a3e90881910",
+        "Authorization": isToken ? Authorization : undefined
+      }, header),
+      success(res) {
+        // console.log("接口:",fullurl, res)
+        if (res.statusCode !== 200) {
           wx.hideLoading();
-          if(res.statusCode !== 200 ) {
-            wx.showToast({
-              "title": "请求错误",
-              "icon": "error",
-              "duration": 1500
-            });
-            return;
-          }
-          if(res.data.code===0){
-            resolve(res.data.data);
-          } else if(res.data.code === 401) {
-            // token过期
-            try {
-              // 删除过期token
-              wx.removeStorageSync('token');
-            } catch (e) {
-              console.log("可能没有这个缓存")
-            };
-            // getCurrentPages()[0].login();
-            // request(url,data,method,header,isToken);
-          } else{
-            _show_error(res.data.code)
-          }
-        },
-        fail: (err) => {
-          _show_error("1");
+          wx.showToast({
+            "title": "请求错误",
+            "icon": "error",
+            "duration": 1500
+          });
+          return;
+        }
+
+        if (!strings.isTrue(data.unShowLoad)) {
           wx.hideLoading();
         }
-      })
+        if (res.data.code === 0) {
+          resolve(res.data.data);
+        } else if (res.data.code === 401) {
+          // token过期
+          try {
+            // 删除过期token
+            wx.removeStorageSync('token');
+          } catch (e) {
+            console.log("可能没有这个缓存")
+          };
+          // getCurrentPages()[0].login();
+          // request(url,data,method,header,isToken);
+        } else {
+          _show_error(res.data.code)
+        }
+      },
+      fail: (err) => {
+        _show_error("1");
+        wx.hideLoading();
+      },
+      complete() {}
+    })
   })
 }
 
@@ -127,4 +145,4 @@ module.exports = {
   isCN,
   urlencodeType,
   jsonType
-}
+}