基本功能是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. mysql:获取某个表的所有字段

    select COLUMN_NAME from information_schema.COLUMNS where table_name = '表名' and table_schema = '数据库名' ...

  2. k8s-job使用

    一.job特性 运行完成后退出,但是不会被删除,便于用户查看日志信息,了解任务完成的情况 删除job时产生的pod也会被一起删除 job中可以运行多个pod(任务执行多次),且可以并行运行缩短任务完成 ...

  3. Java开发笔记(一百五十)C3P0连接池的用法

    JDBC既制定统一标准兼容了多种数据库,又利用预报告堵上了SQL注入漏洞,照理说已经很完善了,可是人算不如天算,它在性能方面不尽如人意.问题出在数据库连接的管理上,按照正常流程,每次操作完数据库,都要 ...

  4. 长乐国庆集训Day2

    T1 连珠风暴 题目 [题目描述] 给定M种颜色的珠子,每种颜色珠子的个数均不限,将这些珠子做成长度为N的项链. 问能做成多少种不重复的项链.两条项链相同,当且仅当两条项链通过旋转或是翻转后能重合在一 ...

  5. Jupyter notebook 安装

    一.建议从官网下载最新版anaconda https://www.anaconda.com/ 进入网址找到下载位置,并找到对应的版本,下载python3.7,根据电脑系统自行选择32/64位进行下载, ...

  6. 23 Collection集合常用方法讲解

    本文讲讲几个Collection的常用方法,这些方法在它的子类中也是很常用的,因此这里先拿出来单独讲解,以后它的子类中的这些方法就不再重复讲解. 几个常用方法: add() 添加一个元素 size() ...

  7. Django框架(十一)--cookie和session

    cookie和session组件 cookie 1.cookie的由来 大家都知道HTTP协议是无状态的. 无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,它 ...

  8. Java中是使用增强for的null问题

    在使用List和Map等集合时,我们经常会使用增强for来进行遍历.但是这里面会存在一些问题.比如当你进行数据库查询是,得到的返回结果是List集合时,如果没有查询到符合要求的数据时List集合时nu ...

  9. python3 安装 pyinstaller 时报错的解决办法

    如上图所示,在安装的过程中发现是所关联的一个 future模块安装失败,庵后我有单独安装了一下这个future,发现还是失败 然后在网上寻找解决办法,最后找到了这个指令,pip install fut ...

  10. Codeforces Round #596 (Div. 1, based on Technocup 2020 Elimination Round 2)

    (第一把div1心态崩了,给大家表演了一把上蓝) (看来以后div1需要先读前三题,如果没把握切掉还是不要交了……) A: 题意是求最少用几个形如$2^{t}+p$的数拼出n,给定n和p.$n\leq ...