本文主要总结微信小程序通过后台请求访问微信用户信息
创建一个微信小程序工程(自行百度)
微信小程序index.js代码
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
backUserInfo:{},//后台得到的微信用户信息
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
//1.静默操作获取用户信息 调用wx.login
var that = this;
wx.login({
success:function(res){
var code = res.code;//2.登录凭证code
console.log('code==='+code);
if(null!=code){
wx.getUserInfo({
success:function(ress){
console.log('res===' + res);
//3.请求自己的服务器,解密用户信息
wx.request({
url: 'http://xxxx.com/wcsp/oauth',
method:'post',
header:{
'content-type': 'application/x-www-form-urlencoded'
},
data: { encryptedData: ress.encryptedData, iv: ress.iv, code: code},
success:function(res){
console.log('resjava===' + res.data.openId);
that.setData({
backUserInfo:res//将后台返回的数据赋值给backUserInfo
})
}
})
}
})
}
}
})
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
su