基本功能是OK,但是感觉传的数据太多,不安全,需要改写。

App({
  d: {
    hostUrl: 'http://www.test.com/index.php', //请填写您自己的小程序主机URL
    appId: "xxx",
    appKey: "xxx",
    ceshiUrl: 'http://www.test.com/index.php',//请填写您自己的测试URL
  },
  //小程序初始化完成时触发,全局只触发一次
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    //login
    this.getUserInfo();
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(that.globalData.userInfo)
    } else {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.login({
              success: function (res) {
                //console.log(res);
                var code = res.code;
                //get wx user simple info
                wx.getUserInfo({
                  withCredentials: true,
                  success: function (res) {
                    //如果已经授权过那么会执行这里代码,console.log("已授权标记");
                    that.globalData.userInfo = res.userInfo;
                    typeof cb == "function" && cb(that.globalData.userInfo);
                    //get user sessionKey
                    that.getUserSessionKey(code);
                    if (that.userInfoReadyCallback) {
                      that.userInfoReadyCallback(res)
                    }
                  }
                });
              }
            })
          } else {
            // 没有授权,重定向到 loading 启动页
            wx.navigateTo({
              url: '../tologin/tologin',
            })
          }
        }
      })
    }
  },

  getUserSessionKey: function (code) {

    //用户的订单状态
    var that = this;
    wx.request({
      url: that.d.ceshiUrl + '/Api/Login/getsessionkey',
      method: 'post',
      data: {
        code: code
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data
        var data = res.data;
        if (data.status == 0) {
          wx.showToast({
            title: data.err,
            duration: 2000
          });
          return false;
        }

        that.globalData.userInfo['sessionId'] = data.session_key;
        that.globalData.userInfo['openid'] = data.openid;
        that.onLoginUser();
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常!err:getsessionkeys',
          duration: 2000
        });
      },
    });
  },
  //授权登录
  onLoginUser: function () {
    var that = this;
    var user = that.globalData.userInfo;
    wx.request({
      url: that.d.ceshiUrl + '/Api/Login/authlogin',
      method: 'post',
      data: {
        SessionId: user.sessionId,
        gender: user.gender,
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid: user.openid
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data
        var data = res.data.arr;
        var status = res.data.status;
        if (status != 1) {
          wx.showToast({
            title: res.data.err,
            duration: 3000
          });
          return false;
        }
        that.globalData.userInfo['id'] = data.ID;
        that.globalData.userInfo['NickName'] = data.NickName;
        that.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId) {
          wx.showToast({
            title: '登录失败!',
            duration: 3000
          });
          return false;
        }
        that.d.userId = userId;
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常!err:authlogin',
          duration: 2000
        });
      },
    });
  },

  globalData: {
    userInfo: null
  },

  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  }

});

如果不想首页自动登陆,在其它页调用登陆:

// pages/user/user.js
var app = getApp()
Page({
  data: {
    userInfo: {},
    orderInfo: {},
    loadingText: '加载中...',
    loadingHidden: false,
  },
  onLoad: function () {
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo,
        loadingHidden: true
      })
    });

    console.log("个人中心:--" + app.d.userId);

    this.loadOrderStatus();
  },
})

我感觉这个书上的微信小程序登陆写得不好的更多相关文章

  1. nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId

    nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId 前言: 我准备用nodejs+koa+uniapp实现一款餐饮点单小程序,以及nodejs+koa+vue实现后端管理 ...

  2. 补充ABP Zero集成微信小程序登陆的BUG修复部分

    感谢园友 @turingguo 发布的 https://www.cnblogs.com/turingguo/p/9019026.html  文章,详细介绍了ABP Zero集成微信小程序登陆的实现过程 ...

  3. 02月刊(上) | 微信小程序

    * { margin: 0; padding: 0 } .con { width: 802px; margin: 0 auto; text-align: center; position: inher ...

  4. 反编译获取线上任何微信小程序源码(转)

    看到人家上线的小程序的效果,纯靠推测,部分效果在绞尽脑汁后能做出大致的实现,但是有些细节,费劲全力都没能做出来.很想一窥源码?查看究竟?看看大厂的前端大神们是如何规避了小程序的各种奇葩的坑?那么赶紧来 ...

  5. 微信小程序初探--写个扫雷分享给你玩

    闲暇里,想学一下微信小程序, 于是,用微信小程序原生做了个扫雷玩. 以下略作总结,分享给大家. 微信里下拉,输入[mini计算器], 看到这个图标的就是了: 说好的扫雷,怎么变成计算器了?原因后面解释 ...

  6. 微信小程序登陆流程图时序图

    微信小程序登录 小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系. 微信小程序登录流程时序图 说明 调用 wx.login() 获取 临时登录凭证cod ...

  7. 微信小程序-登陆、支付、模板消息

    wx.login(OBJECT) 调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key).用户数据的加解密通讯需要 ...

  8. mpvue微信小程序怎么写轮播图,和官方微信代码的差别

    目前用mpvue很多第三方的ui库是引入不了的,因为它不支持含有dom操作. 那我们要做轮播图的话一个是手写另外一个就是用小程序的swiper组件了: 官方代码: <swiper indicat ...

  9. 微信小程序登陆授权

    小程序前端代码 function WXlogin(){ wx.login({ success: function (code) { wx.getUserInfo({ success:function( ...

随机推荐

  1. 复杂的sql参考(3)

    SELECT apply.assets_code, apply.loan_apply_code, cust.cust_name, cust.id_no, cust.mobile, platform.p ...

  2. golang执行命令行(一)

    golang中会经常遇到要 fork 子进程的需求.go 标准库为我们封装了 os/exec标准包,当我们要运行外部命令时应该优先使用这个库. 执行 command 这里我简单结合context 和 ...

  3. 下载并使用MNIST数据集

    TensorFlow提供了一个库,可以直接用来自动下载与安装MNIST. MNIST里包含3个数据集:第一个是训练数据集(mnist.train.images),另外两个分别是测试数据集(mnist. ...

  4. k8s 运行应用

    一.deployment 创建过程 kubect创建deployment —> deployment 创建ReplicaSet—>根据ReplicaSet 创建Pod 命名方式 relic ...

  5. 【题解】Luogu P5279 [ZJOI2019]麻将

    原题传送门 希望这题不会让你对麻将的热爱消失殆尽 我们珂以统计每种牌出现的次数,不需要统计是第几张牌 判一副牌能不能和,类似这道题 对于这题: 设\(f[i][j][k][0/1]\)表示前\(i\) ...

  6. MVC视图中 TextBoxFor 数据格式化

    @Html.TextBoxFor(m => m.Birthday,"{0:yyyy-MM-dd}", new { @class = "m-wrap small&qu ...

  7. springboot项目,打包时携带所有依赖

    springboot项目,打包时携带所有依赖 本文主要解决springboot打包时,如何设置才能把当前项目的所有依赖都打进去. Springboot 的自带spring-boot-maven-plu ...

  8. 【转载】C#中使用int.Parse方法将字符串转换为整型Int类型

    在C#编程过程中,很多时候涉及到数据类型的转换,例如将字符串类型的变量转换为Int类型就是一个常见的类型转换操作,int.Parse方法是C#中专门用来将字符串转换为整型int的,int.Parse方 ...

  9. fileinput 配置项大全,从源码中翻出了很多属性,没那么多时间一一验证,特发出来给大家参考参考

    fileinput 配置项大全,从源码中翻出了很多属性,没那么多时间一一验证,特发出来给大家参考参考 fileinput 配置项大全 option 属性名 属性类型 描述说明 默认值 language ...

  10. dedecms更换默认编辑器为百度编辑器ueditor

    由于体验过ueditor编辑器,再次使用Dedecms编辑器感觉很别扭,所以就有了更换编辑器的想法.操作顺序如下所述: 1.首先,下载ueditor包,官网http://ueditor.baidu.c ...