检查本地是否有 token
验证 token 是否过期
检查微信 session 是否有效
onLaunch: function () {
this.login()
},
login() {
wx.login({
success(res) {
if (res.code) {
wx.request({
url: 'http://127.0.0.1:3000/login',
// req.body
// 如果没有指定为 post,则在 req.query
method: 'POST',
data: {
code: res.code
},
success: res => {
console.log(res);
wx.setStorageSync('openis', res.data.openid)
wx.setStorageSync('session_key', res.data.session_key)
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
const wx = {
appid: 'wxf878bb2864a8f765',
assServ: 'f084f92acca09b2b19081c2e2758b082'
}
app.post('/login', (req, res) => {
fetch(`https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.assServ}&js_code=${req.body.code}&grant_type=authorization_code`)
.then(res => res.json())
.then(result => {
res.json({
errno: 0,
session_key: result.session_key,
openid: result.openid
})
})
})
<button open-type="chooseAvatar" bind:chooseavatar="chooseAvatar">
<image src="{{userInfo.avatar}}" mode="aspectFill" />
</button>
<input type="nickname" bindinput="iptName" value="{{userInfo.avatar}}"/>
const defaultAvatarUrl = 'https://glpla.github.io/imgs/qrcode_glpla.github.io.png'
Page({
data: {
userInfo:{
avatar: defaultAvatarUrl,
nickName:''
}
},
chooseAvatar(e) {
this.setData({
'userInfo.avatar': e.detail.avatarUrl
})
wx.setStorageSync('userInfo', this.data.userInfo);
app.globalData.userInfo = this.data.userInfo
},
iptName(e){
this.setData({
'userInfo.nickName': e.detail.value
})
wx.setStorageSync('userInfo', this.data.userInfo);
app.globalData.userInfo = this.data.userInfo
}
})