登录的逻辑是这样的
wx.checkSession验证session_key是否过去 => wx.login登录获取code => wx.getSetting获取用户当前设置 => wx.getUserInfo获取用户的信息 => 获取用户的openid和session_key
看一下哪部分可以不需要,微信小程序能否代表一个app参加比赛+微信小程序教程。省去的
附上我的代码app.js
//app.js
let AppId = 'wxb56d****f9f4d';
let AppSecret = '51fafc123******a7c29e3cc01';
let LoginSessionKey = 'LoginSessionKey';
App({
// 顺序: wx.checkSession验证session_key是否过去 => wx.login登录获取code => wx.getSetting获取用户当前设置 => wx.getUserInfo获取用户的信息 => 获取用户的openid和session_key
onLaunch: function() {
let self = this;
wx.checkSession({
success: function(){
//session_key 未过期,并且在本生命周期一直有效
console.log('session_key 未过期');
if (wx.getStorageSync(LoginSessionKey)) return;
self.getSetting();
},
fail: function(){
// session_key 已经失效,需要重新执行登录流程
console.log('session_key 已经失效');
self.getSetting();
}
})
},
getSetting() {
let self = this;
self.getLogin().then((code)=> {
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: function(userInfo) {
self.globalData.userInfo = userInfo;
self.getJsCode(code)
}
})
}
}
})
})
},
getLogin() {
return new Promise((resolve, reject)=> {
wx.login({
success: function(params) {
let code = params.code;
if (code) {
wx.showToast({
title: '正在登录...',
icon: 'loading',
duration: 10000
});
resolve(code)
} else {
reject(params.errMsg)
console.log('获取用户登录态失败!' + params.errMsg)
}
}
})
})
},
getJsCode(code) {
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',
data: {
appid: AppId,
secret: AppSecret,
js_code: code,
grant_type: 'authorization_code'
},
method: 'GET',
header: {
'content-type': 'application/json'
}, // 设置请求的 header
success: (res)=> {
console.log(res.data);
if (res.errcode && res.errcode == 40029 && res.statusCode !== 200) {
wx.showToast({
title: 'Code无效, 稍后重试',
duration: 10000
});
} else {
let openid = res.data.openid,
session_key = res.data.session_key;
wx.setStorageSync(LoginSessionKey, {openid,session_key})
}
},
fail: function () {
wx.showToast({
title: '请求失败, 稍后重试',
duration: 10000
});
},
complete: function () {
wx.hideToast();
}
})
},
globalData: {
user: true,
userInfo: null
}
})
求大神帮我分析一下,此步骤是否合理?
本文来自微信小程序开发者论坛 微信小程序工厂 http://www.xcxgc.com 转载请保留。
微信小程序开发者回答:
K***: // 登录
wx.login({
success: eq => {
wx.request({
url:"https://api.weixin.qq.com/sns/jscode2session",
data: {
appid: "你的APPID",
secret: "你的SECRET",
js_code: eq.code,
grant_type: 'authorization_code'
},
method: 'GET',
success: function (e) {
that.globalData.wx = {
openid:e.data.openid,
session_key:e.data.session_key
}
wx.getUserInfo({
success: res => {
that.globalData.userInfo = res.userInfo;
本文网址:http://www.91bianli.com/weixinxiaochengxu/57754.html