微信小程序获取用户openid
微信小程序获取用户openid
首先调用wx.login() 获取登录凭证(code),再通过登录凭证(code)获取用户登录信息,包括用户的唯一标识(openid) 及本次登录的会话密钥(session_key)。
app.js代码
//app.js
globalData: {
userInfo:null,
openid:null,
session_key:null,
apiUrl:http://localhost:1234/api/index.aspx,//请求接口地址
},
getUserProfile(e) {
var that = this
wx.getUserProfile({
desc: 获取用户信息,
success: (res) => {
wx.showToast({
title: 获取中...,
duration: 2000,
icon: loading,
mask:true,
})
that.globalData.userInfo = res.userInfo
//登录
wx.login({
success: res => {
//根据code获取openid,session_key
if (res.code) {
//发起网络请求
wx.request({
url: that.globalData.apiUrl,
data: {
code: res.code,
parameter: onLogin
},
header: {
content-type: application/json
},
success: function(res) {
console.log(res.data.openid);//openid
console.log(res.data.session_key);//session_key
that.globalData.openid= res.data.openid;
that.globalData.session_key= res.data.session_key;
wx.showToast({
title: 获取成功,
duration: 1500,
icon: success
})
},
fail: function() {
wx.showToast({
title: 获取失败,
duration: 2000,
icon: error
})
}
}
}else {
console.log(登录失败: + res.errMsg)
}
})
}
})
},
后端api代码
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
情侣小程序2.0版本已提上日程
