前言
此文章是Java后端接入微信登錄功能,由于專案需要,舍棄了解密用戶資訊的session_key
,只保留openid
用于檢索用戶資訊
后端框架:spring boot
小程式框架:uniapp
流程概括
- 官方流程:通過自定義登錄態與openid,session_key關聯,之后的前后端互動通過自定義登錄態來識別
- 只保留登錄流程:使用 spring boot 的session進行互動,openid存入資料庫,用來檢索用戶資訊(可以理解為 openid 作為賬號,只保留此小程式的登錄功能)
官方小程式登錄流程圖解(圖取自官網)
- 通過wx.login()獲取code
- 將code發送給后端服務器,后端會回傳一個token,這個token將作為你身份的唯一標識,
- 將token通過wx.setStorageSync()保存在本地存盤,
- 用戶下次進入?面時,會先通過wx.getStorageSync() 方法判斷token是否有值,如果有值,則可以請求其它資料,如果沒有值,則進行登錄操作,
- openid:用來唯一標識用戶的一個字串,通過
openid
可以獲取用戶的基本資訊(不同小程式中擁有不同openid) - code:
code
是用戶登錄憑證,由微信服務器頒發給小程式;后端通過code向微信服務器請求用戶的openid
和session_key
等資訊,(code是一次性的,且時效為5分鐘) - unionid:用于標識同一微信開放平臺賬號下多個應用的用戶,多個小程式中的
unionid
是相同的
接入小程式登錄(只保留 openid 登錄功能)
- 通過wx.login()獲取code
- 將code發送給后端服務器,后端保存openid到資料庫并回傳sessionId
- 將sessionId通過wx.setStorageSync()保存在本地存盤
- 用戶下次進入?面時,會先通過wx.getStorageSync() 方法判斷sessionId是否有值,如果有值,則可以請求其它資料,如果沒有值,則進行登錄操作,
后端代碼
工具類
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.redapple.project.common.ErrorCode;
import com.redapple.project.exception.ThrowUtils;
public class RequestUtils {
// 獲取AccessToken
public static JSONObject getAccessToken(String appId, String appSecret) {
String apiUrl = StrUtil.format(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
appId, appSecret
);
String body = HttpRequest.get(apiUrl).execute().body();
ThrowUtils.throwIf(body == null, ErrorCode.OPERATION_ERROR);
return new JSONObject(body);
}
// 獲取session_key和openid
public static String getOpenIdByCode(String appId, String secret, String code) {
String apiUrl = StrUtil.format(
"https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code",
appId, secret, code
);
String body = HttpRequest.get(apiUrl).execute().body();
ThrowUtils.throwIf(body == null, ErrorCode.OPERATION_ERROR);
return body;
}
}
登錄實作
主要接收三個引數,分別是小程式的appi、appSecret、前端傳來的code
這里通過工具類向微信介面服務發送jscode,回傳openid
- openid存在:登錄,回傳用戶資訊
- openid不存在:注冊,將openid存入資料庫并回傳用戶資訊
public LoginUserVO WeChatLogin(String appid, String secret, String code, HttpServletRequest request) {
// 獲取session_key和openid
String result = RequestUtils.getOpenIdByCode(appid, secret, code);
System.out.println("result:" + result);
// 提取openid
String openid = new JSONObject(result).getStr("openid");
// 這里是自己封裝的方法,流程是如果openid為空則拋例外
ThrowUtils.throwIf(openid == null, ErrorCode.NOT_FOUND_ERROR, "openid為空");
// 查詢openid是否存在
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("openid", openid);
User oldUser = this.baseMapper.selectOne(queryWrapper);
// openid不存在
if (oldUser == null) {
// 添加用戶
User user = new User();
user.setOpenid(openid);
user.setPhone("手機號未填寫");
user.setUserName("默認用戶");
boolean saveResult = this.save(user);
if (!saveResult) {
// 這里也是自己封裝的方法,流程是拋自定義例外
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注冊失敗,資料庫錯誤");
}
// 記錄用戶的登錄態
request.getSession().setAttribute(USER_LOGIN_STATE, user);
return getLoginUserVO(user);
}
// 記錄用戶的登錄態
request.getSession().setAttribute(USER_LOGIN_STATE, oldUser);
// 用戶存在,回傳用戶資料
return getLoginUserVO(oldUser); // 自己封裝的方法,回傳脫敏的用戶資料
}
前端代碼
uniapp框架
<template>
<view>
<button @click="login">微信一鍵登錄</button>
</view>
</template>
<script setup lang="ts">
const login = () => {
uni.login({
provider: 'weixin', //使用微信登錄
success: function (loginRes) {
if (loginRes.code !== null) {
console.log("獲取code:" + loginRes.code)
loginUser(loginRes.code);
} else {
console.log("code為空");
}
}
})
}
const loginUser = (code: any) => {
uni.request({
url: "http://localhost:8066/api/wechat/login",
method: 'POST',
data: {
code: code,
},
success: (res : any) => {
//每次登錄時清楚快取
uni.removeStorageSync('JSESSIONID');
// 保存Cookie到Storage
uni.setStorageSync("JSESSIONID", res.header['Set-Cookie'])
if (res.data.code === 1) {
uni.switchTab({
url: "/pages/index/index"
})
} else {
console.log(res);
}
}
})
}
</script>
<style>
</style>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/555551.html
標籤:其他
下一篇:返回列表