wx.login(object,object)
//index.js
Page ({
data: {
openid: null,
session_key: null,
unionid: null,
},
onLoad () {
wx.login ({
success: res => {
if (res.code) {
wx.request ({
url: 'https://test.com/onLogin', //测试api
data: {
code: res.code, //用户登录凭证,有效期5分钟
},
header: {
'content-type': 'application/json', //请求头
},
success: function (result) {
//json转化
const res = JSON.parse (result);
//解构赋值
const {openid, session_key, unionid, errorcode} = res.data;
//errorcode 状态码
if (errorcode === -1) {
console.log ('系统繁忙,请稍微重试');
return;
} else if (errorcode === 0) {
console.log ('请求成功');
} else if (errorcode === 40029) {
console.log ('code无效');
return;
} else if (errorcode === 45011) {
console.log ('请求过于频繁');
return
} else {
console.log ('未知错误');
return
}
//data存储
this.data.openid = openid;
this.data['session_key'] = session_key;
this.data.unionid = unionid;
//数据缓存
this.setStorage ({
key: 'WxLoginInfo',
value: {
openid: openid,
session_key: session_key,
unionid: unionid,
},
});
},
fail: function (result) {
console.log (result);
},
});
} else {
console.log ('登录失败' + res.errMsg);
}
},
});
},
});
从请求登录到返回成功经历了以下几个过程:
1.通过wx.login获取用户登录凭证res.code
2.把res.code通过wx.request发送到后台换取session_key和openid
3.session_key是会话秘钥,openid是用户标识符,为了保证安全,session_key不应该下发到小程序中。