微信小程序的登录注册 实现
前提:本案例是配合API工场的后台接口实现的
1,首先是给页面加上一个按钮或者弹出层
<button class="l" open-type="getUserInfo" bindgetuserinfo="processLogin">允许</button>
2,利用点击按钮来获取用户的信息
processLogin(e) {
//e就是用户的信息
//如果没有用户userInfo
if (!e.detail.userInfo) {
wx.showToast({
title: '已取消',
icon: 'none',
})
//终止操作
return;
}
//如果用userInfo,则调用register注册方法
this.register();
},
3,获取用户信息后实现注册的方法
register(){
//定义一下this值方便后续使用
let _this = this
//通过官方的文档来登录 获取code值
wx.login({
success:function(res){
//拿到code值重新定义一下code值
let code = res.code
//再次执行获取用户信息的方法
wx.getUserInfo({
//根据API工程的后端接口知道要用三个参数(iv,code,encryptedData)
success:function(res){
let iv = res.iv; //加密值
let encryptedData = res.encryptedData; //包括敏感数据在内的完整数据
//拿到参数后 发送请求 传参
wx.request({
url: 'https://api.it120.cc/xps/user/wxapp/register/complex',
method:"POST",
header:{
"content-Type":"application/x-www-form-urlencoded"
},
data:{
code,
iv,
encryptedData,
},
success:function(res){
//成功得知用户是否注册 执行登陆方法
console.log(res.data.msg)
_this.login()
},
})
}
})
}
})
},
4,登陆方法
login(){
//老规矩 定义this
let _this = this
//再次利用wx.login来进行获取code 因为 code只能用一次,所以要再次获取
wx.login({
//获取成功后 拿到code
success:function(res){
let code = res.code
//利用code走登录接口
wx.request({
url: 'https://api.it120.cc/xps/user/wxapp/login',
header:{
"content-type":"application/x-www-form-urlencoded"
},
method:"POST",
data:{
code
},
success:function(res){
console.log(res)
//用户已注册
if(res.data.code === 10000){
return;
}//登陆失败
if(res.data.code!=0){
console.log("登陆失败")
return;
}
//成功后保存token到本地
wx.setStorageSync('token', res.data.data.token)
wx.setStorageSync('uid', res.data.data.uid)
var token=res.data.data.token
//利用接口 配合 token拿到用户详情
wx.request({
url: 'https://api.it120.cc/xps/user/detail',
header:{
"content-Type":"application/x-www-form-urlencoded"
},
data:{
token:token
},success:function(res){
console.log(res.data.data.base.avatarUrl)
_this.setData({
img:res.data.data.base.avatarUrl
})
}
})
}
})
}
})
}