微信小程序一键登录全流程解析
项目概述
本项目实现了基于SpringBoot后端和uniapp前端的微信小程序授权登录功能,支持用户通过微信一键登录,获取用户基本信息并完成注册/登录流程。
技术架构
后端技术栈
-
SpringBoot 2.x - 主框架
-
MyBatis - 数据持久化
-
Redis - 会话管理
-
Apache HttpClient - HTTP请求工具
-
FastJSON - JSON处理
前端技术栈
-
uniapp - 跨平台开发框架
-
Vue.js 2.x - 前端框架
-
微信小程序API - 微信登录相关接口
核心实现流程
1. 微信小程序端登录流程
1.1 获取微信登录凭证
// 调用微信登录API获取code
uni.login({
provider: 'weixin',
success: (loginRes) => {
if (loginRes.code) {
// 获取到临时登录凭证code
this.tempCode = loginRes.code;
// 继续获取用户信息
this.getUserProfile();
}
}
});
1.2 获取用户授权信息
// 使用getUserProfile获取用户信息(推荐方式)
uni.getUserProfile({
desc: '用于完善用户资料',
lang: 'zh_CN',
success: (profileRes) => {
const userDTO = {
code: loginRes.code,
wxHeadPic: profileRes.userInfo.avatarUrl,
wxUsername: profileRes.userInfo.nickName,
roleId: 2
};
this.sendLoginRequest(userDTO);
}
});
1.3 发送登录请求
// 向后端发送登录请求
httpUtil.request({
url: '/app/user/wx_login',
method: 'POST',
data: userDTO,
success: (res) => {
// 保存用户信息到本地存储
uni.setStorageSync('userInfo', JSON.stringify(res.data));
this.isLogin = true;
}
});
2. SpringBoot后端处理流程
2.1 接收登录请求
@PostMapping("/wx_login")
public ResponseDTO<UserDTO> appWxLogin(@RequestBody UserDTO userDTO) {
return userService.appWxLogin(userDTO);
}
2.2 调用微信API验证
// 构建微信API请求URL String url = LOGIN_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&grant_type=authorization_code&js_code=" + userDTO.getCode(); // 发送HTTP请求到微信服务器 HttpClient client = HttpClients.createDefault(); HttpGet getRequest = new HttpGet(url); HttpResponse response = client.execute(getRequest); // 解析响应获取openid String html = EntityUtils.toString(response.getEntity()); LoginDTO loginDTO = JSON.parseObject(html, LoginDTO.class);
2.3 用户信息处理
// 根据openid查询用户是否存在
UserExample userExample = new UserExample();
userExample.createCriteria().andWxIdEqualTo(userDTO.getWxId());
List<User> userList = userMapper.selectByExample(userExample);
if (userList.size() > 0) {
// 用户已存在,直接登录
User user = userList.get(0);
userDTO = CopyUtil.copy(user, UserDTO.class);
} else {
// 用户不存在,创建新用户
User user = new User();
user.setId(UuidUtil.getShortUuid());
user.setWxId(userDTO.getWxId());
user.setWxUsername(EmojiConverterUtil.emojiConvert(userDTO.getWxUsername()));
user.setWxHeadPic(userDTO.getWxHeadPic());
userMapper.insertSelective(user);
}
2.4 生成登录令牌
// 生成用户token userDTO.setToken(UuidUtil.getShortUuid()); // 将用户信息存储到Redis,设置过期时间 stringRedisTemplate.opsForValue().set( "USER_" + userDTO.getToken(), JSON.toJSONString(userMapper.selectByPrimaryKey(userDTO.getId())), 3600, TimeUnit.SECONDS );
数据库设计
用户表结构 (user)
CREATE TABLE `user` ( `id` char(8) NOT NULL COMMENT '主键', `wx_id` varchar(50) DEFAULT NULL COMMENT '微信openid', `head_pic` varchar(200) DEFAULT NULL COMMENT '头像', `wx_head_pic` varchar(200) DEFAULT NULL COMMENT '微信头像', `phone` varchar(11) DEFAULT NULL COMMENT '手机号', `role_id` int DEFAULT NULL COMMENT '角色ID', `sex` int DEFAULT NULL COMMENT '性别', `username` varchar(50) DEFAULT NULL COMMENT '用户名', `wx_username` varchar(50) DEFAULT NULL COMMENT '微信昵称', `password` varchar(50) DEFAULT NULL COMMENT '密码', PRIMARY KEY (`id`), UNIQUE KEY `wx_id` (`wx_id`) );
关键配置
微信小程序配置
// 微信小程序AppID和AppSecret private final static String APP_ID = "wxc41c88e07f3f1bd7"; private final static String APP_SECRET = "99a06dc0d1e21d797a9915baca08c872"; // 微信登录API地址 private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
前端网络配置
// 服务器地址配置 const SERVER_URL = 'http://39.96.184.228:8080'; // 测试模式开关 const TEST_MODE = false;
重要注意事项
1. 微信API调用限制
-
getUserProfile必须由用户主动触发:只能在用户点击按钮等交互事件中直接调用
-
code有效期限制:微信登录code只能使用一次,且有5分钟有效期
-
频率限制:微信API有调用频率限制,需要做好异常处理
2. 用户信息处理
-
表情符号处理:微信昵称可能包含emoji,需要使用EmojiConverterUtil进行转换
-
数据去重:使用wx_id作为唯一标识,避免重复注册
-
默认值设置:为新用户设置合理的默认角色和权限
3. 安全性考虑
-
AppSecret保护:微信AppSecret不能暴露在前端代码中
-
Token管理:使用Redis存储用户会话,设置合理的过期时间
-
请求验证:后端需要验证微信API返回的数据有效性
4. 异常处理
-
网络异常:处理微信API调用失败的情况
-
用户拒绝授权:提供备用登录方案或友好提示
-
数据库异常:确保用户注册过程的事务完整性
5. 测试环境支持
-
模拟登录:支持测试环境下的模拟登录功能
-
调试日志:添加详细的日志记录便于问题排查
-
降级方案:微信API失败时的备用处理逻辑
前端兼容性处理
getUserProfile降级方案
// 优先使用getUserProfile
if (typeof uni.getUserProfile === 'function') {
uni.getUserProfile({...});
} else {
// 降级使用getUserInfo
uni.getUserInfo({...});
}
授权按钮备用方案
<!-- 当getUserProfile失败时显示授权按钮 --> <button v-if="needAuth" open-type="getUserInfo" @getuserinfo="onGetUserInfo"> 授权获取头像和昵称 </button>
性能优化建议
-
缓存用户信息:将用户信息缓存到本地存储,减少重复请求
-
请求合并:避免频繁的网络请求,合理使用防抖和节流
-
图片优化:对用户头像进行适当的压缩和缓存
-
错误重试:网络请求失败时提供重试机制
部署注意事项
-
域名配置:确保服务器域名已在微信小程序后台配置
-
HTTPS要求:生产环境必须使用HTTPS协议
-
跨域处理:正确配置CORS策略
-
日志监控:建立完善的日志监控体系
详细代码实现
前端核心代码分析
登录页面完整实现 (my.vue)
<template>
<view class="container">
<!-- 未登录状态 -->
<view v-if="!isLogin" class="login-container">
<view class="login-header">
<image class="panda-avatar" src="/static/panda.png"></image>
<view class="welcome-text">Hi, 欢迎来智学伴航</view>
</view>
<!-- 微信登录按钮 -->
<button class="login-btn" @tap="directWxLogin">
<image src="/static/微信.png" class="wechat-icon"></image>
微信一键登录
</button>
<!-- 授权按钮备用方案 -->
<button
v-if="needAuth"
open-type="getUserInfo"
@getuserinfo="onGetUserInfo"
class="auth-btn">
授权获取头像和昵称
</button>
</view>
<!-- 已登录状态 -->
<view v-else class="user-info">
<image :src="avatarUrl" class="user-avatar"></image>
<text class="user-name">{{nickName}}</text>
<button @tap="logout" class="logout-btn">退出登录</button>
</view>
</view>
</template>
<script>
import httpUtil from '@/utils/httpUtil.js';
export default {
data() {
return {
isLogin: false,
userInfo: null,
avatarUrl: '/static/panda.png',
nickName: '用户',
token: '',
needAuth: false,
isLoggingIn: false,
tempCode: ''
};
},
onLoad() {
this.checkLoginStatus();
},
methods: {
// 检查本地登录状态
checkLoginStatus() {
const userInfoStr = uni.getStorageSync('userInfo');
if (userInfoStr) {
try {
this.userInfo = typeof userInfoStr === 'string'
? JSON.parse(userInfoStr) : userInfoStr;
this.avatarUrl = this.userInfo.headPic ||
this.userInfo.wxHeadPic || '/static/panda.png';
this.nickName = this.userInfo.username ||
this.userInfo.wxUsername || '用户';
this.token = this.userInfo.token;
this.isLogin = true;
} catch (e) {
console.error('解析用户信息失败:', e);
uni.removeStorageSync('userInfo');
}
}
},
// 微信登录主流程
directWxLogin() {
console.log('开始微信登录流程');
this.isLoggingIn = true;
// 第一步:获取微信登录凭证
uni.login({
provider: 'weixin',
success: (loginRes) => {
if (loginRes.code) {
console.log('获取到微信code:', loginRes.code);
this.tempCode = loginRes.code;
// 第二步:获取用户信息
this.getUserProfileInfo(loginRes.code);
} else {
this.handleLoginError('获取微信登录凭证失败');
}
},
fail: (err) => {
console.error('微信登录失败:', err);
this.handleLoginError('微信登录失败');
}
});
},
// 获取用户信息(支持多种方式)
getUserProfileInfo(code) {
// 优先使用getUserProfile(新版本推荐)
if (typeof uni.getUserProfile === 'function') {
uni.getUserProfile({
desc: '用于完善用户资料',
lang: 'zh_CN',
success: (profileRes) => {
console.log('getUserProfile成功:', profileRes);
this.buildLoginData(code, profileRes.userInfo);
},
fail: (err) => {
console.error('getUserProfile失败:', err);
this.fallbackGetUserInfo(code);
}
});
} else {
this.fallbackGetUserInfo(code);
}
},
// 降级方案:使用getUserInfo
fallbackGetUserInfo(code) {
uni.getUserInfo({
provider: 'weixin',
success: (userInfoRes) => {
console.log('getUserInfo成功:', userInfoRes);
this.buildLoginData(code, userInfoRes.userInfo);
},
fail: (err) => {
console.error('getUserInfo失败:', err);
// 显示授权按钮
this.needAuth = true;
this.isLoggingIn = false;
uni.showModal({
title: '需要您的授权',
content: '请点击授权按钮获取头像和昵称',
showCancel: false
});
}
});
},
// 构建登录数据
buildLoginData(code, userInfo) {
const userDTO = {
code: code,
wxHeadPic: userInfo.avatarUrl,
wxUsername: userInfo.nickName,
roleId: 2
};
console.log('构建登录数据:', userDTO);
this.sendLoginRequest(userDTO);
},
// 发送登录请求到后端
sendLoginRequest(userDTO) {
httpUtil.request({
url: '/app/user/wx_login',
method: 'POST',
data: userDTO,
success: (res) => {
this.handleLoginSuccess(res);
},
fail: (err) => {
this.handleLoginError(err.msg || '登录失败');
}
});
},
// 处理登录成功
handleLoginSuccess(res) {
this.isLoggingIn = false;
console.log('登录成功:', res);
// 保存用户信息
this.userInfo = res.data;
this.token = res.data.token;
this.avatarUrl = res.data.headPic || res.data.wxHeadPic || '/static/panda.png';
this.nickName = res.data.username || res.data.wxUsername || '用户';
// 存储到本地
uni.setStorageSync('userInfo', JSON.stringify(res.data));
this.isLogin = true;
uni.showToast({
title: '登录成功',
icon: 'success'
});
},
// 处理登录错误
handleLoginError(errorMsg) {
this.isLoggingIn = false;
console.error('登录失败:', errorMsg);
uni.showModal({
title: '登录失败',
content: errorMsg,
showCancel: false
});
},
// 用户授权回调
onGetUserInfo(e) {
if (e.detail.userInfo) {
this.isLoggingIn = true;
this.buildLoginData(this.tempCode, e.detail.userInfo);
this.needAuth = false;
} else {
// 用户拒绝授权,使用默认信息
const defaultUserInfo = {
avatarUrl: '/static/panda.png',
nickName: '微信用户'
};
this.buildLoginData(this.tempCode, defaultUserInfo);
}
},
// 退出登录
logout() {
uni.showModal({
title: '确认退出',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
this.performLogout();
}
}
});
},
// 执行退出登录
performLogout() {
httpUtil.logout(this.token).then(() => {
this.resetLoginState();
uni.showToast({
title: '已退出登录',
icon: 'success'
});
}).catch(() => {
// 即使请求失败也清除本地状态
this.resetLoginState();
});
},
// 重置登录状态
resetLoginState() {
this.isLogin = false;
this.userInfo = null;
this.avatarUrl = '/static/panda.png';
this.nickName = '用户';
this.token = '';
uni.removeStorageSync('userInfo');
}
}
};
</script>
后端核心代码分析
用户服务实现 (UserServiceImpl.java)
@Service
@Transactional
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Resource
private StringRedisTemplate stringRedisTemplate;
// 微信小程序配置
private final static String APP_ID = "wxc41c88e07f3f1bd7";
private final static String APP_SECRET = "99a06dc0d1e21d797a9915baca08c872";
private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
@Override
public ResponseDTO<UserDTO> appWxLogin(UserDTO userDTO) {
System.out.println("接收到登录请求,用户数据: " + userDTO);
// 调用微信API获取openid
String openid = getWxOpenid(userDTO.getCode());
if (openid == null) {
return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);
}
userDTO.setWxId(openid);
// 查询用户是否已存在
User existingUser = findUserByWxId(openid);
if (existingUser != null) {
// 用户已存在,更新信息并登录
updateExistingUser(existingUser, userDTO);
userDTO = CopyUtil.copy(existingUser, UserDTO.class);
} else {
// 用户不存在,创建新用户
User newUser = createNewUser(userDTO);
userDTO = CopyUtil.copy(newUser, UserDTO.class);
}
// 生成登录token
String token = generateUserToken(userDTO);
userDTO.setToken(token);
// 存储用户会话到Redis
storeUserSession(token, userDTO.getId());
System.out.println("登录成功,返回数据: " + userDTO);
return ResponseDTO.successByMsg(userDTO, "登录成功!");
}
/**
* 调用微信API获取openid
*/
private String getWxOpenid(String code) {
// 处理模拟登录
if (code != null && code.startsWith("mock_")) {
System.out.println("检测到模拟登录,使用固定openid");
return "mock_openid_fixed";
}
// 构建微信API请求URL
String url = String.format("%s?appid=%s&secret=%s&grant_type=authorization_code&js_code=%s",
LOGIN_URL, APP_ID, APP_SECRET, code);
try {
System.out.println("发送微信API请求: " + url);
// 创建HTTP客户端
HttpClient client = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(url);
// 执行请求
HttpResponse response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println("微信API响应: " + responseBody);
// 解析响应
LoginDTO loginDTO = JSON.parseObject(responseBody, LoginDTO.class);
if (loginDTO.getErrcode() == null || loginDTO.getErrcode() == 0) {
System.out.println("获取到openid: " + loginDTO.getOpenid());
return loginDTO.getOpenid();
} else {
System.out.println("微信登录失败,错误码: " + loginDTO.getErrcode()
+ ", 错误信息: " + loginDTO.getErrmsg());
// 测试环境降级处理
if (isTestEnvironment()) {
System.out.println("测试环境,使用固定openid");
return "test_openid_fixed";
}
return null;
}
} catch (Exception e) {
System.out.println("微信API请求异常: " + e.getMessage());
e.printStackTrace();
// 测试环境异常降级
if (isTestEnvironment()) {
System.out.println("测试环境异常,使用固定openid");
return "test_openid_fixed";
}
return null;
}
}
/**
* 根据微信ID查找用户
*/
private User findUserByWxId(String wxId) {
UserExample userExample = new UserExample();
userExample.createCriteria().andWxIdEqualTo(wxId);
List<User> userList = userMapper.selectByExample(userExample);
return userList.isEmpty() ? null : userList.get(0);
}
/**
* 更新已存在用户信息
*/
private void updateExistingUser(User existingUser, UserDTO userDTO) {
System.out.println("用户已存在,更新信息: " + existingUser.getId());
// 更新用户头像和昵称
if (userDTO.getWxHeadPic() != null) {
existingUser.setWxHeadPic(userDTO.getWxHeadPic());
}
if (userDTO.getWxUsername() != null) {
String processedUsername = EmojiConverterUtil.emojiConvert(userDTO.getWxUsername());
existingUser.setWxUsername(processedUsername);
// 如果用户没有设置用户名,使用微信昵称
if (existingUser.getUsername() == null || existingUser.getUsername().isEmpty()) {
existingUser.setUsername(processedUsername);
}
}
// 更新数据库
userMapper.updateByPrimaryKeySelective(existingUser);
}
/**
* 创建新用户
*/
private User createNewUser(UserDTO userDTO) {
System.out.println("用户不存在,创建新用户");
User user = new User();
user.setId(UuidUtil.getShortUuid());
user.setWxId(userDTO.getWxId());
// 处理用户昵称中的表情符号
String username = EmojiConverterUtil.emojiConvert(userDTO.getWxUsername());
user.setUsername(username);
user.setWxUsername(username);
// 设置头像
user.setHeadPic(userDTO.getWxHeadPic());
user.setWxHeadPic(userDTO.getWxHeadPic());
// 设置默认角色
user.setRoleId(RoleEnum.USER.getCode());
user.setSex(userDTO.getSex());
System.out.println("准备插入用户数据: " + user);
// 插入数据库
if (userMapper.insertSelective(user) == 0) {
System.out.println("用户注册失败");
throw new RuntimeException("用户注册失败");
}
System.out.println("用户注册成功,ID: " + user.getId());
return user;
}
/**
* 生成用户登录token
*/
private String generateUserToken(UserDTO userDTO) {
return UuidUtil.getShortUuid();
}
/**
* 存储用户会话到Redis
*/
private void storeUserSession(String token, String userId) {
User user = userMapper.selectByPrimaryKey(userId);
String userJson = JSON.toJSONString(user);
// 存储到Redis,设置1小时过期
stringRedisTemplate.opsForValue().set(
"USER_" + token,
userJson,
3600,
TimeUnit.SECONDS
);
System.out.println("用户会话已存储到Redis,token: " + token);
}
/**
* 判断是否为测试环境
*/
private boolean isTestEnvironment() {
// 可以根据配置文件或环境变量判断
return true; // 这里简化处理,实际应该从配置读取
}
@Override
public ResponseDTO<Boolean> logout(UserDTO userDTO) {
if (!CommonUtil.isEmpty(userDTO.getToken())) {
// 清除Redis中的用户会话
stringRedisTemplate.delete("USER_" + userDTO.getToken());
System.out.println("已清除用户会话: " + userDTO.getToken());
}
return ResponseDTO.successByMsg(true, "退出登录成功!");
}
}
网络工具类实现 (httpUtil.js)
/**
* HTTP工具类 - 统一网络请求处理
*/
// 服务器配置
const SERVER_URL = 'http://39.96.184.228:8080';
const TEST_MODE = false; // 测试模式开关
/**
* 统一请求方法
* @param {Object} options 请求配置
*/
export const request = (options) => {
return new Promise((resolve, reject) => {
// 显示加载提示
if (options.showLoading !== false) {
uni.showLoading({
title: '加载中...',
mask: true
});
}
// 测试模式模拟响应
if (TEST_MODE) {
return handleTestMode(options, resolve, reject);
}
// 构建请求配置
const requestConfig = {
url: SERVER_URL + (options.url.startsWith('/') ? options.url : '/' + options.url),
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
...(options.header || {})
},
timeout: options.timeout || 10000
};
console.log('发送请求:', requestConfig.url, requestConfig.method, requestConfig.data);
// 发送请求
uni.request({
...requestConfig,
success: (res) => {
if (options.showLoading !== false) {
uni.hideLoading();
}
console.log('请求成功:', res);
// 统一响应处理
if (res.statusCode === 200) {
if (res.data.code === 0) {
// 业务成功
if (options.success) {
options.success(res.data);
}
resolve(res.data);
} else {
// 业务失败
const errorMsg = res.data.msg || '操作失败';
uni.showToast({
title: errorMsg,
icon: 'none'
});
if (options.fail) {
options.fail({ msg: errorMsg });
}
reject({ msg: errorMsg });
}
} else {
// HTTP状态码错误
handleHttpError(res.statusCode, options, reject);
}
},
fail: (err) => {
if (options.showLoading !== false) {
uni.hideLoading();
}
console.error('请求失败:', err);
handleNetworkError(err, options, reject);
},
complete: (res) => {
if (options.complete) {
options.complete(res);
}
}
});
});
};
/**
* 处理测试模式
*/
function handleTestMode(options, resolve, reject) {
setTimeout(() => {
if (options.showLoading !== false) {
uni.hideLoading();
}
console.log('测试模式:模拟请求:', options.url);
// 模拟登录接口
if (options.url.includes('/wx_login')) {
const mockData = {
code: 0,
msg: '登录成功',
data: {
id: 'test_user_' + Date.now(),
username: options.data.wxUsername || '测试用户',
wxUsername: options.data.wxUsername || '测试用户',
headPic: options.data.wxHeadPic || '/static/panda.png',
wxHeadPic: options.data.wxHeadPic || '/static/panda.png',
token: 'test_token_' + Date.now(),
roleId: options.data.roleId || 2
}
};
if (options.success) {
options.success(mockData);
}
resolve(mockData);
} else {
// 其他接口默认成功
const mockData = {
code: 0,
msg: '操作成功',
data: {}
};
if (options.success) {
options.success(mockData);
}
resolve(mockData);
}
}, 500); // 模拟网络延迟
}
/**
* 处理HTTP错误
*/
function handleHttpError(statusCode, options, reject) {
let errorMsg = '服务器错误';
switch (statusCode) {
case 400:
errorMsg = '请求参数错误';
break;
case 401:
errorMsg = '未授权访问';
break;
case 403:
errorMsg = '禁止访问';
break;
case 404:
errorMsg = '请求地址不存在';
break;
case 500:
errorMsg = '服务器内部错误';
break;
case 502:
errorMsg = '网关错误';
break;
case 503:
errorMsg = '服务不可用';
break;
default:
errorMsg = `服务器错误(${statusCode})`;
}
uni.showToast({
title: errorMsg,
icon: 'none'
});
if (options.fail) {
options.fail({ msg: errorMsg, statusCode });
}
reject({ msg: errorMsg, statusCode });
}
/**
* 处理网络错误
*/
function handleNetworkError(err, options, reject) {
let errorMsg = '网络连接失败';
if (err.errMsg) {
if (err.errMsg.includes('timeout')) {
errorMsg = '请求超时,请稍后重试';
} else if (err.errMsg.includes('fail')) {
errorMsg = '网络连接失败,请检查网络';
}
}
uni.showToast({
title: errorMsg,
icon: 'none',
duration: 2000
});
if (options.fail) {
options.fail({ msg: errorMsg });
}
reject({ msg: errorMsg });
}
export default {
request,
SERVER_URL,
TEST_MODE
};
数据传输对象定义
前端用户数据传输对象
// 登录请求数据结构
const LoginRequestDTO = {
code: '', // 微信登录凭证
wxHeadPic: '', // 微信头像URL
wxUsername: '', // 微信昵称
roleId: 2 // 角色ID,默认为普通用户
};
// 登录响应数据结构
const LoginResponseDTO = {
code: 0, // 响应码,0表示成功
msg: '', // 响应消息
data: {
id: '', // 用户ID
wxId: '', // 微信openid
username: '', // 用户名
wxUsername: '', // 微信昵称
headPic: '', // 头像URL
wxHeadPic: '', // 微信头像URL
token: '', // 登录令牌
roleId: 2, // 角色ID
phone: '', // 手机号
sex: 0 // 性别
}
};
后端数据传输对象 (UserDTO.java)
/**
* 用户数据传输对象
*/
public class UserDTO {
private String id; // 用户ID
private String wxId; // 微信openid
private String headPic; // 头像URL
private String wxHeadPic; // 微信头像URL
private String phone; // 手机号
private Integer roleId; // 角色ID
private Integer sex; // 性别
private String username; // 用户名
private String wxUsername; // 微信昵称
private String code; // 微信登录凭证
private String token; // 登录令牌
private String password; // 密码
// getter和setter方法
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getWxId() { return wxId; }
public void setWxId(String wxId) { this.wxId = wxId; }
// ... 其他getter/setter方法
@Override
public String toString() {
return "UserDTO{" +
"id='" + id + '\'' +
", wxId='" + wxId + '\'' +
", username='" + username + '\'' +
", wxUsername='" + wxUsername + '\'' +
", token='" + token + '\'' +
", roleId=" + roleId +
'}';
}
}
微信登录响应对象 (LoginDTO.java)
/**
* 微信登录API响应对象
*/
public class LoginDTO {
private String openid; // 用户唯一标识
private String session_key; // 会话密钥
private String unionid; // 用户在开放平台的唯一标识
private Integer errcode; // 错误码
private String errmsg; // 错误信息
// getter和setter方法
public String getOpenid() { return openid; }
public void setOpenid(String openid) { this.openid = openid; }
public String getSession_key() { return session_key; }
public void setSession_key(String session_key) { this.session_key = session_key; }
public String getUnionid() { return unionid; }
public void setUnionid(String unionid) { this.unionid = unionid; }
public Integer getErrcode() { return errcode; }
public void setErrcode(Integer errcode) { this.errcode = errcode; }
public String getErrmsg() { return errmsg; }
public void setErrmsg(String errmsg) { this.errmsg = errmsg; }
}
错误处理和异常情况
常见错误码处理
微信API错误码
/**
* 微信API常见错误码处理
*/
public class WxErrorHandler {
public static String getErrorMessage(Integer errcode) {
if (errcode == null || errcode == 0) {
return null; // 成功
}
switch (errcode) {
case -1:
return "系统繁忙,此时请开发者稍候再试";
case 40029:
return "code 无效";
case 45011:
return "频率限制,每个用户每分钟100次";
case 40013:
return "不合法的 AppID";
case 40125:
return "不合法的密钥";
default:
return "微信登录失败,错误码:" + errcode;
}
}
/**
* 判断是否为可重试的错误
*/
public static boolean isRetryableError(Integer errcode) {
return errcode != null && (errcode == -1 || errcode == 45011);
}
}
前端异常处理策略
/**
* 登录异常处理策略
*/
const LoginErrorHandler = {
// 处理微信API调用失败
handleWxApiError(error) {
console.error('微信API调用失败:', error);
if (error.errMsg) {
if (error.errMsg.includes('getUserProfile:fail auth deny')) {
// 用户拒绝授权
uni.showModal({
title: '授权提示',
content: '需要您的授权才能正常使用,请重新点击登录按钮',
showCancel: false
});
return 'AUTH_DENIED';
} else if (error.errMsg.includes('getUserProfile:fail')) {
// 其他getUserProfile错误
return 'GET_PROFILE_FAILED';
}
}
return 'UNKNOWN_ERROR';
},
// 处理网络请求失败
handleNetworkError(error) {
console.error('网络请求失败:', error);
let errorMsg = '网络连接失败';
let canRetry = true;
if (error.statusCode) {
switch (error.statusCode) {
case 400:
errorMsg = '请求参数错误';
canRetry = false;
break;
case 401:
errorMsg = '登录已过期,请重新登录';
canRetry = false;
break;
case 500:
errorMsg = '服务器错误,请稍后重试';
break;
default:
errorMsg = `服务器错误(${error.statusCode})`;
}
}
return { errorMsg, canRetry };
},
// 显示错误提示并提供重试选项
showErrorWithRetry(errorMsg, retryCallback) {
uni.showModal({
title: '登录失败',
content: errorMsg + '\n\n是否重试?',
confirmText: '重试',
cancelText: '取消',
success: (res) => {
if (res.confirm && retryCallback) {
retryCallback();
}
}
});
}
};
安全性最佳实践
1. 敏感信息保护
/**
* 敏感信息配置管理
*/
@Configuration
public class WxConfig {
@Value("${wx.miniapp.appid}")
private String appId;
@Value("${wx.miniapp.secret}")
private String appSecret;
// 不要在代码中硬编码敏感信息
// 使用配置文件或环境变量
public String getAppId() {
return appId;
}
public String getAppSecret() {
return appSecret;
}
}
2. Token安全管理
/**
* Token安全管理
*/
@Component
public class TokenManager {
@Resource
private StringRedisTemplate stringRedisTemplate;
private static final String TOKEN_PREFIX = "USER_TOKEN_";
private static final int TOKEN_EXPIRE_TIME = 7200; // 2小时
/**
* 生成安全的Token
*/
public String generateSecureToken(String userId) {
// 使用UUID + 时间戳 + 用户ID生成Token
String timestamp = String.valueOf(System.currentTimeMillis());
String uuid = UUID.randomUUID().toString().replace("-", "");
String rawToken = userId + "_" + timestamp + "_" + uuid;
// 可以考虑加密Token
return DigestUtils.md5DigestAsHex(rawToken.getBytes());
}
/**
* 验证Token有效性
*/
public boolean validateToken(String token) {
if (StringUtils.isEmpty(token)) {
return false;
}
String userInfo = stringRedisTemplate.opsForValue().get(TOKEN_PREFIX + token);
return !StringUtils.isEmpty(userInfo);
}
/**
* 刷新Token过期时间
*/
public void refreshToken(String token) {
if (validateToken(token)) {
stringRedisTemplate.expire(TOKEN_PREFIX + token, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
}
}
/**
* 清除Token
*/
public void removeToken(String token) {
stringRedisTemplate.delete(TOKEN_PREFIX + token);
}
}
3. 请求参数验证
/**
* 登录请求参数验证
*/
@Component
public class LoginValidator {
/**
* 验证登录请求参数
*/
public ValidationResult validateLoginRequest(UserDTO userDTO) {
ValidationResult result = new ValidationResult();
// 验证code
if (StringUtils.isEmpty(userDTO.getCode())) {
result.addError("微信登录凭证不能为空");
} else if (userDTO.getCode().length() > 100) {
result.addError("微信登录凭证格式错误");
}
// 验证微信昵称
if (!StringUtils.isEmpty(userDTO.getWxUsername())) {
if (userDTO.getWxUsername().length() > 50) {
result.addError("微信昵称长度不能超过50个字符");
}
// 检查是否包含敏感词
if (containsSensitiveWords(userDTO.getWxUsername())) {
result.addError("昵称包含敏感词汇");
}
}
// 验证头像URL
if (!StringUtils.isEmpty(userDTO.getWxHeadPic())) {
if (!isValidUrl(userDTO.getWxHeadPic())) {
result.addError("头像URL格式错误");
}
}
return result;
}
private boolean containsSensitiveWords(String text) {
// 实现敏感词检测逻辑
// 可以使用第三方敏感词过滤库
return false;
}
private boolean isValidUrl(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
}
/**
* 验证结果类
*/
public class ValidationResult {
private boolean valid = true;
private List<String> errors = new ArrayList<>();
public void addError(String error) {
this.valid = false;
this.errors.add(error);
}
public boolean isValid() {
return valid;
}
public List<String> getErrors() {
return errors;
}
public String getErrorMessage() {
return String.join("; ", errors);
}
}
部署配置指南
1. 微信小程序配置
小程序后台配置
1. 登录微信公众平台 (mp.weixin.qq.com) 2. 进入"开发" -> "开发管理" -> "开发设置" 3. 配置服务器域名: - request合法域名:https://yourdomain.com - 注意:必须是HTTPS协议,不能使用IP地址 4. 获取AppID和AppSecret: - AppID:在"开发设置"页面可以看到 - AppSecret:点击"生成"按钮获取(注意保密)
小程序代码配置
// manifest.json 配置
{
"mp-weixin": {
"appid": "你的小程序AppID",
"setting": {
"urlCheck": false, // 开发阶段可以关闭URL检查
"es6": true,
"minified": true
},
"permission": {
"scope.userInfo": {
"desc": "用于完善用户资料"
}
}
}
}
2. SpringBoot后端配置
application.yml 配置
# 服务器配置
server:
port: 8080
servlet:
context-path: /api
# 数据库配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:password}
# Redis配置
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
password: ${REDIS_PASSWORD:}
timeout: 3000ms
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
# 微信小程序配置
wx:
miniapp:
appid: ${WX_APPID:your_appid}
secret: ${WX_SECRET:your_secret}
# 日志配置
logging:
level:
com.yjq.programmer: DEBUG
org.springframework.web: INFO
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
Docker部署配置
# Dockerfile FROM openjdk:8-jre-alpine # 设置工作目录 WORKDIR /app # 复制jar包 COPY target/hotel-booking-server-1.0.jar app.jar # 暴露端口 EXPOSE 8080 # 设置环境变量 ENV JAVA_OPTS="-Xmx512m -Xms256m" # 启动应用 ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DB_HOST=mysql
- DB_USERNAME=root
- DB_PASSWORD=password
- REDIS_HOST=redis
- WX_APPID=your_appid
- WX_SECRET=your_secret
depends_on:
- mysql
- redis
networks:
- app-network
mysql:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=hotel_booking
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
networks:
- app-network
redis:
image: redis:6-alpine
ports:
- "6379:6379"
networks:
- app-network
volumes:
mysql_data:
networks:
app-network:
driver: bridge
3. Nginx反向代理配置
# nginx.conf
server {
listen 80;
server_name yourdomain.com;
# 重定向到HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL证书配置
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
# SSL安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
# API代理
location /api/ {
proxy_pass http://localhost:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时配置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# 静态文件
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public, immutable";
}
}
测试方案
1. 单元测试
后端服务测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTest {
@Autowired
private IUserService userService;
@MockBean
private UserMapper userMapper;
@MockBean
private StringRedisTemplate stringRedisTemplate;
@Test
public void testWxLoginSuccess() {
// 准备测试数据
UserDTO userDTO = new UserDTO();
userDTO.setCode("mock_test_code");
userDTO.setWxUsername("测试用户");
userDTO.setWxHeadPic("http://test.com/avatar.jpg");
// 模拟数据库查询结果
when(userMapper.selectByExample(any())).thenReturn(new ArrayList<>());
when(userMapper.insertSelective(any())).thenReturn(1);
// 执行测试
ResponseDTO<UserDTO> result = userService.appWxLogin(userDTO);
// 验证结果
assertThat(result.getCode()).isEqualTo(0);
assertThat(result.getData().getToken()).isNotNull();
assertThat(result.getData().getWxUsername()).isEqualTo("测试用户");
}
@Test
public void testWxLoginExistingUser() {
// 测试已存在用户的登录流程
UserDTO userDTO = new UserDTO();
userDTO.setCode("mock_existing_user");
User existingUser = new User();
existingUser.setId("existing_user_id");
existingUser.setWxId("existing_openid");
when(userMapper.selectByExample(any())).thenReturn(Arrays.asList(existingUser));
ResponseDTO<UserDTO> result = userService.appWxLogin(userDTO);
assertThat(result.getCode()).isEqualTo(0);
assertThat(result.getData().getId()).isEqualTo("existing_user_id");
}
@Test
public void testLogout() {
UserDTO userDTO = new UserDTO();
userDTO.setToken("test_token");
ResponseDTO<Boolean> result = userService.logout(userDTO);
assertThat(result.getCode()).isEqualTo(0);
assertThat(result.getData()).isTrue();
// 验证Redis删除操作
verify(stringRedisTemplate).delete("USER_test_token");
}
}
前端组件测试
// 使用Jest进行前端测试
describe('微信登录组件测试', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(LoginComponent);
});
test('应该正确显示登录按钮', () => {
expect(wrapper.find('.login-btn').exists()).toBe(true);
expect(wrapper.find('.login-btn').text()).toContain('微信一键登录');
});
test('点击登录按钮应该触发登录流程', async () => {
const loginSpy = jest.spyOn(wrapper.vm, 'directWxLogin');
await wrapper.find('.login-btn').trigger('tap');
expect(loginSpy).toHaveBeenCalled();
});
test('登录成功后应该更新用户状态', async () => {
const mockUserData = {
id: 'test_user',
username: '测试用户',
token: 'test_token'
};
wrapper.vm.handleLoginSuccess({ data: mockUserData });
expect(wrapper.vm.isLogin).toBe(true);
expect(wrapper.vm.userInfo).toEqual(mockUserData);
});
});
2. 集成测试
API接口测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testWxLoginEndpoint() {
// 准备请求数据
UserDTO requestDTO = new UserDTO();
requestDTO.setCode("mock_integration_test");
requestDTO.setWxUsername("集成测试用户");
// 发送请求
ResponseEntity<ResponseDTO> response = restTemplate.postForEntity(
"/app/user/wx_login",
requestDTO,
ResponseDTO.class
);
// 验证响应
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().getCode()).isEqualTo(0);
}
@Test
public void testLogoutEndpoint() {
UserDTO requestDTO = new UserDTO();
requestDTO.setToken("test_token");
ResponseEntity<ResponseDTO> response = restTemplate.postForEntity(
"/app/user/logout",
requestDTO,
ResponseDTO.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().getCode()).isEqualTo(0);
}
}
3. 端到端测试
自动化测试脚本
// 使用Cypress进行端到端测试
describe('微信登录端到端测试', () => {
beforeEach(() => {
cy.visit('/pages/my/my');
});
it('完整登录流程测试', () => {
// 检查初始状态
cy.get('.login-container').should('be.visible');
cy.get('.login-btn').should('contain', '微信一键登录');
// 模拟点击登录
cy.get('.login-btn').click();
// 检查登录中状态
cy.get('.login-loading').should('be.visible');
// 等待登录完成
cy.get('.user-info', { timeout: 10000 }).should('be.visible');
// 验证用户信息显示
cy.get('.user-name').should('not.be.empty');
cy.get('.user-avatar').should('have.attr', 'src');
});
it('退出登录测试', () => {
// 先登录
cy.login();
// 点击退出登录
cy.get('.logout-btn').click();
// 确认退出
cy.get('.uni-modal-confirm').click();
// 验证返回登录状态
cy.get('.login-container').should('be.visible');
});
});
常见问题解决
1. 微信API相关问题
问题:code已被使用
错误信息:{"errcode":40029,"errmsg":"invalid code"}
解决方案:
1. 确保每次登录都获取新的code
2. code只能使用一次,不要重复提交
3. code有5分钟有效期,超时需重新获取
问题:频率限制
错误信息:{"errcode":45011,"errmsg":"frequency limit"}
解决方案:
1. 实现请求频率控制
2. 添加重试机制,延迟后重试
3. 缓存用户信息,减少不必要的API调用
2. 用户授权问题
问题:getUserProfile调用失败
// 解决方案:确保在用户交互事件中直接调用
// 错误做法:
setTimeout(() => {
uni.getUserProfile({...}); // 这样会失败
}, 1000);
// 正确做法:
onButtonClick() {
uni.getUserProfile({...}); // 直接在事件处理中调用
}
问题:用户拒绝授权
// 提供友好的降级方案
onGetUserInfo(e) {
if (e.detail.userInfo) {
// 用户同意授权
this.processUserInfo(e.detail.userInfo);
} else {
// 用户拒绝授权,使用默认信息
this.processUserInfo({
avatarUrl: '/static/default-avatar.png',
nickName: '微信用户'
});
}
}
3. 网络请求问题
问题:请求超时
// 解决方案:增加超时时间和重试机制
const requestWithRetry = (options, maxRetries = 3) => {
return new Promise((resolve, reject) => {
const attemptRequest = (retryCount) => {
uni.request({
...options,
timeout: 15000, // 增加超时时间
success: resolve,
fail: (err) => {
if (retryCount < maxRetries && isRetryableError(err)) {
console.log(`请求失败,第${retryCount + 1}次重试`);
setTimeout(() => attemptRequest(retryCount + 1), 1000 * (retryCount + 1));
} else {
reject(err);
}
}
});
};
attemptRequest(0);
});
};
问题:跨域问题
// 后端CORS配置
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
4. 数据库相关问题
问题:表情符号存储问题
-- 确保数据库字符集支持emoji ALTER TABLE user CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
// Java代码中处理emoji
public class EmojiConverterUtil {
public static String emojiConvert(String str) {
if (StringUtils.isEmpty(str)) {
return str;
}
// 过滤掉可能导致问题的特殊字符
return str.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
}
}
5. 性能优化问题
问题:登录速度慢
// 解决方案:并行处理和缓存优化
async directWxLogin() {
try {
// 并行获取登录凭证和检查网络
const [loginRes, networkStatus] = await Promise.all([
this.getWxLoginCode(),
this.checkNetworkStatus()
]);
if (!networkStatus.isConnected) {
throw new Error('网络连接不可用');
}
// 获取用户信息
const userInfo = await this.getUserInfo();
// 发送登录请求
await this.sendLoginRequest({
code: loginRes.code,
...userInfo
});
} catch (error) {
this.handleLoginError(error);
}
}
监控和日志
1. 日志配置
// 自定义日志切面
@Aspect
@Component
public class LoginLogAspect {
private static final Logger logger = LoggerFactory.getLogger(LoginLogAspect.class);
@Around("execution(* com.yjq.programmer.service.impl.UserServiceImpl.appWxLogin(..))")
public Object logLoginAttempt(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object[] args = joinPoint.getArgs();
UserDTO userDTO = (UserDTO) args[0];
logger.info("用户登录开始,wxId: {}, 时间: {}",
userDTO.getWxId(), new Date());
try {
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
logger.info("用户登录成功,耗时: {}ms", endTime - startTime);
return result;
} catch (Exception e) {
logger.error("用户登录失败,错误: {}", e.getMessage(), e);
throw e;
}
}
}
2. 监控指标
// 使用Micrometer进行监控
@Component
public class LoginMetrics {
private final Counter loginAttempts;
private final Counter loginSuccesses;
private final Counter loginFailures;
private final Timer loginDuration;
public LoginMetrics(MeterRegistry meterRegistry) {
this.loginAttempts = Counter.builder("login.attempts")
.description("Total login attempts")
.register(meterRegistry);
this.loginSuccesses = Counter.builder("login.successes")
.description("Successful logins")
.register(meterRegistry);
this.loginFailures = Counter.builder("login.failures")
.description("Failed logins")
.register(meterRegistry);
this.loginDuration = Timer.builder("login.duration")
.description("Login duration")
.register(meterRegistry);
}
public void recordLoginAttempt() {
loginAttempts.increment();
}
public void recordLoginSuccess(Duration duration) {
loginSuccesses.increment();
loginDuration.record(duration);
}
public void recordLoginFailure() {
loginFailures.increment();
}
}
总结
这个SpringBoot + uniapp微信小程序授权登录实现方案具有以下特点:
优势
-
完整的登录流程:从前端授权到后端验证的完整实现
-
多重降级方案:支持多种用户信息获取方式
-
安全性保障:Token管理、参数验证、敏感信息保护
-
异常处理完善:网络异常、API异常、用户拒绝授权等情况的处理
-
测试覆盖全面:单元测试、集成测试、端到端测试
-
部署配置详细:Docker、Nginx、SSL等生产环境配置
-
监控日志完备:详细的日志记录和性能监控
注意事项
-
微信API限制:注意调用频率和参数有效性
-
用户体验:提供友好的授权引导和错误提示
-
安全防护:保护敏感配置信息,验证请求参数
-
性能优化:合理使用缓存,优化网络请求
-
兼容性处理:支持不同版本的微信小程序API
这个实现方案可以作为微信小程序登录功能的标准参考,具有良好的可扩展性和维护性。
更多推荐


所有评论(0)