登陸
用戶登陸主要是爲了獲取用戶標示,用於後續的業務流程。
用戶登陸的流程圖如下
本地緩存
根據小程序文檔,在用戶不手動刪除的情況下,本地緩存會一直存在,所以我們會將用戶的登錄信息緩存在本地中,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中。