微信小程序登录功能wx.login

wx.login(object,object)

//index.js
Page ({
  data: {
    openid: null,
    session_key: null,
    unionid: null,
  },
  onLoad () {
    wx.login ({
      success: res => {
        if (res.code) {
          wx.request ({
            url: 'https://test.com/onLogin', //测试api
            data: {
              code: res.code, //用户登录凭证,有效期5分钟
            },
            header: {
              'content-type': 'application/json', //请求头
            },
            success: function (result) {
              //json转化
              const res = JSON.parse (result);
              //解构赋值
              const {openid, session_key, unionid, errorcode} = res.data;
              //errorcode 状态码
              if (errorcode === -1) {
                console.log ('系统繁忙,请稍微重试');
                return;
              } else if (errorcode === 0) {
                console.log ('请求成功');
              } else if (errorcode === 40029) {
                console.log ('code无效');
                return;
              } else if (errorcode === 45011) {
                console.log ('请求过于频繁');
                return
              } else {
                console.log ('未知错误');
                return 
              }
              //data存储
              this.data.openid = openid;
              this.data['session_key'] = session_key;
              this.data.unionid = unionid;
              //数据缓存
              this.setStorage ({
                key: 'WxLoginInfo',
                value: {
                  openid: openid,
                  session_key: session_key,
                  unionid: unionid,
                },
              });
            },
            fail: function (result) {
              console.log (result);
            },
          });
        } else {
          console.log ('登录失败' + res.errMsg);
        }
      },
    });
  },
});

从请求登录到返回成功经历了以下几个过程:
1.通过wx.login获取用户登录凭证res.code
2.把res.code通过wx.request发送到后台换取session_key和openid
3.session_key是会话秘钥,openid是用户标识符,为了保证安全,session_key不应该下发到小程序中。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值