授权登录
//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?appid=' + APPID + '&secret=' + SECRET + '&js_code=' + postData.code + '&grant_type=authorization_code',
url: 'https://m.renyiwenzhen.com/rymember.php?mod=xcxlogin&code=' + postData.code + '&nickname=' + e.detail.userInfo.nickName,
data: {},
header: {
'content-type': 'application/json'
},
success: function (res) {
// openid = res.data.openid //返回openid
console.log(res.data);
wx.setStorage({
key: "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?action=yimiaolist', //仅为示例,并非真实的接口地址
method: 'post',
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res.data)
that.setData({
list: res.data
})
}
})
if (app.globalData.userInfo) { //获取用户信息是一个异步操作,在onLoad函数加载的时候app.js中的onLaunch可能还没有加载,所以需要判断是否获取成功
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUser) { //判断canIUser的值是否为true,实则在判断微信小程序版本是否支持相关属性
app.userInfoReadyCallback = (res) => { // userInfoReadyCallback:userInfo的回调函数,声明一个回调函数,将回调函数传给app.js,userInfo加载完成后会执行这个回调函数,这个回调函数会将获取的getUserInfo的结果直接传回来
// 在app.js中获取用户信息之后调用这个函数,结果放在函数的参数中
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
wx.getUserInfo({ //在老的版本中是可以直接调用授权接口并获取用户信息
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
}
})
每次检查是否授权
//app.js
App({
globalData: {
userInfo: null,
isok:false,
unionid:null
},
onLaunch: function () {
/* 已授权之后,自动获取用户信息 */
// 判断是否授权
wx.getSetting({
success: (res) => { //箭头函数为了处理this的指向问题
if (res.authSetting["scope.userInfo"]) {
console.log("已授权");
。。。。。。。。。。。。。
作者:Vam的金豆之路
篇幅有限更多请见扩展链接:http://www.mark-to-win.com/tutorial/50993.html
| 留言与评论(共有 0 条评论) “” |