登录的逻辑是这样的
wx.checkSession验证session_key是否过去 => wx.login登录获取code => wx.getSetting获取用户当前设置 => wx.getUserInfo获取用户的信息 => 获取用户的openid和session_key
看一下哪部分可以不需要,省去的
附上我的代码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 } }) |
求大神帮我分析一下,此步骤是否合理?
wx.login需要提交appid等参数么?
直接写死在服务器端不可以么?
厉害了我的哥
直接把AppSecret写程序里,你是真的不怕死
// 登录
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;
wx.request({
url: Config.url +
'appUser/wxLogin'
,
data: { data:
'{openid:"'
+ e.data.openid +
'",nickName:"'
+res.userInfo.nickName+
'",userPic:"'
+res.userInfo.avatarUrl+
'"}'
},
header: {
"Content-Type"
:
"application/x-www-form-urlencoded"
},
success:
function
(res) {
console.log(res)
that.globalData.userMsg = res.data.obj
}
})
}
})
}
})
}
})