微信小程序的登录授权一是只通过微信小程序的开发文档上授权,但是这种授权方式无法获取openid只是快捷展示信息,
需要对数据库和用户信息操作则需要依照微信开放平台上先访问接口获取code,然后在拿到code去访问后端的接口
后端携带code去访问微信api,之后把信息返回给前端,文档地址:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Authorized_API_call_UnionID.html
var openId = (wx.getStorageSync('openId')) if (openId) { wx.getUserInfo({ success: function (res) { that.setData({ nickName: res.userInfo.nickName, avatarUrl: res.userInfo.avatarUrl, }) }, fail: function () { // fail console.log("获取失败!") }, complete: function () { // complete console.log("获取用户信息完成!") } }) } else { wx.login({ success: function (res) { console.log(res.code) if (res.code) { wx.getUserInfo({ withCredentials: true, success: function (res_user) { wx.request({ //后台接口地址 url: 'https://....com/wx/login', data: { code: res.code, encryptedData: res_user.encryptedData, iv: res_user.iv }, method: 'GET', header: { 'content-type': 'application/json' }, success: function (res) { // this.globalData.userInfo = JSON.parse(res.data); that.setData({ nickName: res.data.nickName, avatarUrl: res.data.avatarUrl, }) wx.setStorageSync('openId', res.data.openId); } }) }, fail: function () { wx.showModal({ title: '警告通知', content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。', success: function (res) { if (res.confirm) { wx.openSetting({ success: (res) => { if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录 wx.login({ success: function (res_login) { if (res_login.code) { wx.getUserInfo({ withCredentials: true, success: function (res_user) { wx.request({ url: 'https://....com/wx/login', data: { code: res_login.code, encryptedData: res_user.encryptedData, iv: res_user.iv }, method: 'GET', header: { 'content-type': 'application/json' }, success: function (res) { that.setData({ nickName: res.data.nickName, avatarUrl: res.data.avatarUrl, }) wx.setStorageSync('openId', res.data.openId); } }) } }) } } }); } }, fail: function (res) { } }) } } }) }, complete: function (res) { } }) } } }) } }, globalData: { userInfo: null }