![cover](https://img-blog.csdnimg.cn/img_convert/3256b39ed0ef4decb2ddc7c65e82d331.png)
uniapp微信公众号微信授权登陆实现
通过getAppId方法请求接口获取到appid并且返回到/h5/pages/login/index?然后页面获取到code会执行微信登陆也就是前面onLoad中的this.weChatLogin(options.code)方法并传入code。正常不需要支付的项目一般不需要做微信授权登陆,有业务需要的可以加,我这边项目中使用了微信支付功能所以需要搞个微信授权登陆。我这边请求接口是执行的如果没有用户
·
正常不需要支付的项目一般不需要做微信授权登陆,有业务需要的可以加,我这边项目中使用了微信支付功能所以需要搞个微信授权登陆
进入到登陆页面首先要执行
onLoad(options) {
if (options.code) {
//alert(options.code);
this.code = options.code;
this.weChatLogin(options.code);
} else {
this.getAppId();
}
},
//这里执行的是有code的情况下执行微信登陆
//没有的话执行 this.getAppId()方法 this.getAppId()方法后面会介绍
通过getAppId方法请求接口获取到appid并且返回到/h5/pages/login/index?code=0313uHGa1dhPuF0PekFa1eCT2z23uHGl&state=STATE 登录页面并且获取到code
// 获取公众号APPID
getAppId() {
uni.request({
url: config.baseURL + '/api/thirdParty/weChatPay/getAppId',
data: {
organId: uni.getStorageSync('organId'),
},
method: 'GET',
success: (res) => {
console.log(res.data.data)
let url = config.baseURL + "/h5/pages/login/index";
location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + res.data
.data + "&redirect_uri=" + url +
"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
}
})
},
然后页面获取到code会执行微信登陆也就是前面onLoad中的this.weChatLogin(options.code)方法并传入code
//微信端登陆
weChatLogin(code) {
let that = this;
uni.request({
url: config.baseURL + '/api/thirdParty/weChatPay/weChatLogin',
data: {
code,
},
method: 'GET',
success: (res) => {
console.log("返回openid",res.data.openid);
// that.openid = res.data.data.openid;
if (res.data.code == 500) { //code为500是没有此用户需要注册
that.openid = res.data.openid;
that.state = 1;
//this.openid = res.data.openid;
that.toggle('center');
} else {
that.openid = res.data.openid.data.openid;
let {username} = res.data.openid.data;
console.log("username",username)
that.login(username,username)
}
}
})
},
我这边请求接口是执行的如果没有用户就直接让用户注册,有的话就直接让用户登陆。
//用户登陆
login(username, password) {
let that = this;
uni.request({
url: config.baseURL + '/user/login',
data: {
username,
password,
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
success: (res) => {
console.log("token", res.data.token);
let loginInfo = {
username,
password,
}
uni.setStorageSync('openid',that.openid);
uni.setStorageSync('token', res.data.token);
uni.setStorageSync('user', res.data.user)
uni.setStorageSync('loginInfo', loginInfo);
console.log(uni.getStorageSync('token'));
//uni.navigateBack();
app.websocket_init();
uni.switchTab({
//保留当前页面,跳转到应用内的某个页面
url: '/pages/index/index'
})
}
})
},
更多推荐
所有评论(0)