(编辑:jimmy 日期: 2025/11/4 浏览:2)
授权登录
<button open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo" class="fix">登录</button>
//index.js
//获取应用实例
var APPID ='xxx'
var SECRET = 'xxx'
const app = getApp()
Page({
data: {
list:[],
userInfo:null
},
//事件处理函数
onGotUserInfo:function (e) {
if (e.detail.userInfo != undefined && app.globalData.isok == false) {
console.log(e.detail.userInfo)
wx.login({
success: function (data) {
console.log('获取登录 Code:' + data.code)
var postData = {
code: data.code
};
wx.request({
// url: 'https://api.weixin.qq.com/sns/jscode2session"unionid",
data: res.data.unionid
})
wx.navigateTo({
url: '../archives/archives'
})
},
fail: function () {
console.log('1');
}
})
},
fail: function () {
console.log('登录获取Code失败!');
}
})
}
else if (app.globalData.isok==true) {
wx.navigateTo({
url: '../archives/archives'
})
}
},
onLoad: function () {
var that =this
wx.request({
url: 'https://m.xxx.com/xcx_ajax.php"htmlcode">
//app.js
App({
globalData: {
userInfo: null,
isok:false,
unionid:null
},
onLaunch: function () {
/* 已授权之后,自动获取用户信息 */
// 判断是否授权
wx.getSetting({
success: (res) => { //箭头函数为了处理this的指向问题
if (res.authSetting["scope.userInfo"]) {
console.log("已授权");
// 获取用户信息
wx.getUserInfo({
success: (res) => { //箭头函数为了处理this的指向问题
this.globalData.isok=true
var that =this
console.log(res.userInfo); //用户信息结果
wx.getStorage({
key: 'unionid',
success(res) {
that.globalData.unionid=res.data
}
})
this.globalData.userInfo = res.userInfo;
if (this.userInfoReadyCallback) { //当index.js获取到了globalData就不需要回调函数了,所以回调函数需要做做一个判断,如果app.js中有和这个回调函数,那么就对这个函数进行调用,并将请求到的结果传到index.js中
this.userInfoReadyCallback(res.userInfo);
}
}
})
}
else{
console.log("未授权");
wx.removeStorage({
key: 'unionid'
})
}
}
})
}
})
总结
以上所述是小编给大家介绍的微信小程序授权登陆及每次检查是否授权实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!