wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if(res.code){
wx.getUserInfo({
success: function(res_user){
wx.request({
url: 'http://192.168.xx.xx:8080/test/v1/getOpenId', //这里是本地请求路径,可以写你自己的本地路径,也可以写线上环境
data: {
code: res.code,//获取openid的话 需要向后台传递code,利用code请求api获取openid
headurl: res_user.userInfo.avatarUrl,//这些是用户的基本信息
nickname:res_user.userInfo.nickName,//获取昵称
sex:res_user.userInfo.gender,//获取性别
country: res_user.userInfo.country,//获取国家
province: res_user.userInfo.province,//获取省份
city: res_user.userInfo.city//获取城市
},
success: function(res){
wx.setStorageSync("openid", res.data)//可以把openid保存起来,以便后期需求的使用
}
})
}
})
}
}
})
原文链接:https://blog.youkuaiyun.com/qq_39851704/article/details/79025557
但是询问老师之后,发现云开发有个自带的函数login可以直接获取到openid等一系列信息。
// 云函数模板
const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init({
// API 调用都保持和云函数当前所在环境一致
env: cloud.DYNAMIC_CURRENT_ENV
})
/**
* 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
*
* event 参数包含小程序端调用传入的 data
*
*/
exports.main = (event, context) => {
console.log(event)
console.log(context)
// 可执行其他自定义逻辑
// console.log 的内容可以在云开发云函数调用日志查看
// 获取 WX Context (微信调用上下文),包括 OPENID、APPID、及 UNIONID(需满足 UNIONID 获取条件)等信息
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
env: wxContext.ENV,
}
}
最后用了这个 ↓
// 获取openid
wx.cloud.callFunction({
name:'login',
data:{
},
success:res=>{
console.log(res.result.openid);
this.setData({
user_openid: res.result.openid,
})
}
})