微信小程序获取openid(用户唯一身份识别)

1.首先在js文件中定义存储appid,secret对象

在这里插入图片描述
2.在onLoad生命周期函数里面获取openid

    /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
        var that = this
        var user = wx.getStorageSync('user') || {};
        var userInfo = wx.getStorageSync('userInfo') || {};
        if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)) && (!userInfo.nickName)) {
          wx.login({
            success: function (res) {
              if (res.code) {
                wx.getUserInfo({
                  success: function (res) {
                    var objz = {};
                    objz.avatarUrl = res.userInfo.avatarUrl;
                    objz.nickName = res.userInfo.nickName;
                    //console.log(objz);
                    wx.setStorageSync('userInfo', objz);//存储userInfo
                  }
                });
                var d = that.globalData;//这里存储了appid、secret、token串  
                var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
                wx.request({
                  url: l,
                  data: {},
                  method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
                  // header: {}, // 设置请求的 header  
                  success: function (res) {
                    var obj = {};
                    obj.openid = res.data.openid;
                    obj.expires_in = Date.now() + res.data.expires_in;
                  //存储openid
                    wx.setStorageSync('user', obj); 
                  }
                });
              } else {
                console.log('获取用户登录态失败!' + res.errMsg)
              }
            }
          });
         }

3.取出缓存中的openid

    try {
          var value = wx.getStorageSync('user');
          } catch (e) {
          console.log(value)
        }

在这里插入图片描述
结束…

你可能感兴趣的:(互联网,前端)