登陆
用户登陆主要是为了获取用户标示,用于后续的业务流程。
用户登陆的流程图如下
本地缓存
根据小程序文档,在用户不手动删除的情况下,本地缓存会一直存在,所以我们会将用户的登录信息缓存在本地中,setStorage,在本项目中会存储用户的openId;在使用的时候getStorage,如果获取不到则表示用户没有登录,后面进行登录;
wx.login
wx.login执行后小程序框架会给我们返回用户的一个code,我们用这个code去获取用户真正的唯一标示,该code有时效性,只可以使用一次
wx.login({
success: res => {
console.log(res.code);
}
})
请求微信登陆
拿到用户code后,请求微信服务获取用户的openId;小程序代码如下
wx.login({
success: res => {
console.log(res);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: globalData.constant.context + '/wx/login',
method: 'post',
data: {
appid: res.code
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data);
wx.setStorageSync("openId", res.data);
},
fail(res) {
console.log("fail to login");
}
})
}
})
后台接收到code后请求微信服务器获取用户的唯一标示
public Result login(String code) {
String openId = sessionUtil.getOpenId();
if (StringUtils.isBlank(openId)) {
ResponseResult responseResult = wxUtil.login(code);
if (responseResult.getCode() != HttpServletResponse.SC_OK) {
return Result.getErrorResultWithMessage("login error, status: " + responseResult.getCode());
}
JSONObject jsonObject = JSONObject.parseObject(responseResult.getEntity());
openId = jsonObject.getString("openid");
sessionUtil.setOpenId(openId);
}
return Result.getSuccessResultWithData(openId);
}
public ResponseResult login(String code) {
Map<String, Object> params = new HashMap<>();
params.put("js_code", code);
params.put("appid", appId);
params.put("secret", secret);
params.put("grant_type", "authorization_code");
ResponseResult responseResult = httpUtil.get(wxLoginUrl, params);
return responseResult;
}
客户端接收到数据后存储到storage中。