Java后端接入微信小程序實現登錄功能
更新時間:2023年06月20日 09:11:37 作者:玄德_hk
這篇文章主要介紹了Java如何在后端接入微信小程序從而實現登錄功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
前言
此文章是Java后端接入微信登錄功能,由于項目需要,舍棄了解密用戶信息的session_key
,只保留openid
用于檢索用戶信息
后端框架:spring boot
小程序框架:uniapp
流程概括
- 官方流程:通過自定義登錄態(tài)與openid,session_key關聯(lián),之后的前后端交互通過自定義登錄態(tài)來識別
- 只保留登錄流程:使用 spring boot 的session進行交互,openid存入數據庫,用來檢索用戶信息(可以理解為 openid 作為賬號,只保留此小程序的登錄功能)
官方小程序登錄流程圖解(圖取自官網)
- 通過wx.login()獲取code
- 將code發(fā)送給后端服務器,后端會返回一個token,這個token將作為你身份的唯一標識。
- 將token通過wx.setStorageSync()保存在本地存儲。
- 用戶下次進入?面時,會先通過wx.getStorageSync() 方法判斷token是否有值,如果有值,則可以請求其它數據,如果沒有值,則進行登錄操作。
- openid:用來唯一標識用戶的一個字符串,通過
openid
可以獲取用戶的基本信息(不同小程序中擁有不同openid) - code:
code
是用戶登錄憑證,由微信服務器頒發(fā)給小程序;后端通過code向微信服務器請求用戶的openid
和session_key
等信息。(code是一次性的,且時效為5分鐘) - unionid:用于標識同一微信開放平臺賬號下多個應用的用戶,多個小程序中的
unionid
是相同的
接入小程序登錄(只保留 openid 登錄功能)
- 通過wx.login()獲取code
- 將code發(fā)送給后端服務器,后端保存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
這里通過工具類向微信接口服務發(fā)送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, "注冊失敗,數據庫錯誤"); } // 記錄用戶的登錄態(tài) request.getSession().setAttribute(USER_LOGIN_STATE, user); return getLoginUserVO(user); } // 記錄用戶的登錄態(tài) request.getSession().setAttribute(USER_LOGIN_STATE, oldUser); // 用戶存在,返回用戶數據 return getLoginUserVO(oldUser); // 自己封裝的方法,返回脫敏的用戶數據 }
前端代碼
uniapp框架
<template> <view> <button class="loginbutton" @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>
到此這篇關于Java后端接入微信小程序實現登錄功能的文章就介紹到這了,更多相關Java登錄內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java 在Excel單元格中應用一種/多種字體樣式(實例代碼)
這篇文章主要介紹了Java 在Excel單元格中應用一種/多種字體樣式,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12