需要发布的小程序基本都要用到openid,这里保存一下自己的代码。 一种是不需要服务器的,通过微信提供的接口简单获取openid;一种是有服务器的情况下,获取openid和一些加密的信息,如unionid。
简单获取openid 这里的简单获取,是指调试的时候可以使用,正常的情况应该是通过服务器来获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 wx.login({ success : function (res ) { var code = res.code; if (res.code) { wx.getUserInfo({ success : function (res ) { wx.setStorageSync('userInfo' , res.userInfo); that.getOpenid(code); } }) } else { console .log('获取用户登录态失败!' + res.errMsg) } } }) getOpenid : function (code ) { var that = this ; wx.request({ url : 'https://api.weixin.qq.com/sns/jscode2session?appid=' + that.globalData.appid + '&secret=' + that.globalData.secret + '&js_code=' + code + '&grant_type=authorization_code' , data : {}, method : 'GET' , success : function (res ) { var obj = {}; obj.openid = res.data.openid; obj.expires_in = Date .now() + res.data.expires_in; obj.session_key = res.data.session_key; wx.setStorageSync('openid' , obj.openid); } }); },
通过服务器获取openid和unionid 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 wx.login({ success : function (res ) { var code = res.code; if (res.code) { wx.getUserInfo({ success : function (res ) { wx.setStorageSync('userInfo' , res.userInfo); wx.request({ url : url.host + '/decodeUserInfo' , method : 'POST' , header : { 'content-type' : 'application/x-www-form-urlencoded' }, data : { encryptedData : res.encryptedData, iv : res.iv, code : code, }, success : function (data ) { if (data.data.code == 200 ) { console .log('解密成功' ); var encryptInfo = data.data.data; wx.setStorageSync('openid' , encryptInfo.openId); wx.setStorageSync('encryptInfo' , encryptInfo); } else { console .log('解密失败' ) } } }, fail : function (res ) { console .log(res); console .log('请求错误' ) } }) } else { console .log('获取用户登录态失败!' + res.errMsg) } } })
最后,可以把这个方法给暴露出来,让其他界面调用 1 2 3 4 5 6 7 8 9 getUserInfo : function ( ) { var that = this var userInfo = wx.getStorageSync('userInfo' ) || {}; var openid = wx.getStorageSync('openid' ) || null ; if (!userInfo.nickName || !openid) { that.getData(); } }
其实获取unionid的方法主要在后台实现,需要根据微信提供的方法去解密,具体的解密文档可以参考以下内容: 微信小程序获取用户openid 与 微信小程序联盟:微信小程序之获取并解密用户数据(获取openId、unionId)