想要获取用户的openid首先要明白获取的过程

1,登录

2,发请求获取openid

实现:先定义一组数据,后面发请求获取openid时要的参数,一个是appid,一个是secret秘钥,这两个在注册开发者平台后可以查到

如下:

 globalData:{appid:'wxa1111111111111',secret:'3acbe5r8s4s5d7s895'},

之后写登录的方法和获取openid

  login(){var that = this;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) {console.log(res)var obj = {};obj.openid = res.data.openid;obj.expires_in = Date.now() + res.data.expires_in;//存储openidwx.setStorageSync('user', obj); }});} else {console.log('获取用户登录态失败!' + res.errMsg)}}});},

之后在onload方法中调用登录即可