基本功能是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. Redis 的主从复制(Master/Slave)

    目录 1. 是什么 2. 能干嘛 3. Redis主从复制讲解 (1). info replication:查看 目标redis 主从情况 (2) . 配从库不配主库 (3). 常用策略 (4). 复 ...

  2. SQL Server 特殊字符及中文汉字的处理

    简介 在SQL Server 中很多时候需要对一些字段中特殊的字符做处理,比如某个字段中包含一些回车.制表.换行等特殊字符(这些字符往往来源于Excel).这些特殊字符的存在可能导致无法提取到所需数据 ...

  3. C++ STL学习总结

    1.vector //最好给它一个初始化大小 #include <iostream> #include <vector> using namespace std; int ma ...

  4. Connection to 天mysql failed. [08001] Could not create connection to database server. Attempted ,报错处理方法

    https://blog.csdn.net/myzh215219/article/details/90314345 点击图上的DRIVER,然后点击GO TO DRIVER,之后更改合适的驱动. 我的 ...

  5. python学习-29 map函数-filter函数

    movie_person = ['小红','小明','小王','富豪_sb','美女_sb'] def filter_test(array): ret = [] for i in array: if ...

  6. Python之路【第二十一篇】:JS基础

    JavaScript的基础学习(一) 一.JavaScript概述 1.1 JavaScript的历史 ● 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在 ...

  7. C语言学习笔记01——C语言概述

    作者:Eventi 出处:http://www.cnblogs.com/Eventi 欢迎转载,也请保留这段声明.谢谢! 1 C语言的起源 1972年,贝尔实验室的丹尼斯·里奇(Dennis Ritc ...

  8. springboot+mybatis实现数据库的读写分离

    介绍 随着业务的发展,除了拆分业务模块外,数据库的读写分离也是常见的优化手段.方案使用了AbstractRoutingDataSource和mybatis plugin来动态的选择数据源选择这个方案的 ...

  9. PB 获取或操作数据窗口语句的方法

    1.setsqlselect用法: ls_select=getsqlselect    //通过getsqlselect取得当前数据窗口的查询语句 ls_where="  "    ...

  10. Tr/ee AtCoder - 4433 (构造)

    大意: 给定长$n$的字符串$s$, 要求构造一棵树, 满足若第$i$个字符为$1$, 那么可以删一条边, 得到一个大小为$i$的连通块. 若为$0$则表示不存在一条边删去后得到大小为$i$的连通块. ...