我们在开发小程序的时候,小程序给每个用户分配一个唯一的标识openid,根据这个标识我们可以获取到唯一的用户,进行在设计相关的数据库表时,我们可以依据这个数据进行设置主键存储该用户的相关信息。
根据官网我们知道 ,在小程序登录(wx.login)的过程中我们可以获取到用户res.code
然后根据这个值向后台换取openid,sessionKey的信息。
这个操作在app.js中进行
在进行操作之前我们需要以下操作
- 在微信开发工具启动项目的时候,是使用的是自己的
appid
账号,而非测试号
- 使用自己的appid获取唯一的appsecret(也就是下面的secret)
app.js
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey
console.log(res.code)
if(res.code){
console.log(res.code)
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',//微信服务器获取appid的网址 不用变
method:'post',//必须是post方法
data:{
js_code:res.code,
appid:'wxdadaddceweed',//仅为实例appid
secret:'edajdisajisdincaksaksokdoakadp',//仅为实例secret
grant_type:'authorization_code'
},
header: {
'content-type': 'application/x-www-form-urlencoded',
},
success:function(response){
console.log(response.data)
wx.setStorageSync('app_openid', response.data.openid); 将openid存入本地缓存
wx.setStorageSync('sessionKey', response.data.session_key)//将session_key 存入本地缓存命名为SessionKey
}
})
}else{
console.log("登陆失败");
}
}
})
从本地缓存中取出appid进行操作
var that = this //早success里面不能使用this 因为 success 是回调函数 它会不停的检测是否成功,因此在不断回调的过程中this的指向就发生了变化
wx.getStorage({
key:'app_openid',//获取key值
success: function(res) {
console.log(res)
that.setData({
openid:res.data//返回key对应的value
})
},
})