微信小程序 授权登录代码
时间: 2023-06-21 14:15:32 浏览: 59
我可以提供微信小程序授权登录的代码示例,具体如下:
1、在小程序设置里开启微信登录功能
2、引用登录组件
```javascript
var app=getApp();
var {openid}=app.globalData;
var {user_info}=app.globalData;
App({
onLaunch: function () {
var that=this;
var systemInfo=wx.getSystemInfoSync();
//获取设备宽高然后进行数据绑定
that.globalData.winWidth=systemInfo.windowWidth;
that.globalData.winHeight=systemInfo.windowHeight;
that.checkLogin();
},
checkLogin:function(){
var that=this;
return new Promise(function(resolve,reject){
if(!openid){
wx.login({
success:function(res){
if(res.code){
wx.getUserInfo({
success:function(res){
wx.request({
url:'API接口地址',
data:{
action:'login',
code:res.code,
nickName:res.userInfo.nickName,
avatarUrl:res.userInfo.avatarUrl,
gender:res.userInfo.gender,
province:res.userInfo.province,
city:res.userInfo.city,
country:res.userInfo.country
},
method:'POST',
header:{
'content-type':'application/x-www-form-urlencoded'
},
success:function(res){
if(res.data.status === 1){
openid=res.data.openid;
user_info= res.data.userInfo;
that.globalData.user_info=user_info;
that.globalData.openid=openid;
resolve();
}
else{
that.globalData.openid='';
that.globalData.user_info={};
reject(res.data.msg);
}
},
fail:function(res){
reject(res);
}
})
},
fail:function(res){
reject(res);
}
})
}
else{
reject(res);
}
},
fail:function(res){
reject(res);
}
})
}
else{
resolve();
}
})
},
globalData: {
openid:'',
user_info:{},
winWidth:'',
winHeight:'',
}
})
```
3、调用登录方法并获取用户信息
```javascript
// pages/home/home.js
var app=getApp();
var {openid}=app.globalData;
var {user_info}=app.globalData;
Page({
data:{
openid:'',
nickname:'',
avatar:'',
},
onLoad:function(options){
var that=this;
if(user_info) {
that.setData({
openid:openid,
nickname:user_info.nickName,
avatar:user_info.avatarUrl
})
}
else {
app.checkLogin().then(function(){
that.setData({
openid:openid,
nickname:user_info.nickName,
avatar:user_info.avatarUrl
})
})
}
}
})
```
希望能够帮到你!
阅读全文