feat(core): 初始化项目基础配置与核心工具类- 添加.gitignore文件,配置各类IDE和系统忽略规则

- 新增AI聊天控制器,支持WebSocket消息推送
- 实现支付宝配置工具类,支持证书认证支付
- 添加阿里云签名发送工具类
- 创建统一API返回结果封装类
- 配置多环境application配置文件(dev/prod)- 新增用户角色、文章状态、余额变动等常量定义- 添加Controller基类,封装用户信息获取等通用方法
- 新增代码生成器模板文件(add.config.ts.btl和add.tsx.btl)
This commit is contained in:
2025-10-16 17:45:12 +08:00
commit a8661d5752
313 changed files with 29669 additions and 0 deletions

44
.gitignore vendored Normal file
View File

@@ -0,0 +1,44 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/cert/
/src/main/resources/dev/
### macOS ###
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
/file/
/websoft-modules.log

286
README.md Normal file
View File

@@ -0,0 +1,286 @@
<div align="center">
<h1>🚀 WebSoft API</h1>
<p><strong>基于 Spring Boot + MyBatis Plus 的企业级后端API服务</strong></p>
<p>
<img src="https://img.shields.io/badge/Java-1.8+-ED8B00" alt="Java">
<img src="https://img.shields.io/badge/Spring%20Boot-2.5.4-6DB33F" alt="Spring Boot">
<img src="https://img.shields.io/badge/MyBatis%20Plus-3.4.3-blue" alt="MyBatis Plus">
<img src="https://img.shields.io/badge/MySQL-8.0+-4479A1" alt="MySQL">
<img src="https://img.shields.io/badge/Redis-6.0+-DC382D" alt="Redis">
<img src="https://img.shields.io/badge/License-MIT-blue" alt="License">
</p>
</div>
## 📖 项目简介
WebSoft API 是一个基于 **Spring Boot + MyBatis Plus** 构建的现代化企业级后端API服务采用最新的Java技术栈
- **核心框架**Spring Boot 2.5.4 + Spring Security + Spring AOP
- **数据访问**MyBatis Plus 3.4.3 + Druid 连接池
- **数据库**MySQL + Redis
- **文档工具**Swagger 3.0 + Knife4j
- **工具库**Hutool、Lombok、FastJSON
## 项目演示
| 后台管理系统 | https://mp.websoft.top |
|--------|-------------------------------------------------------------------------------------------------------------------------------------|
| 测试账号 | 13800010123,123456
| 正式账号 | [立即注册](https://mp.websoft.top/register/?inviteCode=github) |
| 关注公众号 | ![输入图片说明](https://oss.wsdns.cn/20240327/f1175cc5aae741d3af05484747270bd5.jpeg?x-oss-process=image/resize,m_fixed,w_150/quality,Q_90) |
## 🛠️ 技术栈
### 核心框架
| 技术 | 版本 | 说明 |
|------|------|------|
| Java | 1.8+ | 编程语言 |
| Spring Boot | 2.5.4 | 微服务框架 |
| Spring Security | 5.5.x | 安全框架 |
| MyBatis Plus | 3.4.3 | ORM框架 |
| MySQL | 8.0+ | 关系型数据库 |
| Redis | 6.0+ | 缓存数据库 |
| Druid | 1.2.6 | 数据库连接池 |
### 功能组件
- **Swagger 3.0 + Knife4j** - API文档生成与测试
- **JWT** - 用户认证与授权
- **Hutool** - Java工具类库
- **EasyPOI** - Excel文件处理
- **阿里云OSS** - 对象存储服务
- **微信支付/支付宝** - 支付集成
- **Socket.IO** - 实时通信
- **MQTT** - 物联网消息传输
## 📋 环境要求
### 基础环境
-**Java 1.8+**
- 🗄️ **MySQL 8.0+**
- 🔴 **Redis 6.0+**
- 📦 **Maven 3.6+**
### 开发工具
- **推荐**IntelliJ IDEA / Eclipse
- **插件**Lombok Plugin、MyBatis Plugin
## 🚀 快速开始
### 1. 克隆项目
```bash
git clone https://github.com/websoft-top/mp-java.git
cd mp-java
```
### 2. 数据库配置
```sql
-- 创建数据库
CREATE DATABASE websoft_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 导入数据库脚本(如果有的话)
-- source /path/to/database.sql
```
### 3. 配置文件
编辑 `src/main/resources/application-dev.yml` 文件,配置数据库连接:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/websoft_db?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: your_username
password: your_password
redis:
host: localhost
port: 6379
password: your_redis_password
```
### 4. 启动项目
```bash
# 使用 Maven 启动
mvn spring-boot:run
# 或者使用 IDE 直接运行 WebSoftApplication.java
```
访问 `http://localhost:9200` 即可看到API服务。
### 5. API文档
启动项目后访问以下地址查看API文档
- Swagger UI: `http://localhost:9200/swagger-ui/index.html`
- Knife4j: `http://localhost:9200/doc.html`
## ⚙️ 配置说明
### 数据库配置
`application-dev.yml` 中配置数据库连接:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/websoft_db
username: root
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
```
### Redis配置
```yaml
spring:
redis:
host: localhost
port: 6379
password: your_redis_password
database: 0
```
### 阿里云OSS配置
```yaml
config:
endpoint: https://oss-cn-shenzhen.aliyuncs.com
accessKeyId: your_access_key_id
accessKeySecret: your_access_key_secret
bucketName: your_bucket_name
bucketDomain: https://your-domain.com
```
### 其他配置
- **JWT密钥**`config.token-key` 用于JWT令牌加密
- **文件上传路径**`config.upload-path` 本地文件存储路径
- **邮件服务**配置SMTP服务器用于发送邮件
## 🎯 核心功能
### 🔐 用户认证与授权
- **JWT认证**基于JSON Web Token的用户认证
- **Spring Security**:完整的安全框架集成
- **角色权限**基于RBAC的权限控制
- **图形验证码**:防止恶意登录
### 📝 内容管理系统(CMS)
- **文章管理**:支持富文本内容管理
- **媒体文件**:图片/视频文件上传与管理
- **分类管理**:内容分类与标签管理
- **SEO优化**:搜索引擎优化支持
### 🛒 电商系统
- **商品管理**:商品信息、规格、库存管理
- **订单系统**:完整的订单流程管理
- **支付集成**:支持微信支付、支付宝
- **物流跟踪**快递100物流查询集成
### 🔧 系统管理
- **用户管理**:用户信息维护与管理
- **系统配置**:动态配置管理
- **日志监控**:系统操作日志记录
- **数据备份**:数据库备份与恢复
### 📊 数据分析
- **统计报表**:业务数据统计分析
- **图表展示**:数据可视化展示
- **导出功能**Excel数据导出
- **实时监控**:系统性能监控
## 🏗️ 项目结构
```
src/main/java/com/gxwebsoft/
├── WebSoftApplication.java # 启动类
├── cms/ # 内容管理模块
│ ├── controller/ # 控制器层
│ ├── service/ # 业务逻辑层
│ ├── mapper/ # 数据访问层
│ └── entity/ # 实体类
├── shop/ # 商城模块
│ ├── controller/
│ ├── service/
│ ├── mapper/
│ └── entity/
├── common/ # 公共模块
│ ├── core/ # 核心配置
│ ├── utils/ # 工具类
│ └── exception/ # 异常处理
└── resources/
├── application.yml # 主配置文件
├── application-dev.yml # 开发环境配置
└── application-prod.yml# 生产环境配置
```
## 🔧 开发规范
### 代码结构
- **Controller层**处理HTTP请求参数验证
- **Service层**:业务逻辑处理,事务管理
- **Mapper层**数据访问SQL映射
- **Entity层**:数据实体,数据库表映射
### 命名规范
- **类名**使用大驼峰命名法PascalCase
- **方法名**使用小驼峰命名法camelCase
- **常量**:使用全大写,下划线分隔
- **包名**:使用小写字母,点分隔
## 📚 API文档
项目集成了Swagger和Knife4j提供完整的API文档
### 访问地址
- **Swagger UI**: `http://localhost:9200/swagger-ui/index.html`
- **Knife4j**: `http://localhost:9200/doc.html`
### 主要接口模块
- **用户认证**: `/api/auth/**` - 登录、注册、权限验证
- **用户管理**: `/api/user/**` - 用户CRUD操作
- **内容管理**: `/api/cms/**` - 文章、媒体文件管理
- **商城管理**: `/api/shop/**` - 商品、订单管理
- **系统管理**: `/api/system/**` - 系统配置、日志管理
## 🚀 部署指南
### 开发环境部署
```bash
# 1. 启动MySQL和Redis服务
# 2. 创建数据库并导入初始数据
# 3. 修改配置文件
# 4. 启动应用
mvn spring-boot:run
```
### 生产环境部署
```bash
# 1. 打包应用
mvn clean package -Dmaven.test.skip=true
# 2. 运行jar包
java -jar target/com-gxwebsoft-modules-1.5.0.jar --spring.profiles.active=prod
# 3. 使用Docker部署可选
docker build -t websoft-api .
docker run -d -p 9200:9200 websoft-api
```
## 🤝 贡献指南
1. Fork 本仓库
2. 创建特性分支 (`git checkout -b feature/AmazingFeature`)
3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
4. 推送到分支 (`git push origin feature/AmazingFeature`)
5. 打开 Pull Request
## 📄 许可证
本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情
## 📞 联系我们
- 官网https://websoft.top
- 邮箱170083662@qq.top
- QQ群479713884
---
⭐ 如果这个项目对您有帮助,请给我们一个星标!

427
pom.xml Normal file
View File

@@ -0,0 +1,427 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gxwebsoft</groupId>
<artifactId>com-gxwebsoft-modules</artifactId>
<version>1.5.0</version>
<name>com-gxwebsoft-api</name>
<description>WebSoftApi project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- spring-boot-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring-boot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Jackson JSR310 support for Java 8 time -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- spring-boot-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mysql -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.20</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.3</version>
</dependency>
<!-- mybatis-plus 连表插件-->
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<version>1.4.5</version>
</dependency>
<!-- mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.25</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-extra</artifactId>
<version>5.8.25</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.8.25</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>5.8.25</version>
</dependency>
<!-- easy poi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<!-- tika, 用于FileServer获取content-type -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>2.9.1</version>
</dependency>
<!-- open office, 用于文档转pdf实现在线预览 -->
<dependency>
<groupId>com.github.livesense</groupId>
<artifactId>jodconverter-core</artifactId>
<version>1.0.5</version>
</dependency>
<!-- spring-boot-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 模板引擎, 用于邮件、代码生成等 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.15.10.RELEASE</version>
</dependency>
<!-- SpringDoc OpenAPI 3 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- 图形验证码 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 阿里SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.3</version>
</dependency>
<!--阿里支付 老版本 SDK-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.35.0.ALL</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.77</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.43</version>
</dependency>
<!--二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<!-- socketio -->
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>2.0.2</version>
</dependency>
<!-- 微信支付 APIv3 Java SDK-->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-java</artifactId>
<version>0.2.17</version>
</dependency>
<!-- MQTT -->
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.6.0</version> <!-- 请替换为最新版本号 -->
</dependency>
<!-- 阿里云 OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
<!-- 快递100-->
<dependency>
<groupId>com.github.kuaidi100-api</groupId>
<artifactId>sdk</artifactId>
<version>1.0.13</version>
</dependency>
<!--诺诺开票接口-->
<dependency>
<groupId>com.nuonuo</groupId>
<artifactId>open-sdk</artifactId>
<version>1.0.5.2</version>
</dependency>
<!-- knife4j for SpringDoc OpenAPI -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<!-- 机器翻译 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alimt20181012</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.2.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- 可选:用来做内存缓存 access_token -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
<dependency>
<groupId>com.freewayso</groupId>
<artifactId>image-combiner</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>bailian20231229</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*Mapper.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.project-lombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliYunMaven</id>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
</project>

View File

@@ -0,0 +1,31 @@
package com.gxwebsoft;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.config.MqttProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
/**
* 启动类
* Created by WebSoft on 2018-02-22 11:29:03
*/
@EnableAsync
@EnableTransactionManagement
@MapperScan("com.gxwebsoft.**.mapper")
@EnableConfigurationProperties({ConfigProperties.class, MqttProperties.class})
@SpringBootApplication
@EnableScheduling
@EnableWebSocket
public class WebSoftApplication {
public static void main(String[] args) {
SpringApplication.run(WebSoftApplication.class, args);
}
}

View File

@@ -0,0 +1,93 @@
package com.gxwebsoft.common.core;
/**
* 系统常量
* Created by WebSoft on 2019-10-29 15:55
*/
public class Constants {
/**
* 默认成功码
*/
public static final int RESULT_OK_CODE = 0;
/**
* 默认失败码
*/
public static final int RESULT_ERROR_CODE = 1;
/**
* 默认成功信息
*/
public static final String RESULT_OK_MSG = "操作成功";
/**
* 默认失败信息
*/
public static final String RESULT_ERROR_MSG = "操作失败";
/**
* 无权限错误码
*/
public static final int UNAUTHORIZED_CODE = 403;
/**
* 无权限提示信息
*/
public static final String UNAUTHORIZED_MSG = "没有访问权限";
/**
* 未认证错误码
*/
public static final int UNAUTHENTICATED_CODE = 401;
/**
* 未认证提示信息
*/
public static final String UNAUTHENTICATED_MSG = "请先登录";
/**
* 登录过期错误码
*/
public static final int TOKEN_EXPIRED_CODE = 401;
/**
* 登录过期提示信息
*/
public static final String TOKEN_EXPIRED_MSG = "登录已过期";
/**
* 非法token错误码
*/
public static final int BAD_CREDENTIALS_CODE = 401;
/**
* 非法token提示信息
*/
public static final String BAD_CREDENTIALS_MSG = "请退出重新登录";
/**
* 表示升序的值
*/
public static final String ORDER_ASC_VALUE = "asc";
/**
* 表示降序的值
*/
public static final String ORDER_DESC_VALUE = "desc";
/**
* token通过header传递的名称
*/
public static final String TOKEN_HEADER_NAME = "Authorization";
/**
* token通过参数传递的名称
*/
public static final String TOKEN_PARAM_NAME = "access_token";
/**
* token认证类型
*/
public static final String TOKEN_TYPE = "Bearer";
}

View File

@@ -0,0 +1,41 @@
package com.gxwebsoft.common.core.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.math.BigDecimal;
/**
* BigDecimal 自定义反序列化器
* 处理null值和空字符串避免反序列化异常
*
* @author WebSoft
* @since 2025-01-15
*/
@Slf4j
public class BigDecimalDeserializer extends JsonDeserializer<BigDecimal> {
@Override
public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
if (value == null || value.trim().isEmpty() || "null".equals(value)) {
return null;
}
try {
return new BigDecimal(value);
} catch (NumberFormatException e) {
log.warn("无法解析BigDecimal值: {}, 返回null", value);
return null;
}
}
@Override
public BigDecimal getNullValue(DeserializationContext ctxt) {
return null;
}
}

View File

@@ -0,0 +1,213 @@
package com.gxwebsoft.common.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 证书配置属性类
* 支持开发环境从classpath加载证书生产环境从Docker挂载卷加载证书
*
* @author 科技小王子
* @since 2024-07-26
*/
@Data
@Component
@ConfigurationProperties(prefix = "certificate")
public class CertificateProperties {
/**
* 证书加载模式
* CLASSPATH: 从classpath加载开发环境
* FILESYSTEM: 从文件系统加载(生产环境)
* VOLUME: 从Docker挂载卷加载容器环境
*/
private LoadMode loadMode = LoadMode.CLASSPATH;
/**
* Docker挂载卷证书根路径
*/
private String certRootPath = "/www/wwwroot/file.ws";
/**
* 开发环境证书路径前缀
*/
private String devCertPath = "dev";
/**
* 微信支付证书配置
*/
private WechatPayConfig wechatPay = new WechatPayConfig();
/**
* 支付宝证书配置
*/
private AlipayConfig alipay = new AlipayConfig();
/**
* 证书加载模式枚举
*/
public enum LoadMode {
CLASSPATH, // 从classpath加载
FILESYSTEM, // 从文件系统加载
VOLUME // 从Docker挂载卷加载
}
/**
* 微信支付证书配置
*/
@Data
public static class WechatPayConfig {
/**
* 开发环境配置
*/
private DevConfig dev = new DevConfig();
/**
* 生产环境基础路径
*/
private String prodBasePath = "/file";
/**
* 微信支付证书目录名
*/
private String certDir = "wechat";
@Data
public static class DevConfig {
/**
* APIv3密钥
*/
private String apiV3Key;
/**
* 商户私钥证书文件名
*/
private String privateKeyFile = "apiclient_key.pem";
/**
* 商户证书文件名
*/
private String apiclientCertFile = "apiclient_cert.pem";
/**
* 微信支付平台证书文件名
*/
private String wechatpayCertFile = "wechatpay_cert.pem";
}
}
/**
* 支付宝证书配置
*/
@Data
public static class AlipayConfig {
/**
* 支付宝证书目录名
*/
private String certDir = "alipay";
/**
* 应用私钥文件名
*/
private String appPrivateKeyFile = "app_private_key.pem";
/**
* 应用公钥证书文件名
*/
private String appCertPublicKeyFile = "appCertPublicKey.crt";
/**
* 支付宝公钥证书文件名
*/
private String alipayCertPublicKeyFile = "alipayCertPublicKey.crt";
/**
* 支付宝根证书文件名
*/
private String alipayRootCertFile = "alipayRootCert.crt";
}
/**
* 获取证书文件的完整路径
*
* @param certType 证书类型wechat/alipay
* @param fileName 文件名
* @return 完整路径
*/
public String getCertificatePath(String certType, String fileName) {
switch (loadMode) {
case CLASSPATH:
return devCertPath + "/" + certType + "/" + fileName;
case FILESYSTEM:
return System.getProperty("user.dir") + "/certs/" + certType + "/" + fileName;
case VOLUME:
return certRootPath + "/" + certType + "/" + fileName;
default:
throw new IllegalArgumentException("不支持的证书加载模式: " + loadMode);
}
}
/**
* 获取微信支付证书路径
*
* @param fileName 文件名
* @return 完整路径
*/
public String getWechatPayCertPath(String fileName) {
// 生产环境特殊处理:数据库中存储的路径需要拼接到 /file/ 目录下
if (loadMode == LoadMode.VOLUME) {
// 修复路径拼接逻辑:数据库中存储的路径如果已经包含 /file则直接拼接
if (fileName.startsWith("/file/")) {
// 路径已经包含 /file/ 前缀,直接拼接到根路径
return certRootPath + fileName;
} else if (fileName.startsWith("file/")) {
// 路径包含 file/ 前缀,添加根路径和斜杠
return certRootPath + "/" + fileName;
} else {
// 路径不包含 file 前缀,添加完整的 /file/ 前缀
return certRootPath + "/file/" + fileName;
}
} else {
// 开发环境和文件系统模式使用原有逻辑
return getCertificatePath(wechatPay.getCertDir(), fileName);
}
}
/**
* 获取支付宝证书路径
*
* @param fileName 文件名
* @return 完整路径
*/
public String getAlipayCertPath(String fileName) {
return getCertificatePath(alipay.getCertDir(), fileName);
}
/**
* 检查证书加载模式是否为classpath模式
*
* @return true if classpath mode
*/
public boolean isClasspathMode() {
return LoadMode.CLASSPATH.equals(loadMode);
}
/**
* 检查证书加载模式是否为文件系统模式
*
* @return true if filesystem mode
*/
public boolean isFilesystemMode() {
return LoadMode.FILESYSTEM.equals(loadMode);
}
/**
* 检查证书加载模式是否为挂载卷模式
*
* @return true if volume mode
*/
public boolean isVolumeMode() {
return LoadMode.VOLUME.equals(loadMode);
}
}

View File

@@ -0,0 +1,105 @@
package com.gxwebsoft.common.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 系统配置属性
*
* @author WebSoft
* @since 2021-08-30 17:58:16
*/
@Data
@ConfigurationProperties(prefix = "config")
public class ConfigProperties {
/**
* 文件上传磁盘位置
*/
private Integer uploadLocation = 0;
/**
* 文件上传是否使用uuid命名
*/
private Boolean uploadUuidName = true;
/**
* 文件上传生成缩略图的大小(kb)
*/
private Integer thumbnailSize = 60;
/**
* OpenOffice的安装目录
*/
private String openOfficeHome;
/**
* swagger扫描包
*/
private String swaggerBasePackage;
/**
* swagger文档标题
*/
private String swaggerTitle;
/**
* swagger文档描述
*/
private String swaggerDescription;
/**
* swagger文档版本号
*/
private String swaggerVersion;
/**
* swagger地址
*/
private String swaggerHost;
/**
* token过期时间, 单位秒
*/
private Long tokenExpireTime = 60 * 60 * 365 * 24L;
/**
* token快要过期自动刷新时间, 单位分钟
*/
private int tokenRefreshTime = 30;
/**
* 生成token的密钥Key的base64字符
*/
private String tokenKey;
/**
* 文件上传目录
*/
private String uploadPath;
/**
* 本地文件上传目录(开发环境)
*/
private String localUploadPath;
/**
* 文件服务器
*/
private String fileServer;
/**
* 网关地址
*/
private String serverUrl;
/**
* 阿里云存储 OSS
* Endpoint
*/
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String bucketDomain;
}

View File

@@ -0,0 +1,15 @@
package com.gxwebsoft.common.core.config;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.util.ArrayList;
import java.util.List;
public class HttpMessageConverter extends MappingJackson2HttpMessageConverter {
public HttpMessageConverter(){
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
setSupportedMediaTypes(mediaTypes);
}
}

View File

@@ -0,0 +1,26 @@
package com.gxwebsoft.common.core.config;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Jackson配置类
* 确保JSR310模块被正确注册
*
* @author WebSoft
* @since 2025-01-12
*/
@Configuration
public class JacksonConfig {
/**
* 确保JavaTimeModule被注册
*/
@Bean
@ConditionalOnMissingBean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
}

View File

@@ -0,0 +1,29 @@
package com.gxwebsoft.common.core.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* LocalDateTime自定义反序列化器
*
* @author WebSoft
* @since 2025-01-12
*/
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
if (value != null && !value.isEmpty()) {
return LocalDateTime.parse(value, FORMATTER);
}
return null;
}
}

View File

@@ -0,0 +1,27 @@
package com.gxwebsoft.common.core.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* LocalDateTime自定义序列化器
*
* @author WebSoft
* @since 2025-01-12
*/
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null) {
gen.writeString(value.format(FORMATTER));
}
}
}

View File

@@ -0,0 +1,72 @@
package com.gxwebsoft.common.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* MQTT配置属性
*
* @author 科技小王子
* @since 2025-07-02
*/
@Data
@Component
@ConfigurationProperties(prefix = "mqtt")
public class MqttProperties {
/**
* 是否启用MQTT服务
*/
private boolean enabled = false;
/**
* MQTT服务器地址
*/
private String host = "tcp://127.0.0.1:1883";
/**
* 用户名
*/
private String username = "";
/**
* 密码
*/
private String password = "";
/**
* 客户端ID前缀
*/
private String clientIdPrefix = "mqtt_client_";
/**
* 订阅主题
*/
private String topic = "/SW_GPS/#";
/**
* QoS等级
*/
private int qos = 2;
/**
* 连接超时时间(秒)
*/
private int connectionTimeout = 10;
/**
* 心跳间隔(秒)
*/
private int keepAliveInterval = 20;
/**
* 是否自动重连
*/
private boolean autoReconnect = true;
/**
* 是否清除会话
*/
private boolean cleanSession = false;
}

View File

@@ -0,0 +1,138 @@
package com.gxwebsoft.common.core.config;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.system.entity.User;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* MybatisPlus配置
*
* @author WebSoft
* @since 2018-02-22 11:29:28
*/
@Configuration
public class MybatisPlusConfig {
@Resource
private RedisUtil redisUtil;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 多租户插件配置
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
@Override
public Expression getTenantId() {
String tenantId = null;
try {
// 从Spring上下文获取当前请求
HttpServletRequest request = getCurrentRequest();
if (request != null) {
// 从请求头拿ID
tenantId = request.getHeader("tenantId");
if(tenantId != null){
return new LongValue(tenantId);
}
// 从域名拿ID
String Domain = request.getHeader("Domain");
if (StrUtil.isNotBlank(Domain)) {
String key = "Domain:" + Domain;
tenantId = redisUtil.get(key);
if(tenantId != null){
System.out.println("从域名拿TID = " + tenantId);
return new LongValue(tenantId);
}
}
}
} catch (Exception e) {
// 忽略异常,使用默认逻辑
}
return getLoginUserTenantId();
}
@Override
public boolean ignoreTable(String tableName) {
// 系统级别的表始终忽略租户隔离
return Arrays.asList(
"sys_tenant",
"sys_dictionary",
"sys_dictionary_data",
"apps_test_data",
"cms_lang"
// "hjm_car",
// "hjm_fence"
// "cms_website"
// "sys_user"
// "cms_domain"
// "shop_order_goods",
// "shop_goods"
// "shop_users",
// "shop_order" // 移除shop_order改为通过注解控制
// "shop_order_info",
// "booking_user_invoice"
).contains(tableName);
}
};
TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
// 分页插件配置
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
paginationInnerInterceptor.setMaxLimit(2000L);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
/**
* 获取当前登录用户的租户id
*
* @return Integer
*/
public Expression getLoginUserTenantId() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
return new LongValue(((User) object).getTenantId());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new NullValue();
}
/**
* 获取当前HTTP请求
*/
private HttpServletRequest getCurrentRequest() {
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes != null ? attributes.getRequest() : null;
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,29 @@
package com.gxwebsoft.common.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getMessageConverters().add(new HttpMessageConverter());
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// ms
factory.setReadTimeout(60000);
// ms
factory.setConnectTimeout(60000);
return factory;
}
}

View File

@@ -0,0 +1,62 @@
package com.gxwebsoft.common.core.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @Author ds
* @Date 2022-05-05
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
/**
* spring的应用上下文
*/
private static ApplicationContext applicationContext;
/**
* 初始化时将应用上下文设置进applicationContext
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
/**
* 根据bean名称获取某个bean对象
*
* @param name bean名称
* @return Object
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
* 根据bean的class获取某个bean对象
* @param beanClass
* @param <T>
* @return
* @throws BeansException
*/
public static <T> T getBean(Class<T> beanClass) throws BeansException {
return applicationContext.getBean(beanClass);
}
/**
* 获取spring.profiles.active
* @return
*/
public static String getProfile(){
return getApplicationContext().getEnvironment().getActiveProfiles()[0];
}
}

View File

@@ -0,0 +1,111 @@
package com.gxwebsoft.common.core.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.Components;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* SpringDoc OpenAPI 配置
*
* @author WebSoft
* @since 2018-02-22 11:29:05
*/
@Configuration
public class SwaggerConfig {
@Resource
private ConfigProperties config;
/**
* 全局 OpenAPI 配置
*/
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title(config.getSwaggerTitle())
.description(config.getSwaggerDescription())
.version(config.getSwaggerVersion())
.contact(new Contact()
.name("科技小王子")
.url("https://www.gxwebsoft.com")
.email("170083662@qq.com"))
.termsOfService(config.getServerUrl() + "/system"))
.components(new Components()
.addSecuritySchemes("Authorization",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.name("Authorization")
.description("JWT Authorization header using the Bearer scheme")))
.addSecurityItem(new SecurityRequirement().addList("Authorization"));
}
/**
* Common 模块分组
*/
@Bean
public GroupedOpenApi commonApi() {
return GroupedOpenApi.builder()
.group("common")
.pathsToMatch("/api/common/**", "/api/system/**", "/api/user/**", "/api/role/**", "/api/menu/**")
.packagesToScan("com.gxwebsoft.common")
.build();
}
/**
* CMS 模块分组
*/
@Bean
public GroupedOpenApi cmsApi() {
return GroupedOpenApi.builder()
.group("cms")
.pathsToMatch("/api/cms/**")
.packagesToScan("com.gxwebsoft.cms")
.build();
}
/**
* Shop 模块分组
*/
@Bean
public GroupedOpenApi shopApi() {
return GroupedOpenApi.builder()
.group("shop")
.pathsToMatch("/api/shop/**")
.packagesToScan("com.gxwebsoft.shop")
.build();
}
/**
* OA 模块分组
*/
@Bean
public GroupedOpenApi oaApi() {
return GroupedOpenApi.builder()
.group("oa")
.pathsToMatch("/api/oa/**")
.packagesToScan("com.gxwebsoft.oa")
.build();
}
/**
* 其他模块分组
*/
@Bean
public GroupedOpenApi otherApi() {
return GroupedOpenApi.builder()
.group("other")
.pathsToMatch("/api/docs/**", "/api/project/**", "/api/pwl/**", "/api/bszx/**", "/api/hjm/**")
.packagesToScan("com.gxwebsoft.docs", "com.gxwebsoft.project", "com.gxwebsoft.pwl", "com.gxwebsoft.bszx", "com.gxwebsoft.hjm")
.build();
}
}

View File

@@ -0,0 +1,31 @@
package com.gxwebsoft.common.core.config;
import com.gxwebsoft.common.core.Constants;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc配置, 拦截器、资源映射等都在此配置
*
* @author WebSoft
* @since 2019-06-12 10:11:16
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 支持跨域访问
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders("*")
.exposedHeaders(Constants.TOKEN_HEADER_NAME)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
.allowCredentials(true)
.maxAge(3600);
}
}

View File

@@ -0,0 +1,8 @@
package com.gxwebsoft.common.core.constants;
public class AppUserConstants {
// 成员角色
public static final Integer TRIAL = 10; // 体验成员
public static final Integer DEVELOPER = 20; // 开发者
public static final Integer ADMINISTRATOR = 30; // 管理员
}

View File

@@ -0,0 +1,6 @@
package com.gxwebsoft.common.core.constants;
public class ArticleConstants extends BaseConstants {
public static final String[] ARTICLE_STATUS = {"已发布","待审核","已驳回","违规内容"};
public static final String CACHE_KEY_ARTICLE = "Article:";
}

View File

@@ -0,0 +1,10 @@
package com.gxwebsoft.common.core.constants;
public class BalanceConstants {
// 余额变动场景
public static final Integer BALANCE_RECHARGE = 10; // 用户充值
public static final Integer BALANCE_USE = 20; // 用户消费
public static final Integer BALANCE_RE_LET = 21; // 续租
public static final Integer BALANCE_ADMIN = 30; // 管理员操作
public static final Integer BALANCE_REFUND = 40; // 订单退款
}

View File

@@ -0,0 +1,5 @@
package com.gxwebsoft.common.core.constants;
public class BaseConstants {
public static final String[] STATUS = {"未定义","显示","隐藏"};
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.common.core.constants;
public class OrderConstants {
// 支付方式
public static final String PAY_METHOD_BALANCE = "10"; // 余额支付
public static final String PAY_METHOD_WX = "20"; // 微信支付
public static final String PAY_METHOD_ALIPAY = "30"; // 支付宝支付
public static final String PAY_METHOD_OTHER = "40"; // 其他支付
// 付款状态
public static final Integer PAY_STATUS_NO_PAY = 10; // 未付款
public static final Integer PAY_STATUS_SUCCESS = 20; // 已付款
// 发货状态
public static final Integer DELIVERY_STATUS_NO = 10; // 未发货
public static final Integer DELIVERY_STATUS_YES = 20; // 已发货
public static final Integer DELIVERY_STATUS_30 = 30; // 部分发货
// 收货状态
public static final Integer RECEIPT_STATUS_NO = 10; // 未收货
public static final Integer RECEIPT_STATUS_YES = 20; // 已收货
public static final Integer RECEIPT_STATUS_RETURN = 30; // 已退货
// 订单状态
public static final Integer ORDER_STATUS_DOING = 10; // 进行中
public static final Integer ORDER_STATUS_CANCEL = 20; // 已取消
public static final Integer ORDER_STATUS_TO_CANCEL = 21; // 待取消
public static final Integer ORDER_STATUS_COMPLETED = 30; // 已完成
// 订单结算状态
public static final Integer ORDER_SETTLED_YES = 1; // 已结算
public static final Integer ORDER_SETTLED_NO = 0; // 未结算
}

View File

@@ -0,0 +1,12 @@
package com.gxwebsoft.common.core.constants;
public class PlatformConstants {
public static final String MP_OFFICIAL = "MP-OFFICIAL"; // 微信公众号
public static final String MP_WEIXIN = "MP-WEIXIN"; // 微信小程序
public static final String MP_ALIPAY = "MP-ALIPAY"; // 支付宝小程序
public static final String WEB = "WEB"; // web同H5
public static final String H5 = "H5"; // H5推荐使用 WEB
public static final String APP = "APP"; // App
public static final String MP_BAIDU = "MP-BAIDU"; // 百度小程序
public static final String MP_TOUTIAO = "MP-TOUTIAO"; // 百度小程序
}

View File

@@ -0,0 +1,9 @@
package com.gxwebsoft.common.core.constants;
public class ProfitConstants {
// 收益类型
public static final Integer PROFIT_TYPE10 = 10; // 推广收益
public static final Integer PROFIT_TYPE20 = 20; // 团队收益
public static final Integer PROFIT_TYPE30 = 30; // 门店收益
public static final Integer PROFIT_TYPE40 = 30; // 区域收益
}

View File

@@ -0,0 +1,10 @@
package com.gxwebsoft.common.core.constants;
public class QRCodeConstants {
// 二维码类型
public static final String USER_QRCODE = "user"; // 用户二维码
public static final String TASK_QRCODE = "task"; // 工单二维码
public static final String ARTICLE_QRCODE = "article"; // 文章二维码
public static final String GOODS_QRCODE = "goods"; // 商品二维码
public static final String DIY_QRCODE = "diy"; // 工单二维码
}

View File

@@ -0,0 +1,47 @@
package com.gxwebsoft.common.core.constants;
public class RedisConstants {
// 短信验证码Key
public static final String SMS_CODE_KEY = "sms";
// 验证码过期时间
public static final Long SMS_CODE_TTL = 5L;
// 微信凭证access-token
public static final String ACCESS_TOKEN_KEY = "access-token";
// 空值防止击穿数据库
public static final Long CACHE_NULL_TTL = 2L;
// 商户信息
public static final String MERCHANT_KEY = "merchant";
// 添加商户定位点
public static final String MERCHANT_GEO_KEY = "merchant-geo";
// token
public static final String TOKEN_USER_ID = "cache:token:";
// 排行榜
public static final String USER_RANKING_BY_APPS = "userRankingByApps";
// 搜索历史
public static final String SEARCH_HISTORY = "searchHistory";
// 租户系统设置信息
public static final String TEN_ANT_SETTING_KEY = "setting";
// 排行榜Key
public static final String USER_RANKING_BY_APPS_5 = "cache5:userRankingByApps";
// 扫码登录相关key
public static final String QR_LOGIN_TOKEN_KEY = "qr-login:token:"; // 扫码登录token前缀
public static final Long QR_LOGIN_TOKEN_TTL = 300L; // 扫码登录token过期时间(5分钟)
public static final String QR_LOGIN_STATUS_PENDING = "pending"; // 等待扫码
public static final String QR_LOGIN_STATUS_SCANNED = "scanned"; // 已扫码
public static final String QR_LOGIN_STATUS_CONFIRMED = "confirmed"; // 已确认
public static final String QR_LOGIN_STATUS_EXPIRED = "expired"; // 已过期
// 哗啦啦key
public static final String getAllShop = "allShop";
public static final String getBaseInfo = "baseInfo";
public static final String getFoodClassCategory = "foodCategory";
public static final String getOpenFood = "openFood";
public static final String haulalaGeoKey = "cache10:hualala-geo";
public static final String HLL_CART_KEY = "hll-cart"; // hll-cart[shopId]:[userId]
public static final String HLL_CART_FOOD_KEY = "hll-cart-list"; // hll-cart-list[shopId]:[userId]
}

View File

@@ -0,0 +1,22 @@
package com.gxwebsoft.common.core.constants;
public class TaskConstants {
// 工单进度
public static final Integer TOBEARRANGED = 0; // 待安排
public static final Integer PENDING = 1; // 待处理
public static final Integer PROCESSING = 2; // 处理中
public static final Integer TOBECONFIRMED = 3; // 待评价
public static final Integer COMPLETED = 4; // 已完成
public static final Integer CLOSED = 5; // 已关闭
// 工单状态
public static final Integer TASK_STATUS_0 = 0; // 待处理
public static final Integer TASK_STATUS_1 = 1; // 已完成
// 操作类型
public static final String ACTION_1 = "派单";
public static final String ACTION_2 = "已解决";
public static final String ACTION_3 = "关单";
public static final String ACTION_4 = "分享";
public static final String ACTION_5 = "编辑";
}

View File

@@ -0,0 +1,14 @@
package com.gxwebsoft.common.core.constants;
public class WebsiteConstants extends BaseConstants {
// 运行状态 0未开通 1运行中 2维护中 3已关闭 4已欠费停机 5违规关停
public static final String[] WEBSITE_STATUS_NAME = {"未开通","运行中","维护中","已关闭","已欠费停机","违规关停"};
// 状态图标
public static final String[] WEBSITE_STATUS_ICON = {"error","success","warning","error","error","error"};
// 关闭原因
public static final String[] WEBSITE_STATUS_TEXT = {"产品未开通","","系统升级维护","","已欠费停机","违规关停"};
// 跳转地址
public static final String[] WEBSITE_STATUS_URL = {"https://websoft.top","","","","https://websoft.top/user","https://websoft.top/user"};
// 跳转按钮文字
public static final String[] WEBSITE_STATUS_BTN_TEXT = {"立即开通","","","","立即续费","申请解封"};
}

View File

@@ -0,0 +1,6 @@
package com.gxwebsoft.common.core.constants;
public class WxOfficialConstants {
// 获取 Access token
public static final String GET_ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
}

View File

@@ -0,0 +1,48 @@
package com.gxwebsoft.common.core.exception;
import com.gxwebsoft.common.core.Constants;
/**
* 自定义业务异常
*
* @author WebSoft
* @since 2018-02-22 11:29:28
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
public BusinessException() {
this(Constants.RESULT_ERROR_MSG);
}
public BusinessException(String message) {
this(Constants.RESULT_ERROR_CODE, message);
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}

View File

@@ -0,0 +1,89 @@
package com.gxwebsoft.common.core.exception;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
/**
* 全局异常处理器
*
* @author WebSoft
* @since 2018-02-22 11:29:30
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
@ResponseBody
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ApiResult<?> methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e,
HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.RESULT_ERROR_CODE, "请求方式不正确").setError(e.toString());
}
@ResponseBody
@ExceptionHandler(AccessDeniedException.class)
public ApiResult<?> accessDeniedExceptionHandler(AccessDeniedException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG).setError(e.toString());
}
@ResponseBody
@ExceptionHandler(BusinessException.class)
public ApiResult<?> businessExceptionHandler(BusinessException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(e.getCode(), e.getMessage());
}
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResult<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
FieldError fieldError = e.getBindingResult().getFieldError();
String message = fieldError != null ? fieldError.getDefaultMessage() : "参数验证失败";
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message);
}
@ResponseBody
@ExceptionHandler(BindException.class)
public ApiResult<?> bindExceptionHandler(BindException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
FieldError fieldError = e.getBindingResult().getFieldError();
String message = fieldError != null ? fieldError.getDefaultMessage() : "参数绑定失败";
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message);
}
@ResponseBody
@ExceptionHandler(ConstraintViolationException.class)
public ApiResult<?> constraintViolationExceptionHandler(ConstraintViolationException e, HttpServletResponse response) {
CommonUtil.addCrossHeaders(response);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
String message = violations.isEmpty() ? "参数验证失败" : violations.iterator().next().getMessage();
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message);
}
@ResponseBody
@ExceptionHandler(Throwable.class)
public ApiResult<?> exceptionHandler(Throwable e, HttpServletResponse response) {
logger.error(e.getMessage(), e);
CommonUtil.addCrossHeaders(response);
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG).setError(e.toString());
}
}

View File

@@ -0,0 +1,29 @@
package com.gxwebsoft.common.core.security;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.utils.CommonUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 没有访问权限异常处理
*
* @author WebSoft
* @since 2020-03-25 00:35:03
*/
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
throws IOException, ServletException {
CommonUtil.responseError(response, Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG, e.getMessage());
}
}

View File

@@ -0,0 +1,30 @@
package com.gxwebsoft.common.core.security;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.utils.CommonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 没有登录异常处理
*
* @author WebSoft
* @since 2020-03-25 00:35:03
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException, ServletException {
// CommonUtil.responseError(response, Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG,
// e.getMessage());
}
}

View File

@@ -0,0 +1,118 @@
package com.gxwebsoft.common.core.security;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.utils.SignCheckUtil;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* 处理携带token的请求过滤器
*
* @author WebSoft
* @since 2020-03-30 20:48:05
*/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Resource
private ConfigProperties configProperties;
@Value("${spring.profiles.active}")
String active;
@Resource
private RedisUtil redisUtil;
// 是否读取用户信息
public static Boolean isReadUserInfo = true;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String access_token = JwtUtil.getAccessToken(request);
if (StrUtil.isNotBlank(access_token)) {
try {
// 解析token
Claims claims = JwtUtil.parseToken(access_token, configProperties.getTokenKey());
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
// 请求主服务器获取用户信息
if (isReadUserInfo) {
HashMap<String, Object> map = new HashMap<>();
map.put("username", jwtSubject.getUsername());
map.put("tenantId", jwtSubject.getTenantId());
// 链式构建请求
String result = HttpRequest.post(configProperties.getServerUrl() + "/auth/user")
.header("Authorization", access_token)
.header("Tenantid", jwtSubject.getTenantId().toString())
.body(JSONUtil.toJSONString(map))//表单内容
.timeout(20000)//超时,毫秒
.execute().body();
// 校验服务器域名白名单
final SignCheckUtil checkUtil = new SignCheckUtil();
String key = "WhiteDomain:" + jwtSubject.getTenantId();
List<String> whiteDomains = redisUtil.get(key, List.class);
// 生产环境
if (active.equals("prod") && !checkUtil.checkWhiteDomains(whiteDomains, request.getServerName())) {
throw new UsernameNotFoundException("The requested domain name is not on the whitelist");
}
JSONObject jsonObject = JSONObject.parseObject(result);
if(jsonObject.getString("code").equals("401")){
throw new UsernameNotFoundException("Username not found");
}
final String data = jsonObject.getString("data");
final User user = JSONObject.parseObject(data, User.class);
List<Menu> authorities = user.getAuthorities().stream()
.filter(m -> StrUtil.isNotBlank(m.getAuthority())).collect(Collectors.toList());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
user, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
// token将要过期签发新token, 防止突然退出登录
// long expiration = (claims.getExpiration().getTime() - new Date().getTime()) / 1000 / 60;
// if (expiration < configProperties.getTokenRefreshTime()) {
// String token = JwtUtil.buildToken(jwtSubject, configProperties.getTokenExpireTime(),
// configProperties.getTokenKey());
// response.addHeader(Constants.TOKEN_HEADER_NAME, token);
// loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_REFRESH, null,
// user.getTenantId(), request);
// }
}
} catch (ExpiredJwtException e) {
CommonUtil.responseError(response, Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG,
e.getMessage());
return;
} catch (Exception e) {
CommonUtil.responseError(response, Constants.BAD_CREDENTIALS_CODE, Constants.BAD_CREDENTIALS_MSG,
e.toString());
return;
}
}
chain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,31 @@
package com.gxwebsoft.common.core.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* Jwt载体
*
* @author WebSoft
* @since 2021-09-03 00:11:12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtSubject implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 账号
*/
private String username;
/**
* 租户id
*/
private Integer tenantId;
}

View File

@@ -0,0 +1,141 @@
package com.gxwebsoft.common.core.security;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.utils.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Date;
/**
* JWT工具类
*
* @author WebSoft
* @since 2018-01-21 16:30:59
*/
public class JwtUtil {
/**
* 获取请求中的access_token
*
* @param request HttpServletRequest
* @return String
*/
public static String getAccessToken(HttpServletRequest request) {
String access_token = ServletUtil.getHeaderIgnoreCase(request, Constants.TOKEN_HEADER_NAME);
if (StrUtil.isNotBlank(access_token)) {
if (access_token.startsWith(Constants.TOKEN_TYPE)) {
access_token = StrUtil.removePrefix(access_token, Constants.TOKEN_TYPE).trim();
}
} else {
access_token = request.getParameter(Constants.TOKEN_PARAM_NAME);
}
return access_token;
}
/**
* 生成token
*
* @param subject 载体
* @param expire 过期时间
* @param base64EncodedKey base64编码的Key
* @return token
*/
public static String buildToken(JwtSubject subject, Long expire, String base64EncodedKey) {
return buildToken(JSONUtil.toJSONString(subject), expire, decodeKey(base64EncodedKey));
}
/**
* 生成token
*
* @param subject 载体
* @param expire 过期时间
* @param key 密钥
* @return token
*/
public static String buildToken(String subject, Long expire, Key key) {
Date expireDate = new Date(new Date().getTime() + 1000 * expire);
return Jwts.builder()
.setSubject(subject)
.setExpiration(expireDate)
.setIssuedAt(new Date())
.signWith(key)
.compact();
}
/**
* 解析token
*
* @param token token
* @param base64EncodedKey base64编码的Key
* @return Claims
*/
public static Claims parseToken(String token, String base64EncodedKey) {
return parseToken(token, decodeKey(base64EncodedKey));
}
/**
* 解析token
*
* @param token token
* @param key 密钥
* @return Claims
*/
public static Claims parseToken(String token, Key key) {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
}
/**
* 获取JwtSubject
*
* @param claims Claims
* @return JwtSubject
*/
public static JwtSubject getJwtSubject(Claims claims) {
return JSONUtil.parseObject(claims.getSubject(), JwtSubject.class);
}
/**
* 生成Key
*
* @return Key
*/
public static Key randomKey() {
return Keys.secretKeyFor(SignatureAlgorithm.HS256);
}
/**
* base64编码key
*
* @return String
*/
public static String encodeKey(Key key) {
return Encoders.BASE64.encode(key.getEncoded());
}
/**
* base64编码Key
*
* @param base64EncodedKey base64编码的key
* @return Key
*/
public static Key decodeKey(String base64EncodedKey) {
if (StrUtil.isBlank(base64EncodedKey)) {
return null;
}
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(base64EncodedKey));
}
}

View File

@@ -0,0 +1,113 @@
package com.gxwebsoft.common.core.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;
/**
* Spring Security配置
*
* @author WebSoft
* @since 2020-03-23 18:04:52
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
@Resource
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
@Resource
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Resource
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/file/**","/**", "/api/captcha", "/")
.permitAll()
.antMatchers(
"/api/login",
"/api/qr-login/**",
"/api/register",
"/api/cms/website/createWebsite",
"/druid/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/webjars/**",
"/v2/api-docs",
"/v3/api-docs",
"/swagger-ui/**",
"/doc.html",
"/api/open/**",
"/hxz/v1/**",
"/api/sendSmsCaptcha",
"/api/login-alipay/*",
"/api/wx-login/loginByMpWxPhone",
"/api/shop/payment/mp-alipay/notify",
"/api/shop/payment/mp-alipay/test/**",
"/api/shop/payment/mp-alipay/getPhoneNumber",
"/api/cms/cms-order/**",
"/api/shop/shop-order/notify/**",
"/api/mp/mp/component_verify_ticket",
"/api/mp/mp/callback",
"/api/shop/test/**",
"/api/test/payment-debug/**",
"/api/shop/wx-login/**",
"/api/shop/wx-native-pay/**",
"/api/shop/wx-pay/**",
"/api/bszx/bszx-pay/notify/**",
"/api/wxWorkQrConnect",
"/WW_verify_QMv7HoblYU6z63bb.txt",
"/5zbYEPkyV4.txt",
"/api/love/user-plan-log/wx-pay/**",
"/api/cms/form-record",
"/api/shop/merchant-account/getMerchantAccountByPhone",
"/api/hjm/hjm-car/**",
"/api/chat/**",
"/api/shop/getShopInfo",
"/api/shop/shop-order/test",
"/api/qr-code/**"
)
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.cors()
.and()
.logout()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.exceptionHandling()
.accessDeniedHandler(jwtAccessDeniedHandler)
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@@ -0,0 +1,253 @@
package com.gxwebsoft.common.core.service;
import com.gxwebsoft.common.core.config.CertificateProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 证书健康检查服务
* 提供证书状态检查和健康监控功能
*
* @author 科技小王子
* @since 2024-07-26
*/
@Slf4j
@Service
public class CertificateHealthService {
private final CertificateService certificateService;
private final CertificateProperties certificateProperties;
public CertificateHealthService(CertificateService certificateService,
CertificateProperties certificateProperties) {
this.certificateService = certificateService;
this.certificateProperties = certificateProperties;
}
/**
* 自定义健康检查结果类
*/
public static class HealthResult {
private final String status;
private final Map<String, Object> details;
public HealthResult(String status, Map<String, Object> details) {
this.status = status;
this.details = details;
}
public String getStatus() {
return status;
}
public Map<String, Object> getDetails() {
return details;
}
public static HealthResult up(Map<String, Object> details) {
return new HealthResult("UP", details);
}
public static HealthResult down(Map<String, Object> details) {
return new HealthResult("DOWN", details);
}
}
public HealthResult health() {
try {
Map<String, Object> details = new HashMap<>();
boolean allHealthy = true;
// 检查微信支付证书
Map<String, Object> wechatHealth = checkWechatPayCertificates();
details.put("wechatPay", wechatHealth);
if (!(Boolean) wechatHealth.get("healthy")) {
allHealthy = false;
}
// 检查支付宝证书
Map<String, Object> alipayHealth = checkAlipayCertificates();
details.put("alipay", alipayHealth);
if (!(Boolean) alipayHealth.get("healthy")) {
allHealthy = false;
}
// 添加系统信息
details.put("loadMode", certificateProperties.getLoadMode());
details.put("certRootPath", certificateProperties.getCertRootPath());
if (allHealthy) {
return HealthResult.up(details);
} else {
return HealthResult.down(details);
}
} catch (Exception e) {
log.error("证书健康检查失败", e);
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("error", e.getMessage());
return HealthResult.down(errorDetails);
}
}
/**
* 检查微信支付证书健康状态
*/
private Map<String, Object> checkWechatPayCertificates() {
Map<String, Object> health = new HashMap<>();
boolean healthy = true;
Map<String, Object> certificates = new HashMap<>();
CertificateProperties.WechatPayConfig wechatConfig = certificateProperties.getWechatPay();
// 检查私钥证书
String privateKeyFile = wechatConfig.getDev().getPrivateKeyFile();
boolean privateKeyExists = certificateService.certificateExists("wechat", privateKeyFile);
certificates.put("privateKey", Map.of(
"file", privateKeyFile,
"exists", privateKeyExists,
"path", certificateService.getWechatPayCertPath(privateKeyFile)
));
if (!privateKeyExists) healthy = false;
// 检查商户证书
String apiclientCertFile = wechatConfig.getDev().getApiclientCertFile();
boolean apiclientCertExists = certificateService.certificateExists("wechat", apiclientCertFile);
certificates.put("apiclientCert", Map.of(
"file", apiclientCertFile,
"exists", apiclientCertExists,
"path", certificateService.getWechatPayCertPath(apiclientCertFile)
));
if (!apiclientCertExists) healthy = false;
// 检查微信支付平台证书
String wechatpayCertFile = wechatConfig.getDev().getWechatpayCertFile();
boolean wechatpayCertExists = certificateService.certificateExists("wechat", wechatpayCertFile);
certificates.put("wechatpayCert", Map.of(
"file", wechatpayCertFile,
"exists", wechatpayCertExists,
"path", certificateService.getWechatPayCertPath(wechatpayCertFile)
));
if (!wechatpayCertExists) healthy = false;
health.put("healthy", healthy);
health.put("certificates", certificates);
return health;
}
/**
* 检查支付宝证书健康状态
*/
private Map<String, Object> checkAlipayCertificates() {
Map<String, Object> health = new HashMap<>();
boolean healthy = true;
Map<String, Object> certificates = new HashMap<>();
CertificateProperties.AlipayConfig alipayConfig = certificateProperties.getAlipay();
// 检查应用私钥
String appPrivateKeyFile = alipayConfig.getAppPrivateKeyFile();
boolean appPrivateKeyExists = certificateService.certificateExists("alipay", appPrivateKeyFile);
certificates.put("appPrivateKey", Map.of(
"file", appPrivateKeyFile,
"exists", appPrivateKeyExists,
"path", certificateService.getAlipayCertPath(appPrivateKeyFile)
));
if (!appPrivateKeyExists) healthy = false;
// 检查应用公钥证书
String appCertPublicKeyFile = alipayConfig.getAppCertPublicKeyFile();
boolean appCertExists = certificateService.certificateExists("alipay", appCertPublicKeyFile);
certificates.put("appCertPublicKey", Map.of(
"file", appCertPublicKeyFile,
"exists", appCertExists,
"path", certificateService.getAlipayCertPath(appCertPublicKeyFile)
));
if (!appCertExists) healthy = false;
// 检查支付宝公钥证书
String alipayCertPublicKeyFile = alipayConfig.getAlipayCertPublicKeyFile();
boolean alipayCertExists = certificateService.certificateExists("alipay", alipayCertPublicKeyFile);
certificates.put("alipayCertPublicKey", Map.of(
"file", alipayCertPublicKeyFile,
"exists", alipayCertExists,
"path", certificateService.getAlipayCertPath(alipayCertPublicKeyFile)
));
if (!alipayCertExists) healthy = false;
// 检查支付宝根证书
String alipayRootCertFile = alipayConfig.getAlipayRootCertFile();
boolean rootCertExists = certificateService.certificateExists("alipay", alipayRootCertFile);
certificates.put("alipayRootCert", Map.of(
"file", alipayRootCertFile,
"exists", rootCertExists,
"path", certificateService.getAlipayCertPath(alipayRootCertFile)
));
if (!rootCertExists) healthy = false;
health.put("healthy", healthy);
health.put("certificates", certificates);
return health;
}
/**
* 获取详细的证书诊断信息
*/
public Map<String, Object> getDiagnosticInfo() {
Map<String, Object> diagnostic = new HashMap<>();
try {
// 基本系统信息
diagnostic.put("loadMode", certificateProperties.getLoadMode());
diagnostic.put("certRootPath", certificateProperties.getCertRootPath());
diagnostic.put("devCertPath", certificateProperties.getDevCertPath());
// 获取所有证书状态
diagnostic.put("certificateStatus", certificateService.getAllCertificateStatus());
// 健康检查结果
HealthResult health = health();
diagnostic.put("healthStatus", health.getStatus());
diagnostic.put("healthDetails", health.getDetails());
} catch (Exception e) {
log.error("获取证书诊断信息失败", e);
diagnostic.put("error", e.getMessage());
}
return diagnostic;
}
/**
* 检查特定证书的详细信息
*/
public Map<String, Object> checkSpecificCertificate(String certType, String fileName) {
Map<String, Object> result = new HashMap<>();
try {
boolean exists = certificateService.certificateExists(certType, fileName);
String path = certificateService.getCertificateFilePath(certType, fileName);
result.put("certType", certType);
result.put("fileName", fileName);
result.put("exists", exists);
result.put("path", path);
if (exists && (fileName.endsWith(".crt") || fileName.endsWith(".pem"))) {
// 尝试验证证书
CertificateService.CertificateInfo certInfo =
certificateService.validateX509Certificate(certType, fileName);
result.put("certificateInfo", certInfo);
}
} catch (Exception e) {
log.error("检查证书失败: {}/{}", certType, fileName, e);
result.put("error", e.getMessage());
}
return result;
}
}

View File

@@ -0,0 +1,281 @@
package com.gxwebsoft.common.core.service;
import com.gxwebsoft.common.core.config.CertificateProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 证书管理服务
* 负责处理不同环境下的证书加载、验证和管理
*
* @author 科技小王子
* @since 2024-07-26
*/
@Slf4j
@Service
public class CertificateService {
private final CertificateProperties certificateProperties;
public CertificateService(CertificateProperties certificateProperties) {
this.certificateProperties = certificateProperties;
}
@PostConstruct
public void init() {
log.info("证书服务初始化,当前加载模式: {}", certificateProperties.getLoadMode());
log.info("证书根路径: {}", certificateProperties.getCertRootPath());
// 检查证书目录和文件
checkCertificateDirectories();
}
/**
* 获取证书文件的输入流
*
* @param certType 证书类型wechat/alipay
* @param fileName 文件名
* @return 输入流
* @throws IOException 文件读取异常
*/
public InputStream getCertificateInputStream(String certType, String fileName) throws IOException {
String certPath = certificateProperties.getCertificatePath(certType, fileName);
if (certificateProperties.isClasspathMode()) {
// 从classpath加载
Resource resource = new ClassPathResource(certPath);
if (!resource.exists()) {
throw new IOException("证书文件不存在: " + certPath);
}
log.debug("从classpath加载证书: {}", certPath);
return resource.getInputStream();
} else {
// 从文件系统加载
File file = new File(certPath);
if (!file.exists()) {
throw new IOException("证书文件不存在: " + certPath);
}
log.debug("从文件系统加载证书: {}", certPath);
return Files.newInputStream(file.toPath());
}
}
/**
* 获取证书文件路径
*
* @param certType 证书类型
* @param fileName 文件名
* @return 文件路径
*/
public String getCertificateFilePath(String certType, String fileName) {
return certificateProperties.getCertificatePath(certType, fileName);
}
/**
* 检查证书文件是否存在
*
* @param certType 证书类型
* @param fileName 文件名
* @return 是否存在
*/
public boolean certificateExists(String certType, String fileName) {
try {
String certPath = certificateProperties.getCertificatePath(certType, fileName);
if (certificateProperties.isClasspathMode()) {
Resource resource = new ClassPathResource(certPath);
return resource.exists();
} else {
File file = new File(certPath);
return file.exists() && file.isFile();
}
} catch (Exception e) {
log.error("检查证书文件存在性时出错: {}", e.getMessage());
return false;
}
}
/**
* 获取微信支付证书路径
*
* @param fileName 文件名
* @return 证书路径
*/
public String getWechatPayCertPath(String fileName) {
return certificateProperties.getWechatPayCertPath(fileName);
}
/**
* 获取支付宝证书路径
*
* @param fileName 文件名
* @return 证书路径
*/
public String getAlipayCertPath(String fileName) {
return certificateProperties.getAlipayCertPath(fileName);
}
/**
* 验证X509证书
*
* @param certType 证书类型
* @param fileName 文件名
* @return 证书信息
*/
public CertificateInfo validateX509Certificate(String certType, String fileName) {
try (InputStream inputStream = getCertificateInputStream(certType, fileName)) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
CertificateInfo info = new CertificateInfo();
info.setSubject(cert.getSubjectX500Principal().toString());
info.setIssuer(cert.getIssuerX500Principal().toString());
info.setNotBefore(convertToLocalDateTime(cert.getNotBefore()));
info.setNotAfter(convertToLocalDateTime(cert.getNotAfter()));
info.setSerialNumber(cert.getSerialNumber().toString());
info.setValid(isValidDate(cert.getNotBefore(), cert.getNotAfter()));
return info;
} catch (Exception e) {
log.error("验证证书失败: {}/{}, 错误: {}", certType, fileName, e.getMessage());
return null;
}
}
/**
* 检查证书目录结构
*/
private void checkCertificateDirectories() {
String[] certTypes = {"wechat", "alipay"};
for (String certType : certTypes) {
if (!certificateProperties.isClasspathMode()) {
// 检查文件系统目录
String dirPath = certificateProperties.getCertificatePath(certType, "");
File dir = new File(dirPath);
if (!dir.exists()) {
log.warn("证书目录不存在: {}", dirPath);
} else {
log.info("证书目录存在: {}", dirPath);
}
}
}
}
/**
* 获取所有证书状态
*
* @return 证书状态映射
*/
public Map<String, Object> getAllCertificateStatus() {
Map<String, Object> status = new HashMap<>();
// 微信支付证书状态
Map<String, Object> wechatStatus = new HashMap<>();
CertificateProperties.WechatPayConfig wechatConfig = certificateProperties.getWechatPay();
wechatStatus.put("privateKey", getCertStatus("wechat", wechatConfig.getDev().getPrivateKeyFile()));
wechatStatus.put("apiclientCert", getCertStatus("wechat", wechatConfig.getDev().getApiclientCertFile()));
wechatStatus.put("wechatpayCert", getCertStatus("wechat", wechatConfig.getDev().getWechatpayCertFile()));
status.put("wechat", wechatStatus);
// 支付宝证书状态
Map<String, Object> alipayStatus = new HashMap<>();
CertificateProperties.AlipayConfig alipayConfig = certificateProperties.getAlipay();
alipayStatus.put("appPrivateKey", getCertStatus("alipay", alipayConfig.getAppPrivateKeyFile()));
alipayStatus.put("appCertPublicKey", getCertStatus("alipay", alipayConfig.getAppCertPublicKeyFile()));
alipayStatus.put("alipayCertPublicKey", getCertStatus("alipay", alipayConfig.getAlipayCertPublicKeyFile()));
alipayStatus.put("alipayRootCert", getCertStatus("alipay", alipayConfig.getAlipayRootCertFile()));
status.put("alipay", alipayStatus);
// 系统信息
Map<String, Object> systemInfo = new HashMap<>();
systemInfo.put("loadMode", certificateProperties.getLoadMode());
systemInfo.put("certRootPath", certificateProperties.getCertRootPath());
systemInfo.put("devCertPath", certificateProperties.getDevCertPath());
status.put("system", systemInfo);
return status;
}
/**
* 获取单个证书状态
*/
private Map<String, Object> getCertStatus(String certType, String fileName) {
Map<String, Object> status = new HashMap<>();
status.put("fileName", fileName);
status.put("exists", certificateExists(certType, fileName));
status.put("path", getCertificateFilePath(certType, fileName));
// 如果是.crt或.pem文件尝试验证证书
if (fileName.endsWith(".crt") || fileName.endsWith(".pem")) {
CertificateInfo certInfo = validateX509Certificate(certType, fileName);
status.put("certificateInfo", certInfo);
}
return status;
}
/**
* 检查日期是否有效
*/
private boolean isValidDate(Date notBefore, Date notAfter) {
Date now = new Date();
return now.after(notBefore) && now.before(notAfter);
}
/**
* 将Date转换为LocalDateTime
*/
private LocalDateTime convertToLocalDateTime(Date date) {
if (date == null) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* 证书信息类
*/
public static class CertificateInfo {
private String subject;
private String issuer;
private LocalDateTime notBefore;
private LocalDateTime notAfter;
private String serialNumber;
private boolean valid;
// Getters and Setters
public String getSubject() { return subject; }
public void setSubject(String subject) { this.subject = subject; }
public String getIssuer() { return issuer; }
public void setIssuer(String issuer) { this.issuer = issuer; }
public LocalDateTime getNotBefore() { return notBefore; }
public void setNotBefore(LocalDateTime notBefore) { this.notBefore = notBefore; }
public LocalDateTime getNotAfter() { return notAfter; }
public void setNotAfter(LocalDateTime notAfter) { this.notAfter = notAfter; }
public String getSerialNumber() { return serialNumber; }
public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; }
public boolean isValid() { return valid; }
public void setValid(boolean valid) { this.valid = valid; }
}
}

View File

@@ -0,0 +1,143 @@
package com.gxwebsoft.common.core.service;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* 环境感知的支付配置服务
* 根据不同环境自动切换支付回调地址
*
* @author WebSoft
* @since 2025-01-15
*/
@Slf4j
@Service
public class EnvironmentAwarePaymentService {
@Autowired
private PaymentCacheService paymentCacheService;
@Value("${spring.profiles.active:dev}")
private String activeProfile;
@Value("${config.server-url:}")
private String serverUrl;
// 开发环境回调地址配置
@Value("${payment.dev.notify-url:http://frps-10550.s209.websoft.top/api/shop/shop-order/notify}")
private String devNotifyUrl;
// 生产环境回调地址配置
@Value("${payment.prod.notify-url:https://cms-api.websoft.top/api/shop/shop-order/notify}")
private String prodNotifyUrl;
/**
* 获取环境感知的支付配置
* 根据当前环境自动调整回调地址
*
* @param payType 支付类型
* @param tenantId 租户ID
* @return 支付配置
*/
public Payment getEnvironmentAwarePaymentConfig(Integer payType, Integer tenantId) {
// 获取原始支付配置
Payment payment = paymentCacheService.getPaymentConfig(payType, tenantId);
if (payment == null) {
return null;
}
// 根据环境调整回调地址
Payment envPayment = clonePayment(payment);
String notifyUrl = getEnvironmentNotifyUrl();
log.info("环境感知支付配置 - 环境: {}, 原始回调: {}, 调整后回调: {}",
activeProfile, payment.getNotifyUrl(), notifyUrl);
envPayment.setNotifyUrl(notifyUrl);
return envPayment;
}
/**
* 根据当前环境获取回调地址
*/
private String getEnvironmentNotifyUrl() {
if ("dev".equals(activeProfile) || "test".equals(activeProfile)) {
// 开发/测试环境使用本地回调地址
return devNotifyUrl;
} else if ("prod".equals(activeProfile)) {
// 生产环境使用生产回调地址
return prodNotifyUrl;
} else {
// 默认使用配置的服务器地址
return serverUrl + "/shop/shop-order/notify";
}
}
/**
* 克隆支付配置对象
*/
private Payment clonePayment(Payment original) {
Payment cloned = new Payment();
cloned.setId(original.getId());
cloned.setName(original.getName());
cloned.setType(original.getType());
cloned.setCode(original.getCode());
cloned.setImage(original.getImage());
cloned.setWechatType(original.getWechatType());
cloned.setAppId(original.getAppId());
cloned.setMchId(original.getMchId());
cloned.setApiKey(original.getApiKey());
cloned.setApiclientCert(original.getApiclientCert());
cloned.setApiclientKey(original.getApiclientKey());
cloned.setPubKey(original.getPubKey());
cloned.setPubKeyId(original.getPubKeyId());
cloned.setMerchantSerialNumber(original.getMerchantSerialNumber());
cloned.setNotifyUrl(original.getNotifyUrl()); // 这个会被后续覆盖
cloned.setComments(original.getComments());
cloned.setSortNumber(original.getSortNumber());
cloned.setStatus(original.getStatus());
cloned.setDeleted(original.getDeleted());
cloned.setTenantId(original.getTenantId());
return cloned;
}
/**
* 获取微信支付配置(环境感知)
*/
public Payment getWechatPayConfig(Integer tenantId) {
return getEnvironmentAwarePaymentConfig(0, tenantId);
}
/**
* 获取支付宝配置(环境感知)
*/
public Payment getAlipayConfig(Integer tenantId) {
return getEnvironmentAwarePaymentConfig(1, tenantId);
}
/**
* 检查当前环境
*/
public String getCurrentEnvironment() {
return activeProfile;
}
/**
* 是否为开发环境
*/
public boolean isDevelopmentEnvironment() {
return "dev".equals(activeProfile) || "test".equals(activeProfile);
}
/**
* 是否为生产环境
*/
public boolean isProductionEnvironment() {
return "prod".equals(activeProfile);
}
}

View File

@@ -0,0 +1,174 @@
package com.gxwebsoft.common.core.service;
import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.system.entity.Payment;
import com.gxwebsoft.common.system.param.PaymentParam;
import com.gxwebsoft.common.system.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 支付配置缓存服务
* 统一管理支付配置的缓存读取,支持 Payment:1* 格式
*
* @author 科技小王子
* @since 2025-07-27
*/
@Slf4j
@Service
public class PaymentCacheService {
@Autowired
private RedisUtil redisUtil;
@Autowired
private PaymentService paymentService;
/**
* 根据支付类型获取支付配置
* 优先从 Payment:1{payType} 格式的缓存读取
*
* @param payType 支付类型 (0=微信支付, 1=支付宝, 2=其他)
* @param tenantId 租户ID (用于兜底查询)
* @return Payment 支付配置
*/
public Payment getPaymentConfig(Integer payType, Integer tenantId) {
// 1. 优先使用 Payment:1{payType} 格式的缓存键
String primaryKey = "Payment:1:" + tenantId;
Payment payment = redisUtil.get(primaryKey, Payment.class);
if (ObjectUtil.isNotEmpty(payment)) {
log.debug("从缓存获取支付配置成功: {}", primaryKey);
return payment;
}
// 2. 如果 Payment:1* 格式不存在,尝试原有格式
String fallbackKey = "Payment:" + payType + ":" + tenantId;
payment = redisUtil.get(fallbackKey, Payment.class);
if (ObjectUtil.isNotEmpty(payment)) {
log.debug("从兜底缓存获取支付配置成功: {}", fallbackKey);
// 将查询结果缓存到 Payment:1* 格式
redisUtil.set(primaryKey, payment);
return payment;
}
// 3. 最后从数据库查询
log.debug("从数据库查询支付配置, payType: {}, tenantId: {}", payType, tenantId);
PaymentParam paymentParam = new PaymentParam();
paymentParam.setType(payType);
paymentParam.setTenantId(tenantId); // 设置租户ID进行过滤
List<Payment> payments = paymentService.listRel(paymentParam);
if (payments.isEmpty()) {
throw new BusinessException("请完成支付配置,支付类型: " + payType);
}
Payment dbPayment = payments.get(0);
// 清理时间字段,避免序列化问题
Payment cachePayment = cleanPaymentForCache(dbPayment);
// 将查询结果缓存到 Payment:1* 格式
redisUtil.set(primaryKey, cachePayment);
log.debug("支付配置已缓存到: {}", primaryKey);
return dbPayment; // 返回原始对象,不影响业务逻辑
}
/**
* 缓存支付配置
* 同时缓存到 Payment:1{payType} 和原有格式
*
* @param payment 支付配置
* @param tenantId 租户ID
*/
public void cachePaymentConfig(Payment payment, Integer tenantId) {
// 缓存到 Payment:1* 格式
String primaryKey = "Payment:1" + payment.getCode();
redisUtil.set(primaryKey, payment);
log.debug("支付配置已缓存到: {}", primaryKey);
// 兼容原有格式
String legacyKey = "Payment:" + payment.getCode() + ":" + tenantId;
redisUtil.set(legacyKey, payment);
log.debug("支付配置已缓存到兼容格式: {}", legacyKey);
}
/**
* 删除支付配置缓存
* 同时删除 Payment:1{payType} 和原有格式
*
* @param paymentCode 支付代码 (可以是String或Integer)
* @param tenantId 租户ID
*/
public void removePaymentConfig(String paymentCode, Integer tenantId) {
// 删除 Payment:1* 格式缓存
String primaryKey = "Payment:1" + paymentCode;
redisUtil.delete(primaryKey);
log.debug("已删除支付配置缓存: {}", primaryKey);
// 删除原有格式缓存
String legacyKey = "Payment:" + paymentCode + ":" + tenantId;
redisUtil.delete(legacyKey);
log.debug("已删除兼容格式缓存: {}", legacyKey);
}
/**
* 获取微信支付配置 (payType = 0)
*/
public Payment getWechatPayConfig(Integer tenantId) {
return getPaymentConfig(0, tenantId);
}
/**
* 获取支付宝配置 (payType = 1)
*/
public Payment getAlipayConfig(Integer tenantId) {
return getPaymentConfig(1, tenantId);
}
/**
* 清理Payment对象用于缓存
* 移除可能导致序列化问题的时间字段
*/
private Payment cleanPaymentForCache(Payment original) {
if (original == null) {
return null;
}
Payment cleaned = new Payment();
// 复制所有业务相关字段
cleaned.setId(original.getId());
cleaned.setName(original.getName());
cleaned.setType(original.getType());
cleaned.setCode(original.getCode());
cleaned.setImage(original.getImage());
cleaned.setWechatType(original.getWechatType());
cleaned.setAppId(original.getAppId());
cleaned.setMchId(original.getMchId());
cleaned.setApiKey(original.getApiKey());
cleaned.setApiclientCert(original.getApiclientCert());
cleaned.setApiclientKey(original.getApiclientKey());
cleaned.setPubKey(original.getPubKey());
cleaned.setPubKeyId(original.getPubKeyId());
cleaned.setMerchantSerialNumber(original.getMerchantSerialNumber());
cleaned.setNotifyUrl(original.getNotifyUrl());
cleaned.setComments(original.getComments());
cleaned.setSortNumber(original.getSortNumber());
cleaned.setStatus(original.getStatus());
cleaned.setDeleted(original.getDeleted());
cleaned.setTenantId(original.getTenantId());
// 不设置时间字段,避免序列化问题
// cleaned.setCreateTime(null);
// cleaned.setUpdateTime(null);
return cleaned;
}
}

View File

@@ -0,0 +1,145 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.codec.Base64;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
@Component
public class AliYunSender {
/*
* 计算MD5+BASE64
*/
public static String MD5Base64(String s) {
if (s == null)
return null;
String encodeStr = "";
byte[] utfBytes = s.getBytes();
MessageDigest mdTemp;
try {
mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(utfBytes);
byte[] md5Bytes = mdTemp.digest();
encodeStr = Base64.encode(md5Bytes);
} catch (Exception e) {
throw new Error("Failed to generate MD5 : " + e.getMessage());
}
return encodeStr;
}
/*
* 计算 HMAC-SHA1
*/
public static String HMACSha1(String data, String key) {
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = Base64.encode(rawHmac);
} catch (Exception e) {
throw new Error("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/*
* 获取时间
*/
public static String toGMTString(Date date) {
SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
return df.format(date);
}
/*
* 发送POST请求
*/
public static String sendPost(String url, String body, String ak_id, String ak_secret) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
/*
* http header 参数
*/
String method = "POST";
String accept = "application/json";
String content_type = "application/json;chrset=utf-8";
String path = realUrl.getFile();
String date = toGMTString(new Date());
String host = realUrl.getHost();
// 1.对body做MD5+BASE64加密
String bodyMd5 = MD5Base64(body);
String uuid = UUID.randomUUID().toString();
String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
+ "x-acs-signature-method:HMAC-SHA1\n"
+ "x-acs-signature-nonce:" + uuid + "\n"
+ "x-acs-version:2019-01-02\n"
+ path;
// 2.计算 HMAC-SHA1
String signature = HMACSha1(stringToSign, ak_secret);
// 3.得到 authorization header
String authHeader = "acs " + ak_id + ":" + signature;
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Accept", accept);
conn.setRequestProperty("Content-Type", content_type);
conn.setRequestProperty("Content-MD5", bodyMd5);
conn.setRequestProperty("Date", date);
conn.setRequestProperty("Host", host);
conn.setRequestProperty("Authorization", authHeader);
conn.setRequestProperty("x-acs-signature-nonce", uuid);
conn.setRequestProperty("x-acs-signature-method", "HMAC-SHA1");
conn.setRequestProperty("x-acs-version", "2019-01-02"); // 版本可选
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(body);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
InputStream is;
HttpURLConnection httpconn = (HttpURLConnection) conn;
if (httpconn.getResponseCode() == 200) {
is = httpconn.getInputStream();
} else {
is = httpconn.getErrorStream();
}
in = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}

View File

@@ -0,0 +1,110 @@
package com.gxwebsoft.common.core.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 支付宝工具类
* @author leng
*
*/
@Component
public class AlipayConfigUtil {
private final StringRedisTemplate stringRedisTemplate;
public Integer tenantId;
public String gateway;
public JSONObject config;
public String appId;
public String privateKey;
public String appCertPublicKey;
public String alipayCertPublicKey;
public String alipayRootCert;
@Resource
private ConfigProperties pathConfig;
public AlipayConfigUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
// 实例化客户端
public DefaultAlipayClient alipayClient(Integer tenantId) throws AlipayApiException {
this.gateway = "https://openapi.alipay.com/gateway.do";
this.tenantId = tenantId;
this.payment(tenantId);
CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
certAlipayRequest.setServerUrl(this.gateway);
certAlipayRequest.setAppId(this.appId);
certAlipayRequest.setPrivateKey(this.privateKey);
certAlipayRequest.setFormat(AlipayConstants.FORMAT_JSON);
certAlipayRequest.setCharset(AlipayConstants.CHARSET_UTF8);
certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
certAlipayRequest.setCertPath(this.appCertPublicKey);
certAlipayRequest.setAlipayPublicCertPath(this.alipayCertPublicKey);
certAlipayRequest.setRootCertPath(this.alipayRootCert);
// System.out.println("this.appId = " + this.appId);
// System.out.println("this.appId = " + this.gateway);
// System.out.println("this.appId = " + this.privateKey);
// System.out.println("this.appId = " + this.appCertPublicKey);
// System.out.println("this.appId = " + this.alipayCertPublicKey);
// System.out.println("this.appId = " + this.alipayRootCert);
// System.out.println("this.config = " + this.config);
return new DefaultAlipayClient(certAlipayRequest);
}
/**
* 获取支付宝秘钥
*/
public JSONObject payment(Integer tenantId) {
System.out.println("tenantId = " + tenantId);
String key = "cache".concat(tenantId.toString()).concat(":setting:payment");
System.out.println("key = " + key);
String cache = stringRedisTemplate.opsForValue().get(key);
if (cache == null) {
throw new BusinessException("支付方式未配置");
}
// 解析json数据
JSONObject payment = JSON.parseObject(cache.getBytes());
this.config = payment;
this.appId = payment.getString("alipayAppId");
this.privateKey = payment.getString("privateKey");
this.appCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("appCertPublicKey");
this.alipayCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("alipayCertPublicKey");
this.alipayRootCert = pathConfig.getUploadPath() + "file" + payment.getString("alipayRootCert");
return payment;
}
public String appId(){
return this.appId;
}
public String privateKey(){
return this.privateKey;
}
public String appCertPublicKey(){
return this.appCertPublicKey;
}
public String alipayCertPublicKey(){
return this.alipayCertPublicKey;
}
public String alipayRootCert(){
return this.alipayRootCert;
}
}

View File

@@ -0,0 +1,265 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.result.RedisResult;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
@Component
public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
public static Integer tenantId;
public CacheClient(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
/**
* 写入redis缓存
* @param key [表名]:id
* @param entity 实体类对象
* 示例 cacheClient.set("merchant:"+id,merchant)
*/
public <T> void set(String key, T entity){
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity));
}
/**
* 写入redis缓存
* @param key [表名]:id
* @param entity 实体类对象
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
*/
public <T> void set(String key, T entity, Long time, TimeUnit unit){
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity),time,unit);
}
/**
* 读取redis缓存
* @param key [表名]:id
* 示例 cacheClient.get(key)
* @return merchant
*/
public String get(String key) {
return stringRedisTemplate.opsForValue().get(prefix(key));
}
/**
* 读取redis缓存
* @param key [表名]:id
* @param clazz Merchant.class
* @param <T>
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
* @return merchant
*/
public <T> T get(String key, Class<T> clazz) {
String json = stringRedisTemplate.opsForValue().get(prefix(key));
if(StrUtil.isNotBlank(json)){
return JSONUtil.parseObject(json, clazz);
}
return null;
}
/**
* 写redis缓存(哈希类型)
* @param key [表名]:id
* @param field 字段
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
*/
public <T> void hPut(String key, String field, T entity) {
stringRedisTemplate.opsForHash().put(prefix(key),field,JSONUtil.toJSONString(entity));
}
/**
* 写redis缓存(哈希类型)
* @param key [表名]:id
* @param map 字段
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
*/
public void hPutAll(String key, Map<String,String> map) {
stringRedisTemplate.opsForHash().putAll(prefix(key),map);
}
/**
* 读取redis缓存(哈希类型)
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
* @param key [表名]:id
* @param field 字段
* @return merchant
*/
public <T> T hGet(String key, String field, Class<T> clazz) {
Object obj = stringRedisTemplate.opsForHash().get(prefix(key), field);
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
}
public List<Object> hValues(String key){
return stringRedisTemplate.opsForHash().values(prefix(key));
}
public Long hSize(String key){
return stringRedisTemplate.opsForHash().size(prefix(key));
}
// 逻辑过期方式写入redis
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
// 设置逻辑过期时间
final RedisResult<T> redisResult = new RedisResult<>();
redisResult.setData(value);
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
stringRedisTemplate.opsForValue().set(prefix(key),JSONUtil.toJSONString(redisResult));
}
// 读取redis
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
String key = keyPrefix + id;
// 1.从redis查询缓存
final String json = stringRedisTemplate.opsForValue().get(prefix(key));
// 2.判断是否存在
if (StrUtil.isNotBlank(json)) {
// 3.存在,直接返回
return JSONUtil.parseObject(json,clazz);
}
// 判断命中的是否为空值
if (json != null) {
return null;
}
// 4. 不存在跟进ID查询数据库
R r = dbFallback.apply(id);
// 5. 数据库不存在,返回错误
if(r == null){
// 空值写入数据库
this.set(prefix(key),"",CACHE_NULL_TTL,TimeUnit.MINUTES);
return null;
}
// 写入redis
this.set(prefix(key),r,time,unit);
return r;
}
/**
* 添加商户定位点
* @param key geo
* @param id
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
*/
public <T> void geoAdd(String key, Double x, Double y, String id){
stringRedisTemplate.opsForGeo().add(prefix(key),new Point(x,y),id);
}
/**
* 删除定位
* @param key geo
* @param id
* 示例 cacheClient.geoRemove("merchant-geo",id)
*/
public void geoRemove(String key, Integer id){
stringRedisTemplate.opsForGeo().remove(prefix(key),id.toString());
}
public <T> void sAdd(String key, T entity){
stringRedisTemplate.opsForSet().add(prefix(key),JSONUtil.toJSONString(entity));
}
public <T> Set<String> sMembers(String key){
return stringRedisTemplate.opsForSet().members(prefix(key));
}
// 更新排行榜
public void zAdd(String key, Integer userId, Double value) {
stringRedisTemplate.opsForZSet().add(prefix(key),userId.toString(),value);
}
// 增加元素的score值并返回增加后的值
public Double zIncrementScore(String key,Integer userId, Double delta){
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
}
// 获取排名榜
public Set<String> range(String key, Integer start, Integer end) {
return stringRedisTemplate.opsForZSet().range(prefix(key), start, end);
}
// 获取排名榜
public Set<String> reverseRange(String key, Integer start, Integer end){
return stringRedisTemplate.opsForZSet().reverseRange(prefix(key), start, end);
}
// 获取分数
public Double score(String key, Object value){
return stringRedisTemplate.opsForZSet().score(prefix(key), value);
}
public void delete(String key){
stringRedisTemplate.delete(prefix(key));
}
// 存储在list头部
public void leftPush(String key, String keyword){
stringRedisTemplate.opsForList().leftPush(prefix(key),keyword);
}
// 获取列表指定范围内的元素
public List<String> listRange(String key,Long start, Long end){
return stringRedisTemplate.opsForList().range(prefix(key), start, end);
}
// 获取列表长度
public Long listSize(String key){
return stringRedisTemplate.opsForList().size(prefix(key));
}
// 裁剪list
public void listTrim(String key){
stringRedisTemplate.opsForList().trim(prefix(key), 0L, 100L);
}
/**
* 读取后台系统设置信息
* @param keyName 键名wx-word
* @param tenantId 租户ID
* @return
* key示例 cache10048:setting:wx-work
*/
public JSONObject getSettingInfo(String keyName,Integer tenantId){
String key = "cache" + tenantId + ":setting:" + keyName;
final String cache = stringRedisTemplate.opsForValue().get(key);
assert cache != null;
return JSON.parseObject(cache);
}
/**
* KEY前缀
* cache[tenantId]:[key+id]
*/
public static String prefix(String key){
String prefix = "cache";
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
final Integer tenantId = ((User) object).getTenantId();
prefix = prefix.concat(tenantId.toString()).concat(":");
}
}
return prefix.concat(key);
}
// 组装key
public String key(String name,Integer id){
return name.concat(":").concat(id.toString());
}
}

View File

@@ -0,0 +1,230 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.core.config.CertificateProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 证书加载工具类
* 支持多种证书加载方式适配Docker容器化部署
*
* @author 科技小王子
* @since 2025-01-26
*/
@Slf4j
@Component
public class CertificateLoader {
private final CertificateProperties certConfig;
public CertificateLoader(CertificateProperties certConfig) {
this.certConfig = certConfig;
}
@PostConstruct
public void init() {
log.info("证书加载器初始化,加载模式:{}", certConfig.getLoadMode());
if (certConfig.getLoadMode() == CertificateProperties.LoadMode.VOLUME) {
log.info("Docker挂载卷证书路径{}", certConfig.getCertRootPath());
validateCertDirectory();
}
}
/**
* 验证证书目录是否存在
*/
private void validateCertDirectory() {
File certDir = new File(certConfig.getCertRootPath());
if (!certDir.exists()) {
log.warn("证书目录不存在:{},将尝试创建", certConfig.getCertRootPath());
if (!certDir.mkdirs()) {
log.error("无法创建证书目录:{}", certConfig.getCertRootPath());
}
} else {
log.info("证书目录验证成功:{}", certConfig.getCertRootPath());
}
}
/**
* 加载证书文件路径
*
* @param certPath 证书路径可能是相对路径、绝对路径或classpath路径
* @return 实际的证书文件路径
*/
public String loadCertificatePath(String certPath) {
if (!StringUtils.hasText(certPath)) {
throw new IllegalArgumentException("证书路径不能为空");
}
try {
switch (certConfig.getLoadMode()) {
case CLASSPATH:
return loadFromClasspath(certPath);
case VOLUME:
return loadFromVolume(certPath);
case FILESYSTEM:
default:
return loadFromFileSystem(certPath);
}
} catch (Exception e) {
log.error("加载证书失败,路径:{}", certPath, e);
throw new RuntimeException("证书加载失败:" + certPath, e);
}
}
/**
* 从classpath加载证书
*/
private String loadFromClasspath(String certPath) throws IOException {
String resourcePath = certPath.startsWith("classpath:") ?
certPath.substring("classpath:".length()) : certPath;
ClassPathResource resource = new ClassPathResource(resourcePath);
if (!resource.exists()) {
throw new IOException("Classpath中找不到证书文件" + resourcePath);
}
// 将classpath中的文件复制到临时目录
Path tempFile = Files.createTempFile("cert_", ".pem");
try (InputStream inputStream = resource.getInputStream()) {
Files.copy(inputStream, tempFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
String tempPath = tempFile.toAbsolutePath().toString();
log.debug("从classpath加载证书{} -> {}", resourcePath, tempPath);
return tempPath;
}
/**
* 从Docker挂载卷加载证书
*/
private String loadFromVolume(String certPath) {
log.debug("尝试从Docker挂载卷加载证书{}", certPath);
// 如果是完整路径,直接使用
if (certPath.startsWith("/") || certPath.contains(":")) {
File file = new File(certPath);
log.debug("检查完整路径文件是否存在:{}", certPath);
if (file.exists()) {
log.debug("使用完整路径加载证书:{}", certPath);
return certPath;
} else {
log.error("完整路径文件不存在:{}", certPath);
}
}
// 否则拼接挂载卷路径
String fullPath = Paths.get(certConfig.getCertRootPath(), certPath).toString();
File file = new File(fullPath);
if (!file.exists()) {
throw new RuntimeException("Docker挂载卷中找不到证书文件" + fullPath);
}
log.debug("从Docker挂载卷加载证书{}", fullPath);
return fullPath;
}
/**
* 从文件系统加载证书
*/
private String loadFromFileSystem(String certPath) {
File file = new File(certPath);
if (!file.exists()) {
throw new RuntimeException("文件系统中找不到证书文件:" + certPath);
}
log.debug("从文件系统加载证书:{}", certPath);
return certPath;
}
/**
* 检查证书文件是否存在
*
* @param certPath 证书路径
* @return 是否存在
*/
public boolean certificateExists(String certPath) {
try {
switch (certConfig.getLoadMode()) {
case CLASSPATH:
String resourcePath = certPath.startsWith("classpath:") ?
certPath.substring("classpath:".length()) : certPath;
ClassPathResource resource = new ClassPathResource(resourcePath);
return resource.exists();
case VOLUME:
String fullPath = certPath.startsWith("/") ? certPath :
Paths.get(certConfig.getCertRootPath(), certPath).toString();
return new File(fullPath).exists();
case FILESYSTEM:
default:
return new File(certPath).exists();
}
} catch (Exception e) {
log.warn("检查证书文件存在性时出错:{}", certPath, e);
return false;
}
}
/**
* 获取证书文件的输入流
*
* @param certPath 证书路径
* @return 输入流
*/
public InputStream getCertificateInputStream(String certPath) throws IOException {
switch (certConfig.getLoadMode()) {
case CLASSPATH:
String resourcePath = certPath.startsWith("classpath:") ?
certPath.substring("classpath:".length()) : certPath;
ClassPathResource resource = new ClassPathResource(resourcePath);
return resource.getInputStream();
case VOLUME:
case FILESYSTEM:
default:
String actualPath = loadCertificatePath(certPath);
return Files.newInputStream(Paths.get(actualPath));
}
}
/**
* 列出证书目录中的所有文件
*
* @return 证书文件列表
*/
public String[] listCertificateFiles() {
try {
switch (certConfig.getLoadMode()) {
case VOLUME:
File certDir = new File(certConfig.getCertRootPath());
if (certDir.exists() && certDir.isDirectory()) {
return certDir.list();
}
break;
case CLASSPATH:
// classpath模式下不支持列出文件
log.warn("Classpath模式下不支持列出证书文件");
break;
case FILESYSTEM:
default:
// 文件系统模式下证书可能分散在不同目录,不支持统一列出
log.warn("文件系统模式下不支持列出证书文件");
break;
}
} catch (Exception e) {
log.error("列出证书文件时出错", e);
}
return new String[0];
}
}

View File

@@ -0,0 +1,321 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.system.entity.Role;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* 常用工具方法
*
* @author WebSoft
* @since 2017-06-10 10:10:22
*/
public class CommonUtil {
// 生成uuid的字符
private static final String[] chars = new String[]{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
};
/**
* 生成8位uuid
*
* @return String
*/
public static String randomUUID8() {
StringBuilder sb = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
sb.append(chars[x % 0x3E]);
}
return sb.toString();
}
/**
* 生成16位uuid
*
* @return String
*/
public static String randomUUID16() {
StringBuilder sb = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 16; i++) {
String str = uuid.substring(i * 2, i * 2 + 2);
int x = Integer.parseInt(str, 16);
sb.append(chars[x % 0x3E]);
}
return sb.toString();
}
/**
* 获取当前时间
*
* @return String
*/
public static String currentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
return sdf.format(date);
}
/**
* 生成10位随机用户名
*
* @return String
*/
public static String randomUsername(String prefix) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
String currentTime = sdf.format(date);
return prefix + currentTime;
}
/**
* 生成订单号
* 20233191166110426
* 20230419135802391412
* @return
*/
public static String createOrderNo() {
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
return prefix + RandomUtil.randomNumbers(2);
}
/**
* 生成订单号
* @param tenantId
* 20233191166110426
* 20230419135802391412
* @return
*/
public static String createOrderNo(String tenantId) {
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
return prefix + tenantId + RandomUtil.randomNumbers(2);
}
/**
* 生成订单水流号
* @param tenantId
* @return
*/
public static String serialNo(int tenantId) {
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
return prefix + tenantId + RandomUtil.randomNumbers(2);
}
/**
* 生成会员卡号
* @return
*/
public static String createCardNo() {
String prefix = DateTime.now().toString(DatePattern.PURE_TIME_PATTERN);
return "00" + prefix + RandomUtil.randomNumbers(2);
}
/**
* 检查List是否有重复元素
*
* @param list List
* @param mapper 获取需要检查的字段的Function
* @param <T> 数据的类型
* @param <R> 需要检查的字段的类型
* @return boolean
*/
public static <T, R> boolean checkRepeat(List<T> list, Function<? super T, ? extends R> mapper) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (i != j && mapper.apply(list.get(i)).equals(mapper.apply(list.get(j)))) {
return true;
}
}
}
return false;
}
/**
* List转为树形结构
*
* @param data List
* @param parentId 顶级的parentId
* @param parentIdMapper 获取parentId的Function
* @param idMapper 获取id的Function
* @param consumer 赋值children的Consumer
* @param <T> 数据的类型
* @param <R> parentId的类型
* @return List<T>
*/
public static <T, R> List<T> toTreeData(List<T> data, R parentId,
Function<? super T, ? extends R> parentIdMapper,
Function<? super T, ? extends R> idMapper,
BiConsumer<T, List<T>> consumer) {
List<T> result = new ArrayList<>();
for (T d : data) {
R dParentId = parentIdMapper.apply(d);
if (ObjectUtil.equals(parentId, dParentId)) {
R dId = idMapper.apply(d);
List<T> children = toTreeData(data, dId, parentIdMapper, idMapper, consumer);
consumer.accept(d, children);
result.add(d);
}
}
return result;
}
/**
* 遍历树形结构数据
*
* @param data List
* @param consumer 回调
* @param mapper 获取children的Function
* @param <T> 数据的类型
*/
public static <T> void eachTreeData(List<T> data, Consumer<T> consumer, Function<T, List<T>> mapper) {
for (T d : data) {
consumer.accept(d);
List<T> children = mapper.apply(d);
if (children != null && children.size() > 0) {
eachTreeData(children, consumer, mapper);
}
}
}
/**
* 获取集合中的第一条数据
*
* @param records 集合
* @return 第一条数据
*/
public static <T> T listGetOne(List<T> records) {
return records == null || records.size() == 0 ? null : records.get(0);
}
/**
* 支持跨域
*
* @param response HttpServletResponse
*/
public static void addCrossHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Expose-Headers", Constants.TOKEN_HEADER_NAME);
}
/**
* 输出错误信息
*
* @param response HttpServletResponse
* @param code 错误码
* @param message 提示信息
* @param error 错误信息
*/
public static void responseError(HttpServletResponse response, Integer code, String message, String error) {
response.setContentType("application/json;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.write(JSONUtil.toJSONString(new ApiResult<>(code, message, null, error)));
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean hasRole(List<Role> array,String value){
System.out.println("value = " + value);
if (value == null) {
return true;
}
if (array == null) {
return false;
}
if (!array.isEmpty()) {
final List<String> collect = array.stream().map(Role::getRoleCode)
.collect(Collectors.toList());
final boolean contains = collect.contains(value);
if (contains) {
return true;
}
}
return false;
}
public static boolean hasRole(List<Role> array,List<String> value){
System.out.println("value = " + value);
if (value == null) {
return true;
}
if (array == null) {
return false;
}
if (!array.isEmpty()) {
final List<String> collect = array.stream().map(Role::getRoleCode)
.collect(Collectors.toList());
final boolean disjoint = Collections.disjoint(collect, value);
if (!disjoint) {
return true;
}
}
return false;
}
public static AES aes(){
// 随机生成密钥
byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
return SecureUtil.aes(key);
}
// 机密文本
public static String encrypt(String text){
final AES aes = aes();
return aes.encryptHex(text);
}
// 解密
public static String decrypt(String encrypt){
final AES aes = aes();
return aes.decryptStr(encrypt, CharsetUtil.CHARSET_UTF_8);
}
/**
* 验证给定的字符串是否为有效的中国大陆手机号码。
*
* @param phoneNumber 要验证的电话号码字符串
* @return 如果字符串是有效的手机号码则返回true否则返回false
*/
public static boolean isValidPhoneNumber(String phoneNumber) {
// 定义手机号码的正则表达式
String regex = "^1[3-9]\\d{9}$";
// 创建Pattern对象
Pattern pattern = Pattern.compile(regex);
// 使用matcher方法创建Matcher对象并进行匹配
return pattern.matcher(phoneNumber).matches();
}
}

View File

@@ -0,0 +1,93 @@
package com.gxwebsoft.common.core.utils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 时间格式化工具类
* 用于统一处理LocalDateTime的格式化
*
* @author WebSoft
* @since 2025-08-23
*/
public class DateTimeUtil {
/**
* 默认的日期时间格式
*/
public static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 默认的日期格式
*/
public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
/**
* 默认的时间格式
*/
public static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";
/**
* 默认的日期时间格式化器
*/
private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER =
DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN);
/**
* 格式化LocalDateTime为字符串
* 使用默认格式yyyy-MM-dd HH:mm:ss
*
* @param dateTime 要格式化的时间
* @return 格式化后的字符串如果输入为null则返回null
*/
public static String formatDateTime(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return dateTime.format(DEFAULT_DATETIME_FORMATTER);
}
/**
* 格式化LocalDateTime为字符串
* 使用指定格式
*
* @param dateTime 要格式化的时间
* @param pattern 格式模式
* @return 格式化后的字符串如果输入为null则返回null
*/
public static String formatDateTime(LocalDateTime dateTime, String pattern) {
if (dateTime == null) {
return null;
}
return dateTime.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 解析字符串为LocalDateTime
* 使用默认格式yyyy-MM-dd HH:mm:ss
*
* @param dateTimeStr 时间字符串
* @return LocalDateTime对象如果输入为null或空字符串则返回null
*/
public static LocalDateTime parseDateTime(String dateTimeStr) {
if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
return null;
}
return LocalDateTime.parse(dateTimeStr, DEFAULT_DATETIME_FORMATTER);
}
/**
* 解析字符串为LocalDateTime
* 使用指定格式
*
* @param dateTimeStr 时间字符串
* @param pattern 格式模式
* @return LocalDateTime对象如果输入为null或空字符串则返回null
*/
public static LocalDateTime parseDateTime(String dateTimeStr, String pattern) {
if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
return null;
}
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
}
}

View File

@@ -0,0 +1,433 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.crypto.spec.SecretKeySpec;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 加密二维码工具类
* 使用token作为密钥对二维码数据进行AES加密
*
* @author WebSoft
* @since 2025-08-18
*/
@Component
public class EncryptedQrCodeUtil {
@Autowired
private RedisUtil redisUtil;
private static final String QR_TOKEN_PREFIX = "qr_token:";
private static final long DEFAULT_EXPIRE_MINUTES = 30; // 默认30分钟过期
/**
* 生成加密的二维码数据
*
* @param originalData 原始数据
* @param expireMinutes 过期时间(分钟)
* @return 包含token和加密数据的Map
*/
public Map<String, String> generateEncryptedData(String originalData, Long expireMinutes) {
if (StrUtil.isBlank(originalData)) {
throw new IllegalArgumentException("原始数据不能为空");
}
if (expireMinutes == null || expireMinutes <= 0) {
expireMinutes = DEFAULT_EXPIRE_MINUTES;
}
// 生成随机token作为密钥
String token = RandomUtil.randomString(32);
try {
// 使用token生成AES密钥
AES aes = createAESFromToken(token);
// 加密原始数据
String encryptedData = aes.encryptHex(originalData);
// 将token和原始数据存储到Redis中设置过期时间
String redisKey = QR_TOKEN_PREFIX + token;
redisUtil.set(redisKey, originalData, expireMinutes, TimeUnit.MINUTES);
Map<String, String> result = new HashMap<>();
result.put("token", token);
result.put("encryptedData", encryptedData);
result.put("expireMinutes", expireMinutes.toString());
return result;
} catch (Exception e) {
throw new RuntimeException("生成加密数据失败: " + e.getMessage(), e);
}
}
/**
* 解密二维码数据
*
* @param token 密钥token
* @param encryptedData 加密的数据
* @return 解密后的原始数据
*/
public String decryptData(String token, String encryptedData) {
if (StrUtil.isBlank(token) || StrUtil.isBlank(encryptedData)) {
throw new IllegalArgumentException("token和加密数据不能为空");
}
try {
// 从Redis验证token是否有效
String redisKey = QR_TOKEN_PREFIX + token;
String originalData = redisUtil.get(redisKey);
if (StrUtil.isBlank(originalData)) {
throw new RuntimeException("token已过期或无效");
}
// 使用token生成AES密钥
AES aes = createAESFromToken(token);
// 解密数据
String decryptedData = aes.decryptStr(encryptedData, CharsetUtil.CHARSET_UTF_8);
// 验证解密结果与Redis中存储的数据是否一致
if (!originalData.equals(decryptedData)) {
throw new RuntimeException("数据验证失败");
}
return decryptedData;
} catch (Exception e) {
throw new RuntimeException("解密数据失败: " + e.getMessage(), e);
}
}
/**
* 生成加密的二维码图片(自包含模式)
*
* @param originalData 原始数据
* @param width 二维码宽度
* @param height 二维码高度
* @param expireMinutes 过期时间(分钟)
* @param businessType 业务类型可选order、user、coupon等
* @return 包含二维码图片Base64和token的Map
*/
public Map<String, Object> generateEncryptedQrCode(String originalData, int width, int height, Long expireMinutes, String businessType) {
try {
// 生成加密数据
Map<String, String> encryptedInfo = generateEncryptedData(originalData, expireMinutes);
// 创建二维码内容包含token、加密数据和业务类型
Map<String, String> qrContent = new HashMap<>();
qrContent.put("token", encryptedInfo.get("token"));
qrContent.put("data", encryptedInfo.get("encryptedData"));
qrContent.put("type", "encrypted");
// 添加业务类型(如果提供)
if (StrUtil.isNotBlank(businessType)) {
qrContent.put("businessType", businessType);
}
String qrDataJson = JSONObject.toJSONString(qrContent);
// 配置二维码
QrConfig config = new QrConfig(width, height);
config.setMargin(1);
config.setForeColor(Color.BLACK);
config.setBackColor(Color.WHITE);
// 生成二维码图片
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
QrCodeUtil.generate(qrDataJson, config, "png", outputStream);
// 转换为Base64
String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
Map<String, Object> result = new HashMap<>();
result.put("qrCodeBase64", base64Image);
result.put("token", encryptedInfo.get("token"));
result.put("originalData", originalData);
result.put("expireMinutes", encryptedInfo.get("expireMinutes"));
result.put("businessType", businessType);
return result;
} catch (Exception e) {
throw new RuntimeException("生成加密二维码失败: " + e.getMessage(), e);
}
}
/**
* 生成加密的二维码图片(自包含模式,无业务类型)
* 向后兼容的重载方法
*
* @param originalData 原始数据
* @param width 二维码宽度
* @param height 二维码高度
* @param expireMinutes 过期时间(分钟)
* @return 包含二维码图片Base64和token的Map
*/
public Map<String, Object> generateEncryptedQrCode(String originalData, int width, int height, Long expireMinutes) {
return generateEncryptedQrCode(originalData, width, height, expireMinutes, null);
}
/**
* 生成业务加密二维码(门店核销模式)
* 使用统一的业务密钥,门店可以直接解密
*
* @param originalData 原始数据
* @param width 二维码宽度
* @param height 二维码高度
* @param businessKey 业务密钥(如门店密钥)
* @param expireMinutes 过期时间(分钟)
* @param businessType 业务类型order、coupon、ticket等
* @return 包含二维码图片Base64的Map
*/
public Map<String, Object> generateBusinessEncryptedQrCode(String originalData, int width, int height,
String businessKey, Long expireMinutes, String businessType) {
try {
if (StrUtil.isBlank(businessKey)) {
throw new IllegalArgumentException("业务密钥不能为空");
}
if (expireMinutes == null || expireMinutes <= 0) {
expireMinutes = DEFAULT_EXPIRE_MINUTES;
}
// 生成唯一的二维码ID
String qrId = RandomUtil.randomString(16);
// 使用业务密钥加密数据
AES aes = createAESFromToken(businessKey);
String encryptedData = aes.encryptHex(originalData);
// 将二维码信息存储到Redis用于验证和防重复使用
String qrInfoKey = "qr_info:" + qrId;
Map<String, String> qrInfo = new HashMap<>();
qrInfo.put("originalData", originalData);
qrInfo.put("createTime", String.valueOf(System.currentTimeMillis()));
qrInfo.put("businessKey", businessKey);
redisUtil.set(qrInfoKey, JSONObject.toJSONString(qrInfo), expireMinutes, TimeUnit.MINUTES);
// 创建二维码内容
Map<String, String> qrContent = new HashMap<>();
qrContent.put("qrId", qrId);
qrContent.put("data", encryptedData);
qrContent.put("type", "business_encrypted");
qrContent.put("expire", String.valueOf(System.currentTimeMillis() + expireMinutes * 60 * 1000));
// 添加业务类型(如果提供)
if (StrUtil.isNotBlank(businessType)) {
qrContent.put("businessType", businessType);
}
String qrDataJson = JSONObject.toJSONString(qrContent);
// 配置二维码
QrConfig config = new QrConfig(width, height);
config.setMargin(1);
config.setForeColor(Color.BLACK);
config.setBackColor(Color.WHITE);
// 生成二维码图片
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
QrCodeUtil.generate(qrDataJson, config, "png", outputStream);
// 转换为Base64
String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
Map<String, Object> result = new HashMap<>();
result.put("qrCodeBase64", base64Image);
result.put("qrId", qrId);
result.put("originalData", originalData);
result.put("expireMinutes", expireMinutes.toString());
result.put("businessType", businessType);
// 注意出于安全考虑不返回businessKey
return result;
} catch (Exception e) {
throw new RuntimeException("生成业务加密二维码失败: " + e.getMessage(), e);
}
}
/**
* 生成业务加密二维码(门店核销模式,无业务类型)
* 向后兼容的重载方法
*
* @param originalData 原始数据
* @param width 二维码宽度
* @param height 二维码高度
* @param businessKey 业务密钥(如门店密钥)
* @param expireMinutes 过期时间(分钟)
* @return 包含二维码图片Base64的Map
*/
public Map<String, Object> generateBusinessEncryptedQrCode(String originalData, int width, int height,
String businessKey, Long expireMinutes) {
return generateBusinessEncryptedQrCode(originalData, width, height, businessKey, expireMinutes, null);
}
/**
* 验证并解密二维码内容(自包含模式)
* 二维码包含token和加密数据扫码方无需额外信息
*
* @param qrContent 二维码扫描得到的内容
* @return 解密后的原始数据
*/
public String verifyAndDecryptQrCode(String qrContent) {
QrCodeDecryptResult result = verifyAndDecryptQrCodeWithResult(qrContent);
return result.getOriginalData();
}
/**
* 验证并解密二维码内容(自包含模式,返回完整结果)
* 包含业务类型等详细信息
*
* @param qrContent 二维码扫描得到的内容
* @return 包含解密数据和业务类型的完整结果
*/
public QrCodeDecryptResult verifyAndDecryptQrCodeWithResult(String qrContent) {
try {
// 解析二维码内容
@SuppressWarnings("unchecked")
Map<String, String> contentMap = JSONObject.parseObject(qrContent, Map.class);
String type = contentMap.get("type");
// 严格验证二维码类型,防止前端伪造
if (!isValidQrCodeType(type, "encrypted")) {
throw new RuntimeException("无效的二维码类型或二维码已被篡改");
}
String token = contentMap.get("token");
String encryptedData = contentMap.get("data");
// 验证必要字段
if (StrUtil.isBlank(token) || StrUtil.isBlank(encryptedData)) {
throw new RuntimeException("二维码数据不完整");
}
String businessType = contentMap.get("businessType"); // 获取业务类型
// 解密数据自包含模式token就在二维码中
String originalData = decryptData(token, encryptedData);
// 返回包含业务类型的完整结果
return QrCodeDecryptResult.createEncryptedResult(originalData, businessType);
} catch (Exception e) {
throw new RuntimeException("验证和解密二维码失败: " + e.getMessage(), e);
}
}
/**
* 验证并解密二维码内容(业务模式)
* 适用于门店核销场景:门店有统一的解密密钥
*
* @param qrContent 二维码扫描得到的内容
* @param businessKey 业务密钥(如门店密钥)
* @return 解密后的原始数据
*/
public String verifyAndDecryptQrCodeWithBusinessKey(String qrContent, String businessKey) {
try {
// 解析二维码内容
@SuppressWarnings("unchecked")
Map<String, String> contentMap = JSONObject.parseObject(qrContent, Map.class);
String type = contentMap.get("type");
if (!"business_encrypted".equals(type)) {
throw new RuntimeException("不是业务加密类型的二维码");
}
String encryptedData = contentMap.get("data");
String qrId = contentMap.get("qrId"); // 二维码唯一ID
// 验证二维码是否已被使用(防止重复核销)
String usedKey = "qr_used:" + qrId;
if (StrUtil.isNotBlank(redisUtil.get(usedKey))) {
throw new RuntimeException("二维码已被使用");
}
// 使用业务密钥解密
AES aes = createAESFromToken(businessKey);
String decryptedData = aes.decryptStr(encryptedData, CharsetUtil.CHARSET_UTF_8);
// 标记二维码为已使用24小时过期防止重复使用
redisUtil.set(usedKey, "used", 24L, TimeUnit.HOURS);
return decryptedData;
} catch (Exception e) {
throw new RuntimeException("业务验证和解密二维码失败: " + e.getMessage(), e);
}
}
/**
* 删除token使二维码失效
*
* @param token 要删除的token
*/
public void invalidateToken(String token) {
if (StrUtil.isNotBlank(token)) {
String redisKey = QR_TOKEN_PREFIX + token;
redisUtil.delete(redisKey);
}
}
/**
* 检查token是否有效
*
* @param token 要检查的token
* @return true表示有效false表示无效或过期
*/
public boolean isTokenValid(String token) {
if (StrUtil.isBlank(token)) {
return false;
}
String redisKey = QR_TOKEN_PREFIX + token;
String data = redisUtil.get(redisKey);
return StrUtil.isNotBlank(data);
}
/**
* 验证二维码类型是否有效
*
* @param actualType 实际的类型
* @param expectedType 期望的类型
* @return true表示有效false表示无效
*/
private boolean isValidQrCodeType(String actualType, String expectedType) {
return expectedType.equals(actualType);
}
/**
* 根据token创建AES加密器
*
* @param token 密钥token
* @return AES加密器
*/
private AES createAESFromToken(String token) {
// 使用token生成固定长度的密钥
String keyString = SecureUtil.md5(token);
// 取前16字节作为AES密钥
byte[] keyBytes = keyString.substring(0, 16).getBytes(CharsetUtil.CHARSET_UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SymmetricAlgorithm.AES.getValue());
return SecureUtil.aes(secretKey.getEncoded());
}
}

View File

@@ -0,0 +1,401 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 文件上传下载工具类
*
* @author WebSoft
* @since 2018-12-14 08:38:53
*/
public class FileServerUtil {
// 除 text/* 外也需要设置输出编码的 content-type
private final static List<String> SET_CHARSET_CONTENT_TYPES = Arrays.asList(
"application/json",
"application/javascript"
);
/**
* 上传文件
*
* @param file MultipartFile
* @param directory 文件保存的目录
* @param uuidName 是否用uuid命名
* @return File
*/
public static File upload(MultipartFile file, String directory, boolean uuidName)
throws IOException, IllegalStateException {
File outFile = getUploadFile(file.getOriginalFilename(), directory, uuidName);
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
throw new RuntimeException("make directory fail");
}
}
file.transferTo(outFile);
return outFile;
}
/**
* 上传base64格式文件
*
* @param base64 base64编码字符
* @param fileName 文件名称, 为空使用uuid命名
* @param directory 文件保存的目录
* @return File
*/
public static File upload(String base64, String fileName, String directory)
throws FileNotFoundException, IORuntimeException {
if (StrUtil.isBlank(base64) || !base64.startsWith("data:image/") || !base64.contains(";base64,")) {
throw new RuntimeException("base64 data error");
}
String suffix = "." + base64.substring(11, base64.indexOf(";")); // 获取文件后缀
boolean uuidName = StrUtil.isBlank(fileName);
File outFile = getUploadFile(uuidName ? suffix : fileName, directory, uuidName);
byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
IoUtil.write(new FileOutputStream(outFile), true, bytes);
return outFile;
}
/**
* 获取上传文件位置
*
* @param name 文件名称
* @param directory 上传目录
* @param uuidName 是否使用uuid命名
* @return File
*/
public static File getUploadFile(String name, String directory, boolean uuidName) {
// 当前日期作为上传子目录
String dir = new SimpleDateFormat("yyyyMMdd/").format(new Date());
// 获取文件后缀
String suffix = (name == null || !name.contains(".")) ? "" : name.substring(name.lastIndexOf("."));
// 使用uuid命名
if (uuidName || name == null) {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return new File(directory, dir + uuid + suffix);
}
// 使用原名称, 存在相同则加(1)
File file = new File(directory, dir + name);
String prefix = StrUtil.removeSuffix(name, suffix);
int sameSize = 2;
while (file.exists()) {
file = new File(directory, dir + prefix + "(" + sameSize + ")" + suffix);
sameSize++;
}
return file;
}
/**
* 查看文件, 支持断点续传
*
* @param file 文件
* @param pdfDir office转pdf输出目录
* @param officeHome openOffice安装目录
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void preview(File file, String pdfDir, String officeHome,
HttpServletResponse response, HttpServletRequest request) {
preview(file, false, null, pdfDir, officeHome, response, request);
}
/**
* 查看文件, 支持断点续传
*
* @param file 文件
* @param forceDownload 是否强制下载
* @param fileName 强制下载的文件名称
* @param pdfDir office转pdf输出目录
* @param officeHome openOffice安装目录
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void preview(File file, boolean forceDownload, String fileName, String pdfDir, String officeHome,
HttpServletResponse response, HttpServletRequest request) {
CommonUtil.addCrossHeaders(response);
if (file == null || !file.exists()) {
outNotFund(response);
return;
}
if (forceDownload) {
setDownloadHeader(response, StrUtil.isBlank(fileName) ? file.getName() : fileName);
} else {
// office转pdf预览
if (OpenOfficeUtil.canConverter(file.getName())) {
File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath(), pdfDir, officeHome);
if (pdfFile != null) {
file = pdfFile;
}
}
// 获取文件类型
String contentType = getContentType(file);
if (contentType != null) {
response.setContentType(contentType);
// 设置编码
if (contentType.startsWith("text/") || SET_CHARSET_CONTENT_TYPES.contains(contentType)) {
try {
String charset = JChardetFacadeUtil.detectCodepage(file.toURI().toURL());
if (charset != null) {
response.setCharacterEncoding(charset);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
} else {
setDownloadHeader(response, file.getName());
}
}
response.setHeader("Cache-Control", "public");
output(file, response, request);
}
/**
* 查看缩略图
*
* @param file 原文件
* @param thumbnail 缩略图文件
* @param size 缩略图文件的最大值(kb)
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void previewThumbnail(File file, File thumbnail, Integer size,
HttpServletResponse response, HttpServletRequest request) {
// 如果是图片并且缩略图不存在则生成
if (!thumbnail.exists() && isImage(file)) {
long fileSize = file.length();
if ((fileSize / 1024) > size) {
try {
if (thumbnail.getParentFile().mkdirs()) {
System.out.println("生成缩略图1>>>>>>>>>>>>>>>> = " + thumbnail);
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
if (thumbnail.exists() && thumbnail.length() > file.length()) {
FileUtil.copy(file, thumbnail, true);
}
}else{
System.out.println("生成缩略图2>>>>>>>>>>>>>>>> = " + thumbnail);
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
if (thumbnail.exists() && thumbnail.length() > file.length()) {
FileUtil.copy(file, thumbnail, true);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
preview(file, null, null, response, request);
return;
}
}
preview(thumbnail.exists() ? thumbnail : file, null, null, response, request);
}
/**
* 输出文件流, 支持断点续传
*
* @param file 文件
* @param response HttpServletResponse
* @param request HttpServletRequest
*/
public static void output(File file, HttpServletResponse response, HttpServletRequest request) {
long length = file.length(); // 文件总大小
long start = 0, to = length - 1; // 开始读取位置, 结束读取位置
long lastModified = file.lastModified(); // 文件修改时间
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("ETag", "\"" + length + "-" + lastModified + "\"");
response.setHeader("Last-Modified", new Date(lastModified).toString());
String range = request.getHeader("Range");
if (range != null) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String[] ranges = range.replace("bytes=", "").split("-");
start = Long.parseLong(ranges[0].trim());
if (ranges.length > 1) {
to = Long.parseLong(ranges[1].trim());
}
response.setHeader("Content-Range", "bytes " + start + "-" + to + "/" + length);
}
response.setHeader("Content-Length", String.valueOf(to - start + 1));
try {
output(file, response.getOutputStream(), 2048, start, to);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出文件流
*
* @param file 文件
* @param os 输出流
*/
public static void output(File file, OutputStream os) {
output(file, os, null);
}
/**
* 输出文件流
*
* @param file 文件
* @param os 输出流
* @param size 读取缓冲区大小
*/
public static void output(File file, OutputStream os, Integer size) {
output(file, os, size, null, null);
}
/**
* 输出文件流, 支持分片
*
* @param file 文件
* @param os 输出流
* @param size 读取缓冲区大小
* @param start 开始位置
* @param to 结束位置
*/
public static void output(File file, OutputStream os, Integer size, Long start, Long to) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
if (start != null) {
long skip = is.skip(start);
if (skip < start) {
System.out.println("ERROR: skip fail[ skipped=" + skip + ", start= " + start + " ]");
}
to = to - start + 1;
}
byte[] bytes = new byte[size == null ? 2048 : size];
int len;
if (to == null) {
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
} else {
while (to > 0 && (len = is.read(bytes)) != -1) {
os.write(bytes, 0, to < len ? (int) ((long) to) : len);
to -= len;
}
}
os.flush();
} catch (IOException ignored) {
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
/**
* 获取文件类型
*
* @param file 文件
* @return String
*/
public static String getContentType(File file) {
String contentType = null;
if (file.exists()) {
try {
contentType = new Tika().detect(file);
} catch (IOException e) {
e.printStackTrace();
}
}
return contentType;
}
/**
* 判断文件是否是图片类型
*
* @param file 文件
* @return boolean
*/
public static boolean isImage(File file) {
return isImage(getContentType(file));
}
/**
* 判断文件是否是图片类型
*
* @param contentType 文件类型
* @return boolean
*/
public static boolean isImage(String contentType) {
return contentType != null && contentType.startsWith("image/");
}
/**
* 设置下载文件的header
*
* @param response HttpServletResponse
* @param fileName 文件名称
*/
public static void setDownloadHeader(HttpServletResponse response, String fileName) {
response.setContentType("application/force-download");
try {
fileName = URLEncoder.encode(fileName, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
}
/**
* 输出404错误页面
*
* @param response HttpServletResponse
*/
public static void outNotFund(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
outMessage("404 Not Found", null, response);
}
/**
* 输出错误页面
*
* @param title 标题
* @param message 内容
* @param response HttpServletResponse
*/
public static void outMessage(String title, String message, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter writer = response.getWriter();
writer.write("<!doctype html>");
writer.write("<title>" + title + "</title>");
writer.write("<h1 style=\"text-align: center\">" + title + "</h1>");
if (message != null) {
writer.write(message);
}
writer.write("<hr/><p style=\"text-align: center\">WebSoft File Server</p>");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,311 @@
package com.gxwebsoft.common.core.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}

View File

@@ -0,0 +1,96 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.codec.Base64Encoder;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.io.File;
public class ImageUtil {
public static String ImageBase64(String imgUrl) {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try{
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=is.read(buffer)) != -1 ){
//用输出流往buffer里写入数据中间参数代表从哪个位置开始读len代表读取的长度
outStream.write(buffer, 0, len);
}
// 对字节数组Base64编码
return new Base64Encoder().encode(outStream.toByteArray());
}catch (Exception e) {
e.printStackTrace();
}
finally{
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpUrl != null) {
httpUrl.disconnect();
}
}
return null;
}
public static void adjustQuality(File inputFile, File outputFile, float quality) throws IOException {
// 读取图片文件
BufferedImage image = ImageIO.read(inputFile);
// 获取JPEG ImageWriters的迭代器
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
// 创建输出文件
ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
// 创建ImageWriteParam并设置压缩质量
ImageWriteParam iwp = writer.getDefaultWriteParam();
if (iwp.canWriteCompressed()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality); // 设置质量1.0为最好0.0最差
}
// 写入图片
writer.write(null, new IIOImage(image, null, null), iwp);
writer.dispose();
ios.close();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,69 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
/**
* JSON解析工具类
*
* @author WebSoft
* @since 2017-06-10 10:10:39
*/
public class JSONUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
/**
* 对象转json字符串
*
* @param value 对象
* @return String
*/
public static String toJSONString(Object value) {
return toJSONString(value, false);
}
/**
* 对象转json字符串
*
* @param value 对象
* @param pretty 是否格式化输出
* @return String
*/
public static String toJSONString(Object value, boolean pretty) {
if (value != null) {
if (value instanceof String) {
return (String) value;
}
try {
if (pretty) {
return objectWriter.writeValueAsString(value);
}
return objectMapper.writeValueAsString(value);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* json字符串转对象
*
* @param json String
* @param clazz Class
* @return T
*/
public static <T> T parseObject(String json, Class<T> clazz) {
if (StrUtil.isNotBlank(json) && clazz != null) {
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@@ -0,0 +1,85 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import static com.gxwebsoft.common.core.constants.QRCodeConstants.*;
/**
* 常用工具方法
*
* @author WebSoft
* @since 2017-06-10 10:10:22
*/
public class MyQrCodeUtil {
@Value("${config.upload-path}")
private static String uploadPath;
private static final String logoUrl = "https://file.wsdns.cn/20230430/6fa31aca3b0d47af98a149cf2dd26a4f.jpeg";
/**
* 生成用户二维码
*/
public static String getUserCode(Integer userId, String content) throws IOException {
return createQrCode(USER_QRCODE,userId,content);
}
/**
* 生成工单二维码
*/
public static String getTaskCode(Integer taskId, String content) throws IOException {
return createQrCode(TASK_QRCODE,taskId,content);
}
/**
* 生成商品二维码
*/
public static String getGoodsCode(Integer goodsId, String content) throws IOException {
return createQrCode(GOODS_QRCODE,goodsId,content);
}
/**
* 生成自定义二维码
*/
public static String getCodeMap(HashMap<String, String> map) throws IOException {
return "";
}
/**
* 生成带水印的二维码
* @param type 类型
* @param id 实体ID
* @param content 二维码内容
* @return 二维码图片地址
*/
public static String createQrCode(String type,Integer id, String content) throws IOException {
String filePath = uploadPath + "/file/qrcode/".concat(type).concat("/");
String qrcodeUrl = "https://file.websoft.top/qrcode/".concat(type).concat("/");
// 将URL转为BufferedImage
BufferedImage bufferedImage = ImageIO.read(new URL(logoUrl));
// 生成二维码
QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(1);
// 附带小logo
config.setImg(bufferedImage);
// 保存路径
filePath = filePath.concat(id + ".jpg");
qrcodeUrl = qrcodeUrl.concat(id + ".jpg") + "?v=" + DateUtil.current();
// 生成二维码
QrCodeUtil.generate(content, config, FileUtil.file(filePath));
return qrcodeUrl;
}
}

View File

@@ -0,0 +1,124 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.StrUtil;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import java.io.File;
import java.util.Arrays;
import java.util.Base64;
/**
* OpenOfficeUtil
*
* @author WebSoft
* @since 2018-12-14 08:38:19
*/
public class OpenOfficeUtil {
// 支持转换pdf的文件后缀列表
private static final String[] CAN_CONVERTER_FILES = new String[]{
"doc", "docx", "xls", "xlsx", "ppt", "pptx"
};
/**
* 文件转pdf
*
* @param filePath 源文件路径
* @param outDir 输出目录
* @param officeHome OpenOffice安装路径
* @return File
*/
public static File converterToPDF(String filePath, String outDir, String officeHome) {
return converterToPDF(filePath, outDir, officeHome, true);
}
/**
* 文件转pdf
*
* @param filePath 源文件路径
* @param outDir 输出目录
* @param officeHome OpenOffice安装路径
* @param cache 是否使用上次转换过的文件
* @return File
*/
public static File converterToPDF(String filePath, String outDir, String officeHome, boolean cache) {
if (StrUtil.isBlank(filePath)) {
return null;
}
File srcFile = new File(filePath);
if (!srcFile.exists()) {
return null;
}
// 是否转换过
String outPath = Base64.getEncoder().encodeToString(filePath.getBytes())
.replace("/", "-").replace("+", "-");
File outFile = new File(outDir, outPath + ".pdf");
if (cache && outFile.exists()) {
return outFile;
}
// 转换
OfficeManager officeManager = null;
try {
officeManager = getOfficeManager(officeHome);
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
return converterFile(srcFile, outFile, converter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (officeManager != null) {
officeManager.stop();
}
}
return null;
}
/**
* 转换文件
*
* @param inFile 源文件
* @param outFile 输出文件
* @param converter OfficeDocumentConverter
* @return File
*/
public static File converterFile(File inFile, File outFile, OfficeDocumentConverter converter) {
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
return outFile;
}
}
converter.convert(inFile, outFile);
return outFile;
}
/**
* 判断文件后缀是否可以转换pdf
*
* @param path 文件路径
* @return boolean
*/
public static boolean canConverter(String path) {
try {
String suffix = path.substring(path.lastIndexOf(".") + 1);
return Arrays.asList(CAN_CONVERTER_FILES).contains(suffix);
} catch (Exception e) {
return false;
}
}
/**
* 连接并启动OpenOffice
*
* @param officeHome OpenOffice安装路径
* @return OfficeManager
*/
public static OfficeManager getOfficeManager(String officeHome) {
if (officeHome == null || officeHome.trim().isEmpty()) return null;
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
config.setOfficeHome(officeHome); // 设置OpenOffice安装目录
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start(); // 启动OpenOffice服务
return officeManager;
}
}

View File

@@ -0,0 +1,93 @@
package com.gxwebsoft.common.core.utils;
import lombok.Data;
/**
* 二维码解密结果类
* 包含解密后的数据和业务类型信息
*
* @author WebSoft
* @since 2025-08-18
*/
@Data
public class QrCodeDecryptResult {
/**
* 解密后的原始数据
*/
private String originalData;
/**
* 业务类型order、user、coupon、ticket等
*/
private String businessType;
/**
* 二维码类型encrypted 或 business_encrypted
*/
private String qrType;
/**
* 二维码ID仅业务模式有
*/
private String qrId;
/**
* 过期时间戳(仅业务模式有)
*/
private Long expireTime;
/**
* 是否已过期
*/
private Boolean expired;
public QrCodeDecryptResult() {}
public QrCodeDecryptResult(String originalData, String businessType, String qrType) {
this.originalData = originalData;
this.businessType = businessType;
this.qrType = qrType;
this.expired = false;
}
/**
* 创建自包含模式的解密结果
*/
public static QrCodeDecryptResult createEncryptedResult(String originalData, String businessType) {
return new QrCodeDecryptResult(originalData, businessType, "encrypted");
}
/**
* 创建业务模式的解密结果
*/
public static QrCodeDecryptResult createBusinessResult(String originalData, String businessType,
String qrId, Long expireTime) {
QrCodeDecryptResult result = new QrCodeDecryptResult(originalData, businessType, "business_encrypted");
result.setQrId(qrId);
result.setExpireTime(expireTime);
result.setExpired(expireTime != null && System.currentTimeMillis() > expireTime);
return result;
}
/**
* 检查是否有业务类型
*/
public boolean hasBusinessType() {
return businessType != null && !businessType.trim().isEmpty();
}
/**
* 检查是否为业务模式
*/
public boolean isBusinessMode() {
return "business_encrypted".equals(qrType);
}
/**
* 检查是否为自包含模式
*/
public boolean isEncryptedMode() {
return "encrypted".equals(qrType);
}
}

View File

@@ -0,0 +1,279 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.result.RedisResult;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
@Component
public class RedisUtil {
private final StringRedisTemplate stringRedisTemplate;
public static Integer tenantId;
public RedisUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
/**
* 写入redis缓存
* @param key [表名]:id
* @param entity 实体类对象
* 示例 cacheClient.set("merchant:"+id,merchant)
*/
public <T> void set(String key, T entity){
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity));
}
/**
* 写入redis缓存
* @param key [表名]:id
* @param entity 实体类对象
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
*/
public <T> void set(String key, T entity, Long time, TimeUnit unit){
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity),time,unit);
}
/**
* 读取redis缓存
* @param key [表名]:id
* 示例 cacheClient.get(key)
* @return merchant
*/
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 读取redis缓存
* @param key [表名]:id
* @param clazz Merchant.class
* @param <T>
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
* @return merchant
*/
public <T> T get(String key, Class<T> clazz) {
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(json)){
return JSONUtil.parseObject(json, clazz);
}
return null;
}
/**
* 写redis缓存(哈希类型)
* @param key [表名]:id
* @param field 字段
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
*/
public <T> void hPut(String key, String field, T entity) {
stringRedisTemplate.opsForHash().put(key,field,JSONUtil.toJSONString(entity));
}
/**
* 写redis缓存(哈希类型)
* @param key [表名]:id
* @param map 字段
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
*/
public void hPutAll(String key, Map<String,String> map) {
stringRedisTemplate.opsForHash().putAll(key,map);
}
/**
* 读取redis缓存(哈希类型)
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
* @param key [表名]:id
* @param field 字段
* @return merchant
*/
public <T> T hGet(String key, String field, Class<T> clazz) {
Object obj = stringRedisTemplate.opsForHash().get(key, field);
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
}
public List<Object> hValues(String key){
return stringRedisTemplate.opsForHash().values(key);
}
public Long hSize(String key){
return stringRedisTemplate.opsForHash().size(key);
}
// 逻辑过期方式写入redis
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
// 设置逻辑过期时间
final RedisResult<T> redisResult = new RedisResult<>();
redisResult.setData(value);
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJSONString(redisResult));
}
// 读取redis
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
String key = keyPrefix + id;
// 1.从redis查询缓存
final String json = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(json)) {
// 3.存在,直接返回
return JSONUtil.parseObject(json,clazz);
}
// 判断命中的是否为空值
if (json != null) {
return null;
}
// 4. 不存在跟进ID查询数据库
R r = dbFallback.apply(id);
// 5. 数据库不存在,返回错误
if(r == null){
// 空值写入数据库
this.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
return null;
}
// 写入redis
this.set(key,r,time,unit);
return r;
}
/**
* 添加商户定位点
* @param key geo
* @param id
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
*/
public <T> void geoAdd(String key, Double x, Double y, String id){
stringRedisTemplate.opsForGeo().add(key,new Point(x,y),id);
}
/**
* 删除定位
* @param key geo
* @param id
* 示例 cacheClient.geoRemove("merchant-geo",id)
*/
public void geoRemove(String key, Integer id){
stringRedisTemplate.opsForGeo().remove(key,id.toString());
}
public <T> void sAdd(String key, T entity){
stringRedisTemplate.opsForSet().add(key,JSONUtil.toJSONString(entity));
}
public <T> Set<String> sMembers(String key){
return stringRedisTemplate.opsForSet().members(key);
}
// 更新排行榜
public void zAdd(String key, Integer userId, Double value) {
stringRedisTemplate.opsForZSet().add(key,userId.toString(),value);
}
// 增加元素的score值并返回增加后的值
public Double zIncrementScore(String key,Integer userId, Double delta){
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
}
// 获取排名榜
public Set<String> range(String key, Integer start, Integer end) {
return stringRedisTemplate.opsForZSet().range(key, start, end);
}
// 获取排名榜
public Set<String> reverseRange(String key, Integer start, Integer end){
return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
}
// 获取分数
public Double score(String key, Object value){
return stringRedisTemplate.opsForZSet().score(key, value);
}
public void delete(String key){
stringRedisTemplate.delete(key);
}
// 存储在list头部
public void leftPush(String key, String keyword){
stringRedisTemplate.opsForList().leftPush(key,keyword);
}
// 获取列表指定范围内的元素
public List<String> listRange(String key,Long start, Long end){
return stringRedisTemplate.opsForList().range(key, start, end);
}
// 获取列表长度
public Long listSize(String key){
return stringRedisTemplate.opsForList().size(key);
}
// 裁剪list
public void listTrim(String key){
stringRedisTemplate.opsForList().trim(key, 0L, 100L);
}
/**
* 读取后台系统设置信息
* @param keyName 键名wx-word
* @param tenantId 租户ID
* @return
* key示例 cache10048:setting:wx-work
*/
public JSONObject getSettingInfo(String keyName,Integer tenantId){
String key = "cache" + tenantId + ":setting:" + keyName;
final String cache = stringRedisTemplate.opsForValue().get(key);
assert cache != null;
return JSON.parseObject(cache);
}
/**
* KEY前缀
* cache[tenantId]:[key+id]
*/
public static String prefix(String key){
String prefix = "cache";
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
final Integer tenantId = ((User) object).getTenantId();
prefix = prefix.concat(tenantId.toString()).concat(":");
}
}
return prefix.concat(key);
}
// 组装key
public String key(String name,Integer id){
return name.concat(":").concat(id.toString());
}
// 获取上传配置
public HashMap<String, String> getUploadConfig(Integer tenantId){
String key = "setting:upload:" + tenantId;
final String s = get(key);
final JSONObject jsonObject = JSONObject.parseObject(s);
final String uploadMethod = jsonObject.getString("uploadMethod");
final String bucketDomain = jsonObject.getString("bucketDomain");
final HashMap<String, String> map = new HashMap<>();
map.put("uploadMethod",uploadMethod);
map.put("bucketDomain",bucketDomain);
return map;
}
}

View File

@@ -0,0 +1,197 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.system.entity.KVEntity;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* 签名检查和获取签名
* https://blog.csdn.net/u011628753/article/details/110251445
* @author leng
*
*/
public class SignCheckUtil {
// 签名字段
public final static String SIGN = "sign";
/**
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
*
* @param params
* @param key
* @return
*/
public static boolean signCheck(JSONObject params, String key) {
if (null != params) {
Map<String, String> map = new HashMap<>();
params.forEach((k, v) -> {
map.put(k, v.toString());
});
return signCheck(map, key);
}
return false;
}
/**
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
*
* @param params
* @param key
* 签名key不允许为空
* @return
*/
public static boolean signCheck(Map<String, String> params, String key) {
String sign = params.get(SIGN);// 签名
if (null == sign) {
return false;
}
String signTemp = getSignString(params,key);
if (null == signTemp) {
return false;
}
return signTemp.equals(sign);
}
/**
* 获取签名的字符串
*
* @param params
* @param key
* @return
*/
public static String getSignString(JSONObject params, String key) {
if (null != params) {
Map<String, String> map = new HashMap<>();
params.forEach((k, v) -> {
map.put(k, v.toString());
});
return getSignString(map, key);
}
return null;
}
/**
* 获取签名的字符串
*
* @param params
* @param key
* @return
*/
public static String getSignString(Map<String, String> params, String key) {
// 签名
if (null == params || params.size() == 0) {
return null;
}
key = (null == key) ? "" : key;
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
params.forEach((k, v) -> {
if (!SIGN.equals(k)) {
list.add(KVEntity.build(k, v));
}
});
Collections.sort(list, (obj1, obj2) -> {
return obj1.getK().compareTo(obj2.getK());
});
StringBuffer sb = new StringBuffer();
for (KVEntity<String, String> kv : list) {
String value = kv.getV();
if (!StringUtils.isEmpty(value)) {
sb.append(kv.getV()).append("-");
}
}
sb.append(key);
System.out.println("md5加密前的字符串 = " + sb + key);
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
return signTemp;
}
/**
* 获取微信签名的字符串
*
* 注意签名sign的生成方式具体见官方文档传参都要参与生成签名且参数名按照字典序排序最后接上APP_KEY,转化成大写)
*
* @param params
* @param key
* @return
*/
public static String getWXSignString(Map<String, String> params, String key) {
// 签名
if (null == params || params.size() == 0 || StringUtils.isEmpty(key)) {
return null;
}
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
params.forEach((k, v) -> {
if (!SIGN.equals(k)) {
list.add(KVEntity.build(k, v));
}
});
Collections.sort(list, (obj1, obj2) -> {
return obj1.getK().compareTo(obj2.getK());
});
StringBuffer sb = new StringBuffer();
for (KVEntity<String, String> kv : list) {
String value = kv.getV();
if (!StringUtils.isEmpty(value)) {
sb.append(kv.getK() + "=" + value + "&");
}
}
sb.append("key=" + key);
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
return signTemp;
}
/**
* 微信签名验证
* @param params
* @param key
* @return
*/
public static boolean WXsignCheck(Map<String, String> params, String key) {
String sign = params.get(SIGN);
if (StringUtils.isEmpty(sign)) {
return false;
}
return sign.equals(getWXSignString(params, key));
}
/**
* 白名单校验
* @param domainName abc.com
* @return true
*/
public boolean checkWhiteDomains(List<String> whiteDomains, String domainName) {
if(whiteDomains == null){
return true;
}
if (whiteDomains.isEmpty()) {
return true;
}
// 服务器域名白名单列表
whiteDomains.add("server.websoft.top");
System.out.println("whiteDomains = " + whiteDomains);
System.out.println(">>> domainName = " + domainName);
for(String item: whiteDomains){
if(Objects.equals(item, domainName)){
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,171 @@
package com.gxwebsoft.common.core.utils;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.gxwebsoft.common.core.config.ConfigProperties;
import javax.annotation.Resource;
/**
* 微信支付证书自动配置工具类
* 使用RSAAutoCertificateConfig实现证书自动管理
*
* @author 科技小王子
* @since 2024-07-26
*/
@Slf4j
@Component
public class WechatCertAutoConfig {
@Value("${spring.profiles.active:prod}")
private String activeProfile;
@Resource
private ConfigProperties configProperties;
/**
* 创建微信支付自动证书配置
*
* @param merchantId 商户号
* @param privateKeyPath 私钥文件路径
* @param merchantSerialNumber 商户证书序列号
* @param apiV3Key APIv3密钥
* @return 微信支付配置对象
*/
public Config createAutoConfig(String merchantId, String privateKeyPath,
String merchantSerialNumber, String apiV3Key) {
try {
log.info("创建微信支付自动证书配置...");
log.info("商户号: {}", merchantId);
log.info("私钥路径: {}", privateKeyPath);
log.info("证书序列号: {}", merchantSerialNumber);
Config config = new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
log.info("✅ 微信支付自动证书配置创建成功");
log.info("🔄 系统将自动管理平台证书的下载和更新");
return config;
} catch (Exception e) {
log.error("❌ 创建微信支付自动证书配置失败: {}", e.getMessage(), e);
// 提供详细的错误诊断信息
log.error("🔍 错误诊断:");
log.error("1. 请检查商户平台是否已开启API安全功能");
log.error("2. 请确认已申请使用微信支付公钥");
log.error("3. 请验证APIv3密钥和证书序列号是否正确");
log.error("4. 请检查网络连接是否正常");
log.error("5. 请确认私钥文件路径是否正确: {}", privateKeyPath);
throw new RuntimeException("微信支付自动证书配置失败: " + e.getMessage(), e);
}
}
/**
* 使用默认开发环境配置创建自动证书配置
* 根据当前环境自动选择证书路径
* 开发环境拼接规则配置文件upload-path + dev/wechat/ + 租户ID
*
* @return 微信支付配置对象
*/
public Config createDefaultDevConfig() {
String merchantId = "1723321338";
String privateKeyPath;
String merchantSerialNumber = "2B933F7C35014A1C363642623E4A62364B34C4EB";
String apiV3Key = "0kF5OlPr482EZwtn9zGufUcqa7ovgxRL";
// 根据环境选择证书路径
if ("dev".equals(activeProfile)) {
// 开发环境使用配置文件upload-path拼接证书路径
String uploadPath = configProperties.getUploadPath(); // 配置文件路径
String tenantId = "10550"; // 租户ID
String certPath = uploadPath + "dev/wechat/" + tenantId + "/";
privateKeyPath = certPath + "apiclient_key.pem";
log.info("开发环境使用配置文件upload-path拼接证书路径");
log.info("配置文件upload-path: {}", uploadPath);
log.info("证书基础路径: {}", certPath);
log.info("私钥文件路径: {}", privateKeyPath);
} else {
// 生产环境:使用相对路径,由系统动态解析
privateKeyPath = "src/main/resources/certs/dev/wechat/apiclient_key.pem";
log.info("生产环境:使用相对证书路径 - {}", privateKeyPath);
}
return createAutoConfig(merchantId, privateKeyPath, merchantSerialNumber, apiV3Key);
}
/**
* 测试证书配置是否正常
*
* @param config 微信支付配置
* @return 是否配置成功
*/
public boolean testConfig(Config config) {
try {
// 这里可以添加一些基本的配置验证逻辑
log.info("🧪 测试微信支付证书配置...");
if (config == null) {
log.error("配置对象为空");
return false;
}
log.info("✅ 证书配置测试通过");
return true;
} catch (Exception e) {
log.error("❌ 证书配置测试失败: {}", e.getMessage(), e);
return false;
}
}
/**
* 获取配置使用说明
*
* @return 使用说明
*/
public String getUsageInstructions() {
return """
🚀 微信支付自动证书配置使用说明
================================
✅ 优势:
1. 自动下载微信支付平台证书
2. 证书过期时自动更新
3. 无需手动管理 wechatpay_cert.pem 文件
4. 符合微信支付官方最佳实践
📝 使用方法:
// 方法1: 使用默认开发环境配置
Config config = wechatCertAutoConfig.createDefaultDevConfig();
// 方法2: 自定义配置
Config config = wechatCertAutoConfig.createAutoConfig(
"商户号",
"私钥路径",
"证书序列号",
"APIv3密钥"
);
🔧 前置条件:
1. 微信商户平台已开启API安全功能
2. 已申请使用微信支付公钥
3. 私钥文件存在且路径正确
4. 网络连接正常
📚 更多信息:
https://pay.weixin.qq.com/doc/v3/merchant/4012153196
""";
}
}

View File

@@ -0,0 +1,314 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
/**
* 微信支付证书诊断工具
* 专门用于诊断和解决证书相关问题
*
* @author 科技小王子
* @since 2025-07-29
*/
@Slf4j
@Component
public class WechatPayCertificateDiagnostic {
private final CertificateProperties certConfig;
private final CertificateLoader certificateLoader;
public WechatPayCertificateDiagnostic(CertificateProperties certConfig, CertificateLoader certificateLoader) {
this.certConfig = certConfig;
this.certificateLoader = certificateLoader;
}
/**
* 全面诊断微信支付证书配置
*
* @param payment 支付配置
* @param tenantId 租户ID
* @param environment 环境dev/prod
* @return 诊断结果
*/
public DiagnosticResult diagnoseCertificateConfig(Payment payment, Integer tenantId, String environment) {
DiagnosticResult result = new DiagnosticResult();
log.info("=== 开始微信支付证书诊断 ===");
log.info("租户ID: {}, 环境: {}", tenantId, environment);
try {
// 1. 检查基本配置
checkBasicConfig(payment, result);
// 2. 检查证书文件
checkCertificateFiles(payment, tenantId, environment, result);
// 3. 检查证书内容
validateCertificateContent(payment, tenantId, environment, result);
// 4. 生成建议
generateRecommendations(result);
} catch (Exception e) {
result.addError("诊断过程中发生异常: " + e.getMessage());
log.error("证书诊断异常", e);
}
log.info("=== 证书诊断完成 ===");
return result;
}
/**
* 检查基本配置
*/
private void checkBasicConfig(Payment payment, DiagnosticResult result) {
if (payment == null) {
result.addError("支付配置为空");
return;
}
if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
result.addError("商户号未配置");
} else {
result.addInfo("商户号: " + payment.getMchId());
}
if (payment.getAppId() == null || payment.getAppId().trim().isEmpty()) {
result.addError("应用ID未配置");
} else {
result.addInfo("应用ID: " + payment.getAppId());
}
if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
result.addError("商户证书序列号未配置");
} else {
result.addInfo("商户证书序列号: " + payment.getMerchantSerialNumber());
}
if (payment.getApiKey() == null || payment.getApiKey().trim().isEmpty()) {
result.addWarning("数据库中APIv3密钥未配置将使用配置文件默认值");
} else {
result.addInfo("APIv3密钥: 已配置(" + payment.getApiKey().length() + "位)");
}
}
/**
* 检查证书文件
*/
private void checkCertificateFiles(Payment payment, Integer tenantId, String environment, DiagnosticResult result) {
if ("dev".equals(environment)) {
// 开发环境证书检查
String tenantCertPath = "dev/wechat/" + tenantId;
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
String apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
// 检查私钥文件
if (certificateLoader.certificateExists(privateKeyPath)) {
result.addInfo("✅ 私钥文件存在: " + privateKeyPath);
try {
String privateKeyFile = certificateLoader.loadCertificatePath(privateKeyPath);
result.addInfo("私钥文件路径: " + privateKeyFile);
} catch (Exception e) {
result.addError("私钥文件加载失败: " + e.getMessage());
}
} else {
result.addError("❌ 私钥文件不存在: " + privateKeyPath);
}
// 检查商户证书文件
if (certificateLoader.certificateExists(apiclientCertPath)) {
result.addInfo("✅ 商户证书文件存在: " + apiclientCertPath);
} else {
result.addWarning("⚠️ 商户证书文件不存在: " + apiclientCertPath + " (自动证书配置不需要此文件)");
}
} else {
// 生产环境证书检查
if (payment.getApiclientKey() != null) {
result.addInfo("私钥文件配置: " + payment.getApiclientKey());
} else {
result.addError("生产环境私钥文件路径未配置");
}
if (payment.getApiclientCert() != null) {
result.addInfo("商户证书文件配置: " + payment.getApiclientCert());
} else {
result.addWarning("生产环境商户证书文件路径未配置 (自动证书配置不需要此文件)");
}
}
}
/**
* 验证证书内容
*/
private void validateCertificateContent(Payment payment, Integer tenantId, String environment, DiagnosticResult result) {
try {
if ("dev".equals(environment)) {
String tenantCertPath = "dev/wechat/" + tenantId;
String apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
if (certificateLoader.certificateExists(apiclientCertPath)) {
validateX509Certificate(apiclientCertPath, payment.getMerchantSerialNumber(), result);
}
}
} catch (Exception e) {
result.addWarning("证书内容验证失败: " + e.getMessage());
}
}
/**
* 验证X509证书
*/
private void validateX509Certificate(String certPath, String expectedSerialNumber, DiagnosticResult result) {
try {
String actualCertPath = certificateLoader.loadCertificatePath(certPath);
try (InputStream inputStream = new FileInputStream(new File(actualCertPath))) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
if (cert != null) {
String actualSerialNumber = cert.getSerialNumber().toString(16).toUpperCase();
result.addInfo("证书序列号: " + actualSerialNumber);
result.addInfo("证书有效期: " + cert.getNotBefore() + "" + cert.getNotAfter());
result.addInfo("证书主体: " + cert.getSubjectX500Principal().toString());
// 检查序列号是否匹配
if (expectedSerialNumber != null && !expectedSerialNumber.equalsIgnoreCase(actualSerialNumber)) {
result.addError("证书序列号不匹配! 配置: " + expectedSerialNumber + ", 实际: " + actualSerialNumber);
} else {
result.addInfo("✅ 证书序列号匹配");
}
// 检查证书是否过期
long now = System.currentTimeMillis();
if (now < cert.getNotBefore().getTime()) {
result.addError("证书尚未生效");
} else if (now > cert.getNotAfter().getTime()) {
result.addError("证书已过期");
} else {
result.addInfo("✅ 证书在有效期内");
}
} else {
result.addError("无法解析证书文件");
}
}
} catch (Exception e) {
result.addError("证书验证失败: " + e.getMessage());
}
}
/**
* 生成建议
*/
private void generateRecommendations(DiagnosticResult result) {
if (result.hasErrors()) {
result.addRecommendation("🔧 修复建议:");
String errorText = result.getErrors();
if (errorText.contains("商户号")) {
result.addRecommendation("1. 请在支付配置中设置正确的商户号");
}
if (errorText.contains("序列号")) {
result.addRecommendation("2. 请检查商户证书序列号是否正确,可在微信商户平台查看");
}
if (errorText.contains("证书文件")) {
result.addRecommendation("3. 请确保证书文件已正确放置在指定目录");
}
if (errorText.contains("过期")) {
result.addRecommendation("4. 请更新过期的证书文件");
}
result.addRecommendation("5. 建议使用RSAAutoCertificateConfig自动证书配置可避免手动管理证书");
result.addRecommendation("6. 确保在微信商户平台开启API安全功能并申请使用微信支付公钥");
} else {
result.addRecommendation("✅ 证书配置正常,建议使用自动证书配置以获得最佳体验");
}
}
/**
* 诊断结果类
*/
public static class DiagnosticResult {
private final StringBuilder errors = new StringBuilder();
private final StringBuilder warnings = new StringBuilder();
private final StringBuilder info = new StringBuilder();
private final StringBuilder recommendations = new StringBuilder();
public void addError(String error) {
if (errors.length() > 0) errors.append("\n");
errors.append(error);
}
public void addWarning(String warning) {
if (warnings.length() > 0) warnings.append("\n");
warnings.append(warning);
}
public void addInfo(String information) {
if (info.length() > 0) info.append("\n");
info.append(information);
}
public void addRecommendation(String recommendation) {
if (recommendations.length() > 0) recommendations.append("\n");
recommendations.append(recommendation);
}
public boolean hasErrors() {
return errors.length() > 0;
}
public String getErrors() {
return errors.toString();
}
public String getWarnings() {
return warnings.toString();
}
public String getInfo() {
return info.toString();
}
public String getRecommendations() {
return recommendations.toString();
}
public String getFullReport() {
StringBuilder report = new StringBuilder();
report.append("=== 微信支付证书诊断报告 ===\n\n");
if (info.length() > 0) {
report.append("📋 基本信息:\n").append(info).append("\n\n");
}
if (warnings.length() > 0) {
report.append("⚠️ 警告:\n").append(warnings).append("\n\n");
}
if (errors.length() > 0) {
report.append("❌ 错误:\n").append(errors).append("\n\n");
}
if (recommendations.length() > 0) {
report.append("💡 建议:\n").append(recommendations).append("\n\n");
}
report.append("=== 诊断报告结束 ===");
return report.toString();
}
}
}

View File

@@ -0,0 +1,312 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
/**
* 微信支付证书修复工具
* 自动检测和修复常见的证书配置问题
*
* @author 科技小王子
* @since 2025-07-29
*/
@Slf4j
@Component
public class WechatPayCertificateFixer {
private final CertificateProperties certConfig;
private final CertificateLoader certificateLoader;
public WechatPayCertificateFixer(CertificateProperties certConfig, CertificateLoader certificateLoader) {
this.certConfig = certConfig;
this.certificateLoader = certificateLoader;
}
/**
* 自动修复证书配置问题
*
* @param payment 支付配置
* @param tenantId 租户ID
* @param environment 环境
* @return 修复结果
*/
public FixResult autoFixCertificateIssues(Payment payment, Integer tenantId, String environment) {
FixResult result = new FixResult();
log.info("开始自动修复租户 {} 的证书配置问题", tenantId);
try {
// 1. 检查并修复基本配置
fixBasicConfiguration(payment, result);
// 2. 检查并修复证书文件问题
fixCertificateFiles(payment, tenantId, environment, result);
// 3. 检查并修复序列号问题
fixSerialNumberIssues(payment, tenantId, environment, result);
// 4. 生成修复建议
generateFixRecommendations(result);
} catch (Exception e) {
result.addError("修复过程中发生异常: " + e.getMessage());
log.error("证书修复异常", e);
}
log.info("证书配置修复完成,成功修复 {} 个问题", result.getFixedIssues().size());
return result;
}
/**
* 修复基本配置问题
*/
private void fixBasicConfiguration(Payment payment, FixResult result) {
if (payment == null) {
result.addError("支付配置为空,无法修复");
return;
}
// 检查商户号
if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
result.addError("商户号未配置,需要手动设置");
}
// 检查应用ID
if (payment.getAppId() == null || payment.getAppId().trim().isEmpty()) {
result.addError("应用ID未配置需要手动设置");
}
// 检查APIv3密钥
if (payment.getApiKey() == null || payment.getApiKey().trim().isEmpty()) {
result.addWarning("APIv3密钥未配置将使用配置文件默认值");
} else if (payment.getApiKey().length() != 32) {
result.addError("APIv3密钥长度错误应为32位实际为: " + payment.getApiKey().length());
}
// 检查商户证书序列号
if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
result.addError("商户证书序列号未配置,需要手动设置");
}
}
/**
* 修复证书文件问题
*/
private void fixCertificateFiles(Payment payment, Integer tenantId, String environment, FixResult result) {
if ("dev".equals(environment)) {
fixDevCertificateFiles(tenantId, result);
} else {
fixProdCertificateFiles(payment, result);
}
}
/**
* 修复开发环境证书文件问题
*/
private void fixDevCertificateFiles(Integer tenantId, FixResult result) {
String tenantCertPath = "dev/wechat/" + tenantId;
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
String apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
// 检查私钥文件
if (!certificateLoader.certificateExists(privateKeyPath)) {
result.addError("私钥文件不存在: " + privateKeyPath);
result.addRecommendation("请将 apiclient_key.pem 文件放置到 src/main/resources/" + privateKeyPath);
} else {
result.addFixed("私钥文件存在: " + privateKeyPath);
// 尝试加载私钥文件
try {
String privateKeyFile = certificateLoader.loadCertificatePath(privateKeyPath);
result.addFixed("私钥文件加载成功: " + privateKeyFile);
} catch (Exception e) {
result.addError("私钥文件加载失败: " + e.getMessage());
}
}
// 检查商户证书文件(可选)
if (!certificateLoader.certificateExists(apiclientCertPath)) {
result.addWarning("商户证书文件不存在: " + apiclientCertPath + " (自动证书配置不需要此文件)");
} else {
result.addFixed("商户证书文件存在: " + apiclientCertPath);
}
}
/**
* 修复生产环境证书文件问题
*/
private void fixProdCertificateFiles(Payment payment, FixResult result) {
if (payment.getApiclientKey() == null || payment.getApiclientKey().trim().isEmpty()) {
result.addError("生产环境私钥文件路径未配置");
} else {
result.addFixed("生产环境私钥文件路径已配置: " + payment.getApiclientKey());
}
if (payment.getApiclientCert() == null || payment.getApiclientCert().trim().isEmpty()) {
result.addWarning("生产环境商户证书文件路径未配置 (自动证书配置不需要此文件)");
} else {
result.addFixed("生产环境商户证书文件路径已配置: " + payment.getApiclientCert());
}
}
/**
* 修复序列号问题
*/
private void fixSerialNumberIssues(Payment payment, Integer tenantId, String environment, FixResult result) {
if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
result.addError("商户证书序列号未配置");
return;
}
// 在开发环境中,尝试从证书文件中提取序列号进行验证
if ("dev".equals(environment)) {
try {
String tenantCertPath = "dev/wechat/" + tenantId;
String apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
if (certificateLoader.certificateExists(apiclientCertPath)) {
String actualCertPath = certificateLoader.loadCertificatePath(apiclientCertPath);
try (InputStream inputStream = new FileInputStream(new File(actualCertPath))) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
if (cert != null) {
String actualSerialNumber = cert.getSerialNumber().toString(16).toUpperCase();
String configuredSerialNumber = payment.getMerchantSerialNumber();
if (!configuredSerialNumber.equalsIgnoreCase(actualSerialNumber)) {
result.addError("证书序列号不匹配! 配置: " + configuredSerialNumber + ", 实际: " + actualSerialNumber);
result.addRecommendation("建议将商户证书序列号更新为: " + actualSerialNumber);
} else {
result.addFixed("证书序列号匹配: " + actualSerialNumber);
}
}
}
}
} catch (Exception e) {
result.addWarning("无法验证证书序列号: " + e.getMessage());
}
}
}
/**
* 生成修复建议
*/
private void generateFixRecommendations(FixResult result) {
if (result.hasErrors()) {
result.addRecommendation("=== 修复建议 ===");
if (result.getErrors().stream().anyMatch(e -> e.contains("商户号"))) {
result.addRecommendation("1. 请在微信商户平台获取商户号并在系统中配置");
}
if (result.getErrors().stream().anyMatch(e -> e.contains("应用ID"))) {
result.addRecommendation("2. 请在微信开放平台获取应用ID并在系统中配置");
}
if (result.getErrors().stream().anyMatch(e -> e.contains("APIv3密钥"))) {
result.addRecommendation("3. 请在微信商户平台设置32位APIv3密钥");
}
if (result.getErrors().stream().anyMatch(e -> e.contains("证书序列号"))) {
result.addRecommendation("4. 请在微信商户平台查看正确的商户证书序列号");
}
if (result.getErrors().stream().anyMatch(e -> e.contains("私钥文件"))) {
result.addRecommendation("5. 请从微信商户平台下载私钥文件并放置到正确位置");
}
result.addRecommendation("6. 建议使用RSAAutoCertificateConfig自动证书配置");
result.addRecommendation("7. 确保在微信商户平台开启API安全功能");
}
}
/**
* 修复结果类
*/
public static class FixResult {
private final List<String> errors = new ArrayList<>();
private final List<String> warnings = new ArrayList<>();
private final List<String> fixedIssues = new ArrayList<>();
private final List<String> recommendations = new ArrayList<>();
public void addError(String error) {
errors.add(error);
}
public void addWarning(String warning) {
warnings.add(warning);
}
public void addFixed(String fixed) {
fixedIssues.add(fixed);
}
public void addRecommendation(String recommendation) {
recommendations.add(recommendation);
}
public boolean hasErrors() {
return !errors.isEmpty();
}
public List<String> getErrors() {
return errors;
}
public List<String> getWarnings() {
return warnings;
}
public List<String> getFixedIssues() {
return fixedIssues;
}
public List<String> getRecommendations() {
return recommendations;
}
public String getFullReport() {
StringBuilder report = new StringBuilder();
report.append("=== 微信支付证书修复报告 ===\n\n");
if (!fixedIssues.isEmpty()) {
report.append("✅ 已修复的问题:\n");
fixedIssues.forEach(issue -> report.append(" - ").append(issue).append("\n"));
report.append("\n");
}
if (!warnings.isEmpty()) {
report.append("⚠️ 警告:\n");
warnings.forEach(warning -> report.append(" - ").append(warning).append("\n"));
report.append("\n");
}
if (!errors.isEmpty()) {
report.append("❌ 需要手动修复的问题:\n");
errors.forEach(error -> report.append(" - ").append(error).append("\n"));
report.append("\n");
}
if (!recommendations.isEmpty()) {
report.append("💡 修复建议:\n");
recommendations.forEach(rec -> report.append(" ").append(rec).append("\n"));
report.append("\n");
}
report.append("=== 修复报告结束 ===");
return report.toString();
}
}
}

View File

@@ -0,0 +1,243 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.core.service.PaymentCacheService;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 微信支付配置检查器
* 用于快速检查和验证微信支付配置状态
*
* @author 科技小王子
* @since 2025-07-29
*/
@Slf4j
@Component
public class WechatPayConfigChecker {
@Autowired
private PaymentCacheService paymentCacheService;
@Autowired
private CertificateLoader certificateLoader;
@Autowired
private CertificateProperties certConfig;
@Value("${spring.profiles.active:dev}")
private String activeProfile;
/**
* 检查租户的微信支付配置状态
*
* @param tenantId 租户ID
* @return 配置状态报告
*/
public ConfigStatus checkTenantConfig(Integer tenantId) {
ConfigStatus status = new ConfigStatus();
status.tenantId = tenantId;
status.environment = activeProfile;
try {
// 获取支付配置
Payment payment = paymentCacheService.getWechatPayConfig(tenantId);
if (payment == null) {
status.hasError = true;
status.errorMessage = "支付配置不存在";
return status;
}
status.merchantId = payment.getMchId();
status.appId = payment.getAppId();
status.serialNumber = payment.getMerchantSerialNumber();
status.hasApiKey = payment.getApiKey() != null && !payment.getApiKey().isEmpty();
status.apiKeyLength = payment.getApiKey() != null ? payment.getApiKey().length() : 0;
// 检查公钥配置
if (payment.getPubKey() != null && !payment.getPubKey().isEmpty() &&
payment.getPubKeyId() != null && !payment.getPubKeyId().isEmpty()) {
status.hasPublicKey = true;
status.publicKeyFile = payment.getPubKey();
status.publicKeyId = payment.getPubKeyId();
status.configMode = "公钥模式";
// 检查公钥文件是否存在
String tenantCertPath = "dev/wechat/" + tenantId;
String pubKeyPath = tenantCertPath + "/" + payment.getPubKey();
status.publicKeyExists = certificateLoader.certificateExists(pubKeyPath);
} else {
status.hasPublicKey = false;
status.configMode = "自动证书模式";
}
// 检查私钥文件
String tenantCertPath = "dev/wechat/" + tenantId;
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
status.privateKeyExists = certificateLoader.certificateExists(privateKeyPath);
// 检查商户证书文件
String apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
status.merchantCertExists = certificateLoader.certificateExists(apiclientCertPath);
// 评估配置完整性
evaluateConfigCompleteness(status);
} catch (Exception e) {
status.hasError = true;
status.errorMessage = "检查配置时发生异常: " + e.getMessage();
log.error("检查租户 {} 配置时发生异常", tenantId, e);
}
return status;
}
/**
* 评估配置完整性
*/
private void evaluateConfigCompleteness(ConfigStatus status) {
if (status.hasError) {
return;
}
// 基本配置检查
if (status.merchantId == null || status.merchantId.isEmpty()) {
status.addIssue("商户号未配置");
}
if (status.appId == null || status.appId.isEmpty()) {
status.addIssue("应用ID未配置");
}
if (status.serialNumber == null || status.serialNumber.isEmpty()) {
status.addIssue("商户证书序列号未配置");
}
if (!status.hasApiKey) {
status.addIssue("APIv3密钥未配置");
} else if (status.apiKeyLength != 32) {
status.addIssue("APIv3密钥长度错误应为32位实际为" + status.apiKeyLength + "");
}
if (!status.privateKeyExists) {
status.addIssue("私钥文件不存在");
}
// 公钥模式特定检查
if (status.hasPublicKey) {
if (!status.publicKeyExists) {
status.addIssue("公钥文件不存在");
}
}
// 设置配置状态
if (status.issues.isEmpty()) {
status.configComplete = true;
status.recommendation = "✅ 配置完整,建议使用当前配置";
} else {
status.configComplete = false;
if (status.hasPublicKey) {
status.recommendation = "⚠️ 公钥配置不完整,建议修复问题或回退到自动证书模式";
} else {
status.recommendation = "⚠️ 自动证书配置不完整,建议配置公钥模式或修复当前问题";
}
}
}
/**
* 生成配置建议
*/
public String generateConfigAdvice(Integer tenantId) {
ConfigStatus status = checkTenantConfig(tenantId);
StringBuilder advice = new StringBuilder();
advice.append("=== 租户 ").append(tenantId).append(" 微信支付配置建议 ===\n\n");
advice.append("当前配置模式: ").append(status.configMode).append("\n");
advice.append("配置完整性: ").append(status.configComplete ? "完整" : "不完整").append("\n\n");
if (status.hasError) {
advice.append("❌ 错误: ").append(status.errorMessage).append("\n\n");
return advice.toString();
}
// 基本信息
advice.append("📋 基本信息:\n");
advice.append(" 商户号: ").append(status.merchantId).append("\n");
advice.append(" 应用ID: ").append(status.appId).append("\n");
advice.append(" 序列号: ").append(status.serialNumber).append("\n");
advice.append(" API密钥: ").append(status.hasApiKey ? "已配置(" + status.apiKeyLength + "位)" : "未配置").append("\n\n");
// 证书文件状态
advice.append("📁 证书文件状态:\n");
advice.append(" 私钥文件: ").append(status.privateKeyExists ? "✅ 存在" : "❌ 不存在").append("\n");
advice.append(" 商户证书: ").append(status.merchantCertExists ? "✅ 存在" : "⚠️ 不存在").append("\n");
if (status.hasPublicKey) {
advice.append(" 公钥文件: ").append(status.publicKeyExists ? "✅ 存在" : "❌ 不存在").append("\n");
advice.append(" 公钥ID: ").append(status.publicKeyId).append("\n");
}
advice.append("\n");
// 问题列表
if (!status.issues.isEmpty()) {
advice.append("⚠️ 发现的问题:\n");
for (String issue : status.issues) {
advice.append(" - ").append(issue).append("\n");
}
advice.append("\n");
}
// 建议
advice.append("💡 建议:\n");
advice.append(" ").append(status.recommendation).append("\n\n");
if (!status.hasPublicKey) {
advice.append("🔧 配置公钥模式的步骤:\n");
advice.append(" 1. 获取微信支付平台公钥文件和公钥ID\n");
advice.append(" 2. 将公钥文件放置到: src/main/resources/dev/wechat/").append(tenantId).append("/\n");
advice.append(" 3. 执行SQL更新数据库配置:\n");
advice.append(" UPDATE sys_payment SET \n");
advice.append(" pub_key = 'wechatpay_public_key.pem',\n");
advice.append(" pub_key_id = 'YOUR_PUBLIC_KEY_ID'\n");
advice.append(" WHERE tenant_id = ").append(tenantId).append(" AND type = 0;\n\n");
}
advice.append("=== 配置建议结束 ===");
return advice.toString();
}
/**
* 配置状态类
*/
public static class ConfigStatus {
public Integer tenantId;
public String environment;
public String merchantId;
public String appId;
public String serialNumber;
public boolean hasApiKey;
public int apiKeyLength;
public boolean hasPublicKey;
public String publicKeyFile;
public String publicKeyId;
public boolean publicKeyExists;
public boolean privateKeyExists;
public boolean merchantCertExists;
public String configMode;
public boolean configComplete;
public boolean hasError;
public String errorMessage;
public String recommendation;
public java.util.List<String> issues = new java.util.ArrayList<>();
public void addIssue(String issue) {
issues.add(issue);
}
}
}

View File

@@ -0,0 +1,223 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* 微信支付配置验证工具
*
* @author 科技小王子
* @since 2025-07-27
*/
@Slf4j
@Component
public class WechatPayConfigValidator {
private final CertificateProperties certConfig;
private final CertificateLoader certificateLoader;
@Value("${spring.profiles.active}")
private String activeProfile;
public WechatPayConfigValidator(CertificateProperties certConfig, CertificateLoader certificateLoader) {
this.certConfig = certConfig;
this.certificateLoader = certificateLoader;
}
/**
* 验证微信支付配置
*
* @param payment 支付配置
* @param tenantId 租户ID
* @return 验证结果
*/
public ValidationResult validateWechatPayConfig(Payment payment, Integer tenantId) {
ValidationResult result = new ValidationResult();
log.info("开始验证微信支付配置 - 租户ID: {}", tenantId);
// 1. 验证基本配置
if (payment == null) {
result.addError("支付配置为空");
return result;
}
if (!StringUtils.hasText(payment.getMchId())) {
result.addError("商户号未配置");
}
if (!StringUtils.hasText(payment.getAppId())) {
result.addError("应用ID未配置");
}
if (!StringUtils.hasText(payment.getMerchantSerialNumber())) {
result.addError("商户证书序列号未配置");
}
// 2. 验证 APIv3 密钥
String apiV3Key = getValidApiV3Key(payment);
if (!StringUtils.hasText(apiV3Key)) {
result.addError("APIv3密钥未配置");
} else {
validateApiV3Key(apiV3Key, result);
}
// 3. 验证证书文件
validateCertificateFiles(tenantId, result);
// 4. 记录验证结果
if (result.isValid()) {
log.info("✅ 微信支付配置验证通过 - 租户ID: {}", tenantId);
} else {
log.error("❌ 微信支付配置验证失败 - 租户ID: {}, 错误: {}", tenantId, result.getErrors());
}
return result;
}
/**
* 获取有效的 APIv3 密钥
* 优先使用数据库配置,如果为空则使用配置文件默认值
*/
public String getValidApiV3Key(Payment payment) {
String apiV3Key = payment.getApiKey();
if (!StringUtils.hasText(apiV3Key)) {
apiV3Key = certConfig.getWechatPay().getDev().getApiV3Key();
log.warn("数据库中APIv3密钥为空使用配置文件默认值");
}
return apiV3Key;
}
/**
* 验证 APIv3 密钥格式
*/
private void validateApiV3Key(String apiV3Key, ValidationResult result) {
if (apiV3Key.length() != 32) {
result.addError("APIv3密钥长度错误应为32位实际为: " + apiV3Key.length());
}
if (!apiV3Key.matches("^[a-zA-Z0-9]+$")) {
result.addError("APIv3密钥格式错误应仅包含字母和数字");
}
log.info("APIv3密钥验证 - 长度: {}, 格式: {}",
apiV3Key.length(),
apiV3Key.matches("^[a-zA-Z0-9]+$") ? "正确" : "错误");
}
/**
* 验证证书文件
*/
private void validateCertificateFiles(Integer tenantId, ValidationResult result) {
if ("dev".equals(activeProfile)) {
// 开发环境证书验证
String tenantCertPath = "dev/wechat/" + tenantId;
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
if (!certificateLoader.certificateExists(privateKeyPath)) {
result.addError("证书文件不存在: " + privateKeyPath);
return;
}
try {
certificateLoader.loadCertificatePath(privateKeyPath);
log.info("✅ 开发环境证书文件验证通过: {}", privateKeyPath);
} catch (Exception e) {
result.addError("证书文件加载失败: " + e.getMessage());
}
} else {
// 生产环境证书验证 - 跳过文件存在性检查,因为证书路径来自数据库
log.info("✅ 生产环境跳过证书文件存在性验证,使用数据库配置的证书路径");
}
}
/**
* 验证结果类
*/
public static class ValidationResult {
private boolean valid = true;
private StringBuilder errors = new StringBuilder();
public void addError(String error) {
this.valid = false;
if (errors.length() > 0) {
errors.append("; ");
}
errors.append(error);
}
public boolean isValid() {
return valid;
}
public String getErrors() {
return errors.toString();
}
public void logErrors() {
if (!valid) {
log.error("配置验证失败: {}", errors.toString());
}
}
}
/**
* 生成配置诊断报告
*/
public String generateDiagnosticReport(Payment payment, Integer tenantId) {
StringBuilder report = new StringBuilder();
report.append("=== 微信支付配置诊断报告 ===\n");
report.append("租户ID: ").append(tenantId).append("\n");
if (payment != null) {
report.append("商户号: ").append(payment.getMchId()).append("\n");
report.append("应用ID: ").append(payment.getAppId()).append("\n");
report.append("商户证书序列号: ").append(payment.getMerchantSerialNumber()).append("\n");
String dbApiKey = payment.getApiKey();
String configApiKey = certConfig.getWechatPay().getDev().getApiV3Key();
report.append("数据库APIv3密钥: ").append(dbApiKey != null ? "已配置(" + dbApiKey.length() + "位)" : "未配置").append("\n");
report.append("配置文件APIv3密钥: ").append(configApiKey != null ? "已配置(" + configApiKey.length() + "位)" : "未配置").append("\n");
String finalApiKey = getValidApiV3Key(payment);
report.append("最终使用APIv3密钥: ").append(finalApiKey != null ? "已配置(" + finalApiKey.length() + "位)" : "未配置").append("\n");
} else {
report.append("❌ 支付配置为空\n");
}
// 证书文件检查
report.append("当前环境: ").append(activeProfile).append("\n");
if ("dev".equals(activeProfile)) {
String tenantCertPath = "dev/wechat/" + tenantId;
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
boolean certExists = certificateLoader.certificateExists(privateKeyPath);
report.append("开发环境证书文件路径: ").append(privateKeyPath).append("\n");
report.append("证书文件存在: ").append(certExists ? "" : "").append("\n");
} else {
report.append("生产环境证书路径: 从数据库配置获取\n");
if (payment != null) {
report.append("私钥文件: ").append(payment.getApiclientKey()).append("\n");
report.append("证书文件: ").append(payment.getApiclientCert()).append("\n");
}
}
ValidationResult validation = validateWechatPayConfig(payment, tenantId);
report.append("配置验证结果: ").append(validation.isValid() ? "通过" : "失败").append("\n");
if (!validation.isValid()) {
report.append("验证错误: ").append(validation.getErrors()).append("\n");
}
report.append("=== 诊断报告结束 ===");
return report.toString();
}
}

View File

@@ -0,0 +1,222 @@
package com.gxwebsoft.common.core.utils;
import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* 微信支付配置诊断工具
* 用于排查微信支付签名验证失败等问题
*
* @author 科技小王子
* @since 2025-07-27
*/
@Slf4j
@Component
public class WechatPayDiagnostic {
/**
* 诊断微信支付配置
*
* @param payment 支付配置
* @param privateKeyPath 私钥路径
* @param environment 环境标识
*/
public void diagnosePaymentConfig(Payment payment, String privateKeyPath, String environment) {
log.info("=== 微信支付配置诊断开始 ===");
log.info("环境: {}", environment);
// 1. 检查支付配置基本信息
checkBasicConfig(payment);
// 2. 检查证书文件
checkCertificateFiles(payment, privateKeyPath, environment);
// 3. 检查配置完整性
checkConfigCompleteness(payment);
log.info("=== 微信支付配置诊断结束 ===");
}
/**
* 检查基本配置信息
*/
private void checkBasicConfig(Payment payment) {
log.info("--- 基本配置检查 ---");
if (payment == null) {
log.error("❌ 支付配置为空");
return;
}
log.info("支付配置ID: {}", payment.getId());
log.info("支付方式名称: {}", payment.getName());
log.info("支付类型: {}", payment.getType());
log.info("支付代码: {}", payment.getCode());
log.info("状态: {}", payment.getStatus());
// 检查关键字段
checkField("应用ID", payment.getAppId());
checkField("商户号", payment.getMchId());
checkField("商户证书序列号", payment.getMerchantSerialNumber());
checkField("API密钥", payment.getApiKey(), true);
}
/**
* 检查证书文件
*/
private void checkCertificateFiles(Payment payment, String privateKeyPath, String environment) {
log.info("--- 证书文件检查 ---");
// 检查私钥文件
if (privateKeyPath != null) {
checkFileExists("私钥文件", privateKeyPath);
}
// 生产环境检查证书文件
if (!"dev".equals(environment)) {
if (payment.getApiclientCert() != null) {
log.info("商户证书文件配置: {}", payment.getApiclientCert());
}
if (payment.getPubKey() != null) {
log.info("公钥文件配置: {}", payment.getPubKey());
log.info("公钥ID: {}", payment.getPubKeyId());
}
}
}
/**
* 检查配置完整性
*/
private void checkConfigCompleteness(Payment payment) {
log.info("--- 配置完整性检查 ---");
boolean isComplete = true;
if (isEmpty(payment.getMchId())) {
log.error("❌ 商户号未配置");
isComplete = false;
}
if (isEmpty(payment.getMerchantSerialNumber())) {
log.error("❌ 商户证书序列号未配置");
isComplete = false;
}
if (isEmpty(payment.getApiKey())) {
log.error("❌ API密钥未配置");
isComplete = false;
}
if (isEmpty(payment.getAppId())) {
log.error("❌ 应用ID未配置");
isComplete = false;
}
if (isComplete) {
log.info("✅ 配置完整性检查通过");
} else {
log.error("❌ 配置不完整,请补充缺失的配置项");
}
}
/**
* 检查字段是否为空
*/
private void checkField(String fieldName, String value) {
checkField(fieldName, value, false);
}
/**
* 检查字段是否为空
*/
private void checkField(String fieldName, String value, boolean isSensitive) {
if (isEmpty(value)) {
log.warn("⚠️ {}: 未配置", fieldName);
} else {
if (isSensitive) {
log.info("✅ {}: 已配置(长度:{})", fieldName, value.length());
} else {
log.info("✅ {}: {}", fieldName, value);
}
}
}
/**
* 检查文件是否存在
*/
private void checkFileExists(String fileName, String filePath) {
try {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
log.info("✅ {}: 文件存在 - {}", fileName, filePath);
log.info(" 文件大小: {} bytes", file.length());
// 检查文件内容格式
if (filePath.endsWith(".pem")) {
checkPemFileFormat(fileName, filePath);
}
} else {
log.error("❌ {}: 文件不存在 - {}", fileName, filePath);
}
} catch (Exception e) {
log.error("❌ {}: 检查文件时出错 - {} ({})", fileName, filePath, e.getMessage());
}
}
/**
* 检查PEM文件格式
*/
private void checkPemFileFormat(String fileName, String filePath) {
try {
String content = Files.readString(Paths.get(filePath));
if (content.contains("-----BEGIN") && content.contains("-----END")) {
log.info("✅ {}: PEM格式正确", fileName);
} else {
log.warn("⚠️ {}: PEM格式可能有问题", fileName);
}
} catch (Exception e) {
log.warn("⚠️ {}: 无法读取文件内容进行格式检查 ({})", fileName, e.getMessage());
}
}
/**
* 检查字符串是否为空
*/
private boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
/**
* 生成诊断报告
*/
public String generateDiagnosticReport(Payment payment, String environment) {
StringBuilder report = new StringBuilder();
report.append("🔍 微信支付配置诊断报告\n");
report.append("========================\n\n");
report.append("环境: ").append(environment).append("\n");
report.append("租户ID: ").append(payment != null ? payment.getTenantId() : "未知").append("\n");
report.append("商户号: ").append(payment != null ? payment.getMchId() : "未配置").append("\n");
report.append("应用ID: ").append(payment != null ? payment.getAppId() : "未配置").append("\n\n");
report.append("🚨 常见问题排查:\n");
report.append("1. 商户证书序列号是否正确\n");
report.append("2. APIv3密钥是否正确\n");
report.append("3. 私钥文件是否正确\n");
report.append("4. 微信支付平台证书是否过期\n");
report.append("5. 网络连接是否正常\n\n");
report.append("💡 建议解决方案:\n");
report.append("1. 使用自动证书配置(RSAAutoCertificateConfig)\n");
report.append("2. 在微信商户平台重新下载证书\n");
report.append("3. 检查商户平台API安全设置\n");
return report.toString();
}
}

View File

@@ -0,0 +1,111 @@
package com.gxwebsoft.common.core.utils;
import java.nio.charset.StandardCharsets;
/**
* 微信支付工具类
* 处理微信支付API的字段限制和格式要求
*
* @author 科技小王子
* @since 2025-01-11
*/
public class WechatPayUtils {
/**
* 微信支付description字段的最大字节数限制
*/
public static final int DESCRIPTION_MAX_BYTES = 127;
/**
* 微信支付attach字段的最大字节数限制
*/
public static final int ATTACH_MAX_BYTES = 127;
/**
* 截断字符串以确保字节数不超过指定限制
* 主要用于微信支付API的字段限制处理
*
* @param text 原始文本
* @param maxBytes 最大字节数
* @return 截断后的文本确保UTF-8字符完整性
*/
public static String truncateToByteLimit(String text, int maxBytes) {
if (text == null || text.isEmpty()) {
return text;
}
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
if (bytes.length <= maxBytes) {
return text;
}
// 截断字节数组但要确保不会截断UTF-8字符的中间
int truncateLength = maxBytes;
while (truncateLength > 0) {
byte[] truncated = new byte[truncateLength];
System.arraycopy(bytes, 0, truncated, 0, truncateLength);
try {
String result = new String(truncated, StandardCharsets.UTF_8);
// 检查是否有无效字符被截断的UTF-8字符
if (!result.contains("\uFFFD")) {
return result;
}
} catch (Exception e) {
// 继续尝试更短的长度
}
truncateLength--;
}
return ""; // 如果无法安全截断,返回空字符串
}
/**
* 处理微信支付商品描述字段
* 确保字节数不超过127字节
*
* @param description 商品描述
* @return 处理后的描述,符合微信支付要求
*/
public static String processDescription(String description) {
return truncateToByteLimit(description, DESCRIPTION_MAX_BYTES);
}
/**
* 处理微信支付附加数据字段
* 确保字节数不超过127字节
*
* @param attach 附加数据
* @return 处理后的附加数据,符合微信支付要求
*/
public static String processAttach(String attach) {
return truncateToByteLimit(attach, ATTACH_MAX_BYTES);
}
/**
* 验证字符串是否符合微信支付字段的字节限制
*
* @param text 待验证的文本
* @param maxBytes 最大字节数限制
* @return true如果符合限制false如果超出限制
*/
public static boolean isWithinByteLimit(String text, int maxBytes) {
if (text == null) {
return true;
}
return text.getBytes(StandardCharsets.UTF_8).length <= maxBytes;
}
/**
* 获取字符串的UTF-8字节数
*
* @param text 文本
* @return 字节数
*/
public static int getByteLength(String text) {
if (text == null) {
return 0;
}
return text.getBytes(StandardCharsets.UTF_8).length;
}
}

View File

@@ -0,0 +1,20 @@
package com.gxwebsoft.common.core.utils;
import com.wechat.pay.java.core.Config;
import java.util.HashMap;
import java.util.Map;
public class WxNativeUtil {
private static final Map<Integer, Config> tenantConfigs = new HashMap<>();
public static void addConfig(Integer tenantId, Config config) {
tenantConfigs.put(tenantId, config);
}
public static Config getConfig(Integer tenantId) {
return tenantConfigs.get(tenantId);
}
}

View File

@@ -0,0 +1,106 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.system.service.SettingService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* 微信公众号工具类
* @author 科技小王子
*
*/
@Component
public class WxOfficialUtil {
private final StringRedisTemplate stringRedisTemplate;
private Integer tenantId;
public String appId;
public String appSecret;
public String openid;
public String unionid;
public String access_token;
public String expires_in;
public String nickname;
@Resource
private SettingService settingService;
@Resource
private ConfigProperties pathConfig;
@Resource
private CacheClient cacheClient;
public WxOfficialUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
// 实例化客户端
public WxOfficialUtil client(Integer tenantId) {
if(tenantId > 0){
throw new BusinessException(tenantId + "123123");
}
this.tenantId = tenantId;
this.config();
System.out.println("this.tenantId = " + this.tenantId);
return this;
}
// 开发者ID和秘钥
private void config() {
String key = "cache"+ this.tenantId +":setting:wx-official";
String wxOfficial = stringRedisTemplate.opsForValue().get(key);
JSONObject data = JSONObject.parseObject(wxOfficial);
if(data != null){
this.appId = data.getString("appId");
this.appSecret = data.getString("appSecret");
}
System.out.println("this.appId = " + this.appId);
System.out.println("this.appSecret = " + this.appSecret);
}
// 获取appId
public String getAppSecret(){
return this.appSecret;
}
public String getCodeUrl() throws UnsupportedEncodingException {
String encodedReturnUrl = URLEncoder.encode(pathConfig.getServerUrl() + "/open/wx-official/accessToken","UTF-8");
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ this.appId +"&redirect_uri=" + encodedReturnUrl + "&response_type=code&scope=snsapi_userinfo&state="+ this.tenantId +"#wechat_redirect";
}
// 获取access_token
public String getAccessToken(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ this.appId +"&secret="+ this.appSecret +"&code="+ code +"&grant_type=authorization_code";
System.out.println("url = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
final JSONObject jsonObject = JSONObject.parseObject(response);
access_token = jsonObject.getString("access_token");
if(access_token == null){
throw new BusinessException("获取access_token失败");
}
this.openid = jsonObject.getString("openid");
this.unionid = jsonObject.getString("unionid");
this.expires_in = jsonObject.getString("expires_in");
return access_token;
}
// 获取userinfo
public JSONObject getUserInfo(String access_token) {
String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +"&openid="+ this.openid +"&lang=zh_CN";
System.out.println("url2 = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
System.out.println("response = " + response);
if(response == null){
throw new BusinessException("获取userinfo失败");
}
return JSONObject.parseObject(response);
}
}

View File

@@ -0,0 +1,132 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.exception.BusinessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 微信小程序工具类
* @author 科技小王子
*
*/
@Component
public class WxUtil {
private final StringRedisTemplate stringRedisTemplate;
private Integer tenantId;
public String appId;
public String appSecret;
public String access_token;
public String expires_in;
public String nickname;
public String userid;
public String user_ticket;
public String openid;
public String external_userid;
public String name;
public String position;
public String mobile;
public String gender;
public String email;
public String avatar;
public String thumb_avatar;
public String telephone;
public String address;
public String alias;
public String qr_code;
public String open_userid;
@Resource
private CacheClient cacheClient;
public WxUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
// 实例化客户端
public WxUtil client(Integer tenantId) {
this.tenantId = tenantId;
this.config();
return this;
}
// 开发者ID和秘钥
private void config() {
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
if(settingInfo == null){
throw new BusinessException("微信小程序未配置");
}
this.appId = settingInfo.getString("corpId");
this.appSecret = settingInfo.getString("secret");
System.out.println("this.appId = " + this.appId);
System.out.println("this.appSecret = " + this.appSecret);
}
// 获取access_token
public void getAccessToken(String code) {
String key = "cache"+ this.tenantId +":ww:access_token";
final String access_token = stringRedisTemplate.opsForValue().get(key);
if(access_token != null){
this.getUserInfo(code,access_token);
}else {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
System.out.println("url = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
System.out.println("response = " + response);
final JSONObject jsonObject = JSONObject.parseObject(response);
// 获取成功
if(jsonObject.getString("access_token") != null){
this.access_token = jsonObject.getString("access_token");
this.expires_in = jsonObject.getString("expires_in");
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
System.out.println("获取access_token成功 = " + this.access_token);
this.getUserInfo(code,this.access_token);
}
}
}
// 获取userinfo
public void getUserInfo(String code, String access_token) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
System.out.println("url2 = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
JSONObject jsonObject = JSONObject.parseObject(response);
final String errcode = jsonObject.getString("errcode");
final String errmsg = jsonObject.getString("errmsg");
if(!StrUtil.equals(errcode,"0")){
throw new BusinessException(errmsg);
}
this.userid = jsonObject.getString("userid");
this.user_ticket = jsonObject.getString("user_ticket");
this.openid = jsonObject.getString("openid");
this.external_userid = jsonObject.getString("external_userid");
}
public void getUserProfile(String userid, String access_token) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
JSONObject jsonObject = JSONObject.parseObject(response);
this.name = jsonObject.getString("name");
this.position = jsonObject.getString("position");
this.gender = jsonObject.getString("gender");
this.email = jsonObject.getString("email");
this.avatar = jsonObject.getString("avatar");
this.thumb_avatar = jsonObject.getString("thumb_avatar");
this.telephone = jsonObject.getString("telephone");
this.address = jsonObject.getString("address");
this.alias = jsonObject.getString("alias");
this.qr_code = jsonObject.getString("qr_code");
this.open_userid = jsonObject.getString("open_userid");
}
}

View File

@@ -0,0 +1,134 @@
package com.gxwebsoft.common.core.utils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.exception.BusinessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 企业微信工具类
* @author 科技小王子
*
*/
@Component
public class WxWorkUtil {
private final StringRedisTemplate stringRedisTemplate;
private Integer tenantId;
public String appId;
public String appSecret;
public String access_token;
public String expires_in;
public String nickname;
public String userid;
public String user_ticket;
public String openid;
public String external_userid;
public String name;
public String position;
public String mobile;
public String gender;
public String email;
public String avatar;
public String thumb_avatar;
public String telephone;
public String address;
public String alias;
public String qr_code;
public String open_userid;
@Resource
private CacheClient cacheClient;
public WxWorkUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
// 实例化客户端
public WxWorkUtil client(Integer tenantId) {
this.tenantId = tenantId;
this.config();
return this;
}
// 开发者ID和秘钥
private void config() {
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
if(settingInfo == null){
throw new BusinessException("企业微信未配置");
}
this.appId = settingInfo.getString("corpId");
this.appSecret = settingInfo.getString("secret");
System.out.println("this.appId = " + this.appId);
System.out.println("this.appSecret = " + this.appSecret);
}
// 获取access_token
public void getAccessToken(String code) {
String key = "cache"+ this.tenantId +":ww:access_token";
final String access_token = stringRedisTemplate.opsForValue().get(key);
if(access_token != null){
this.getUserInfo(code,access_token);
}else {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
System.out.println("url = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
System.out.println("response = " + response);
final JSONObject jsonObject = JSONObject.parseObject(response);
// 获取成功
if(jsonObject.getString("access_token") != null){
this.access_token = jsonObject.getString("access_token");
this.expires_in = jsonObject.getString("expires_in");
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
System.out.println("获取access_token成功 = " + this.access_token);
this.getUserInfo(code,this.access_token);
}
}
}
// 获取userinfo
public void getUserInfo(String code, String access_token) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
System.out.println("url2 = " + url);
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
System.out.println("response = " + response);
JSONObject jsonObject = JSONObject.parseObject(response);
final String errcode = jsonObject.getString("errcode");
final String errmsg = jsonObject.getString("errmsg");
if(!StrUtil.equals(errcode,"0")){
throw new BusinessException(errmsg);
}
this.userid = jsonObject.getString("userid");
this.user_ticket = jsonObject.getString("user_ticket");
this.openid = jsonObject.getString("openid");
this.external_userid = jsonObject.getString("external_userid");
System.out.println("获取用户信息成功 = " + jsonObject);
}
public void getUserProfile(String userid, String access_token) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
System.out.println("response3 = " + response);
JSONObject jsonObject = JSONObject.parseObject(response);
System.out.println("读取用户详细信息 = " + jsonObject);
this.name = jsonObject.getString("name");
this.position = jsonObject.getString("position");
this.gender = jsonObject.getString("gender");
this.email = jsonObject.getString("email");
this.avatar = jsonObject.getString("avatar");
this.thumb_avatar = jsonObject.getString("thumb_avatar");
this.telephone = jsonObject.getString("telephone");
this.address = jsonObject.getString("address");
this.alias = jsonObject.getString("alias");
this.qr_code = jsonObject.getString("qr_code");
this.open_userid = jsonObject.getString("open_userid");
}
}

View File

@@ -0,0 +1,87 @@
package com.gxwebsoft.common.core.web;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
/**
* 返回结果
*
* @author WebSoft
* @since 2017-06-10 10:10:50
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "状态码")
private Integer code;
@Schema(description = "状态信息")
private String message;
@Schema(description = "返回数据")
private T data;
@Schema(description = "错误信息")
private String error;
public ApiResult() {}
public ApiResult(Integer code) {
this(code, null);
}
public ApiResult(Integer code, String message) {
this(code, message, null);
}
public ApiResult(Integer code, String message, T data) {
this(code, message, data, null);
}
public ApiResult(Integer code, String message, T data, String error) {
setCode(code);
setMessage(message);
setData(data);
setError(error);
}
public Integer getCode() {
return this.code;
}
public ApiResult<T> setCode(Integer code) {
this.code = code;
return this;
}
public String getMessage() {
return this.message;
}
public ApiResult<T> setMessage(String message) {
this.message = message;
return this;
}
public T getData() {
return this.data;
}
public ApiResult<T> setData(T data) {
this.data = data;
return this;
}
public String getError() {
return this.error;
}
public ApiResult<T> setError(String error) {
this.error = error;
return this;
}
}

View File

@@ -0,0 +1,333 @@
package com.gxwebsoft.common.core.web;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.utils.SignCheckUtil;
import com.gxwebsoft.common.system.entity.User;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Controller基类
*
* @author WebSoft
* @since 2017-06-10 10:10:19
*/
public class BaseController {
@Resource
private HttpServletRequest request;
@Resource
private RedisUtil redisUtil;
/**
* 获取当前登录的user
*
* @return User
*/
public User getLoginUser() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
return (User) object;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
/**
* 获取当前登录的userId
*
* @return userId
*/
public Integer getLoginUserId() {
User loginUser = getLoginUser();
return loginUser == null ? null : loginUser.getUserId();
}
/**
* 获取当前登录的tenantId
*
* @return tenantId
*/
public Integer getTenantId() {
String tenantId;
// 2 从请求头拿ID
tenantId = request.getHeader("tenantId");
if(StrUtil.isNotBlank(tenantId)){
return Integer.valueOf(tenantId);
}
// 3 从登录用户拿tenantId
User loginUser = getLoginUser();
if (loginUser != null) {
return loginUser.getTenantId();
}
// 1 从域名拿ID
String Domain = request.getHeader("Domain");
if (StrUtil.isNotBlank(Domain)) {
String key = "Domain:" + Domain;
tenantId = redisUtil.get(key);
if(tenantId != null){
System.out.println("从域名拿ID = " + tenantId);
return Integer.valueOf(tenantId);
}
}
return null;
}
/**
* 返回成功
*
* @return ApiResult
*/
public ApiResult<?> success() {
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG);
}
/**
* 返回成功
*
* @param message 状态信息
* @return ApiResult
*/
public ApiResult<?> success(String message) {
return success().setMessage(message);
}
/**
* 返回成功
*
* @param data 返回数据
* @return ApiResult
*/
public <T> ApiResult<T> success(T data) {
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG, data);
}
/**
* 返回成功
*
* @param message 状态信息
* @return ApiResult
*/
public <T> ApiResult<T> success(String message, T data) {
return success(data).setMessage(message);
}
/**
* 返回分页查询数据
*
* @param list 当前页数据
* @param count 总数量
* @return ApiResult
*/
public <T> ApiResult<PageResult<T>> success(List<T> list, Long count) {
return success(new PageResult<>(list, count));
}
/**
* 返回分页查询数据
*
* @param iPage IPage
* @return ApiResult
*/
public <T> ApiResult<PageResult<T>> success(IPage<T> iPage) {
return success(iPage.getRecords(), iPage.getTotal());
}
/**
* 返回失败
*
* @return ApiResult
*/
public ApiResult<?> fail() {
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG);
}
/**
* 返回失败
*
* @param message 状态信息
* @return ApiResult
*/
public ApiResult<?> fail(String message) {
return fail().setMessage(message);
}
/**
* 返回失败
*
* @param data 返回数据
* @return ApiResult
*/
public <T> ApiResult<T> fail(T data) {
return fail(Constants.RESULT_ERROR_MSG, data);
}
/**
* 返回失败
*
* @param message 状态信息
* @param data 返回数据
* @return ApiResult
*/
public <T> ApiResult<T> fail(String message, T data) {
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message, data);
}
/**
* 请求参数的空字符串转为null
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
// 自定义函数
public String getAuthorization(){
return request.getHeader("Authorization");
}
public String getAppId() {
// 兼容小写
if(request.getHeader("appid") != null){
return request.getHeader("appid");
}
return request.getHeader("AppId");
}
public String getSign() {
return request.getParameter("sign");
}
/**
* 是否校验签名信息
* 存在签名信息则需要验证
*/
public void isCheckSign() {
if (StrUtil.isNotBlank(getSign())) {
if(getTenantId() == null){
throw new BusinessException("签名失败:TenantId不能为空");
}
String timestamp1 = request.getParameter("timestamp");
long timestamp2 = System.currentTimeMillis();
long time = timestamp2 - Long.parseLong(timestamp1);
if(time > 600000L){
throw new BusinessException("签名失败:请求超时");
}
Enumeration<String> names = request.getParameterNames();
//2.遍历正文名称的枚举获得请求参数
Map<String, String> params = new HashMap<>();
while(names.hasMoreElements()){
String name = names.nextElement();
String value = request.getParameter(name);
params.put(name,value);
}
String signString = SignCheckUtil.getSignString(params, getAppSecret());
System.out.println("请求的参数 = " + params);
System.out.println("正确的签名 = " + signString);
System.out.println("签名是否正确 = " + SignCheckUtil.signCheck(params, getAppSecret()));
if (!SignCheckUtil.signCheck(params, getAppSecret())) {
throw new BusinessException("签名失败");
}
}
// 模拟提交参数
// String key = "FRbMx1FkG4Qz6GZxY";
// Map<String, String> param0 = new HashMap<>();
// param0.put("orderId", "D2018062976332656413");
// param0.put("MainAccountID", "DC3NHPJ73S");
// param0.put("MainAccountSN", "320");
// param0.put("payStatus", "2");
// param0.put("title","测试");
// System.out.println("请求的参数 = " + param0);
// String signString0 = SignCheckUtil.getSignString(param0, key);
// System.out.println("signString0 = " + signString0);
// return SignCheckUtil.signCheck(params, getAppSecret());
}
/**
* 获取当前请求租户的AppSecret
*
* @return AppSecret
*/
public String getAppSecret() {
String key = "cache5:AppSecret:" + Integer.valueOf(getAppId());
return redisUtil.get(key);
}
/**
* 根据账号|手机号码|邮箱查找用户ID
* @return userId
*/
// public Integer getUserIdByUsername(String username, Integer tenantId){
// // 按账号搜素
// User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username).eq(User::getTenantId,tenantId));
// if (user != null && user.getUserId() > 0) {
// return user.getUserId();
// }
// // 按手机号码搜索
// User userByPhone = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, username).eq(User::getTenantId, tenantId));
// if (userByPhone != null && userByPhone.getUserId() > 0) {
// return userByPhone.getUserId();
// }
// // 按邮箱搜索
// User userByEmail = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, username).eq(User::getTenantId, tenantId));
// if (userByEmail != null && userByEmail.getUserId() > 0) {
// return userByEmail.getUserId();
// }
// throw new BusinessException("找不到该用户");
// }
/**
* 处理方法参数类型转换异常
* 主要处理URL路径参数中传入"NaN"等无法转换为Integer的情况
*
* @param ex 方法参数类型不匹配异常
* @return ApiResult
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ApiResult<?> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex) {
String parameterName = ex.getName();
Object value = ex.getValue();
Class<?> requiredType = ex.getRequiredType();
// 记录错误日志
System.err.println("参数类型转换异常: 参数名=" + parameterName +
", 传入值=" + value +
", 期望类型=" + (requiredType != null ? requiredType.getSimpleName() : "unknown"));
// 如果是ID参数且传入的是"NaN",返回友好的错误信息
if ("id".equals(parameterName) && "NaN".equals(String.valueOf(value))) {
return fail("无效的ID参数请检查传入的ID值");
}
// 其他类型转换错误的通用处理
return fail("参数格式错误: " + parameterName + " 的值 '" + value + "' 无法转换为 " +
(requiredType != null ? requiredType.getSimpleName() : "目标类型"));
}
}

View File

@@ -0,0 +1,98 @@
package com.gxwebsoft.common.core.web;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.utils.CommonUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 查询参数基本字段
*
* @author WebSoft
* @since 2021-08-26 22:14:43
*/
@Data
public class BaseParam implements Serializable {
private static final long serialVersionUID = 1L;
@TableField(exist = false)
@Schema(description = "分页查询页码")
private Long page;
@TableField(exist = false)
@Schema(description = "分页查询每页数量")
private Long limit;
@TableField(exist = false)
@Schema(description = "国际化")
private String lang;
@TableField(exist = false)
@Schema(description = "排序字段", example = "id asc, name desc")
private String sort;
@TableField(exist = false)
@Schema(description = "排序方式", example = "asc或desc")
private String order;
@QueryField(value = "create_time", type = QueryType.GE)
@TableField(exist = false)
@Schema(description = "创建时间起始值")
private String createTimeStart;
@QueryField(value = "create_time", type = QueryType.LE)
@TableField(exist = false)
@Schema(description = "创建时间结束值")
private String createTimeEnd;
@QueryField(value = "create_time", type = QueryType.GE)
@Schema(description = "搜索场景")
@TableField(exist = false)
private String sceneType;
@Schema(description = "模糊搜素")
@TableField(exist = false)
private String keywords;
@Schema(description = "token")
@TableField(exist = false)
private String token;
@Schema(description = "租户ID")
@TableField(exist = false)
private Integer tenantId;
@Schema(description = "商户ID")
@TableField(exist = false)
private Long merchantId;
/**
* 获取集合中的第一条数据
*
* @param records 集合
* @return 第一条数据
*/
public <T> T getOne(List<T> records) {
return CommonUtil.listGetOne(records);
}
/**
* 国际化参数
*/
public String getLang(){
if(StrUtil.isBlank(this.lang)){
return null;
}
if(this.lang.equals("zh")){
return "zh_CN";
}
return this.lang;
}
}

View File

@@ -0,0 +1,57 @@
package com.gxwebsoft.common.core.web;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 批量修改通用参数
*
* @author WebSoft
* @since 2020-03-13 00:11:06
*/
@Data
public class BatchParam<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "需要修改的数据id集合")
private List<Serializable> ids;
@Schema(description = "需要修改的字段和值")
private T data;
/**
* 通用批量修改方法
*
* @param service IService
* @param idField id字段名称
* @return boolean
*/
public boolean update(IService<T> service, String idField) {
if (this.data == null) {
return false;
}
return service.update(this.data, new UpdateWrapper<T>().in(idField, this.ids));
}
/**
* 通用批量修改方法
*
* @param service IService
* @param idField id字段名称
* @return boolean
*/
public boolean update(IService<T> service, SFunction<T, ?> idField) {
if (this.data == null) {
return false;
}
return service.update(this.data, new LambdaUpdateWrapper<T>().in(idField, this.ids));
}
}

View File

@@ -0,0 +1,96 @@
package com.gxwebsoft.common.core.web;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 检查是否存在通用参数
*
* @author WebSoft
* @since 2021-09-07 22:24:39
*/
@Data
public class ExistenceParam<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "检查的字段")
private String field;
@Schema(description = "字段的值")
private String value;
@Schema(description = "修改时的主键")
private Integer id;
/**
* 检查是否存在
*
* @param service IService
* @param idField 修改时的主键字段
* @return boolean
*/
public boolean isExistence(IService<T> service, String idField) {
return isExistence(service, idField, true);
}
/**
* 检查是否存在
*
* @param service IService
* @param idField 修改时的主键字段
* @param isToUnderlineCase 是否需要把field转为下划线格式
* @return boolean
*/
public boolean isExistence(IService<T> service, String idField, boolean isToUnderlineCase) {
if (StrUtil.hasBlank(this.field, this.value)) {
return false;
}
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
QueryWrapper<T> wrapper = new QueryWrapper<>();
wrapper.eq(fieldName, value);
if (id != null) {
wrapper.ne(idField, id);
}
return service.count(wrapper) > 0;
}
/**
* 检查是否存在
*
* @param service IService
* @param idField 修改时的主键字段
* @return boolean
*/
public boolean isExistence(IService<T> service, SFunction<T, ?> idField) {
return isExistence(service, idField, true);
}
/**
* 检查是否存在
*
* @param service IService
* @param idField 修改时的主键字段
* @param isToUnderlineCase 是否需要把field转为下划线格式
* @return boolean
*/
public boolean isExistence(IService<T> service, SFunction<T, ?> idField, boolean isToUnderlineCase) {
if (StrUtil.hasBlank(this.field, this.value)) {
return false;
}
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
wrapper.apply(fieldName + " = {0}", value);
if (id != null) {
wrapper.ne(idField, id);
}
return service.count(wrapper) > 0;
}
}

View File

@@ -0,0 +1,343 @@
package com.gxwebsoft.common.core.web;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxwebsoft.common.core.Constants;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.utils.CommonUtil;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 分页、排序、搜索参数封装
*
* @author WebSoft
* @since 2019-04-26 10:34:35
*/
public class PageParam<T, U extends BaseParam> extends Page<T> {
private static final long serialVersionUID = 1L;
/**
* 租户id字段名称
*/
private static final String TENANT_ID_FIELD = "tenantId";
/**
* 查询条件
*/
private final U where;
/**
* 是否把字段名称驼峰转下划线
*/
private final boolean isToUnderlineCase;
public PageParam() {
this(null);
}
public PageParam(U where) {
this(where, true);
}
public PageParam(U where, boolean isToUnderlineCase) {
super();
this.where = where;
this.isToUnderlineCase = isToUnderlineCase;
if (where != null) {
// 获取分页页码
if (where.getPage() != null) {
setCurrent(where.getPage());
}
// 获取分页每页数量
if (where.getLimit() != null) {
setSize(where.getLimit());
}
// 获取排序方式
if (where.getSort() != null) {
if (sortIsSQL(where.getSort())) {
setOrders(parseOrderSQL(where.getSort()));
} else {
List<OrderItem> orderItems = new ArrayList<>();
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(where.getSort()) : where.getSort();
boolean asc = !Constants.ORDER_DESC_VALUE.equals(where.getOrder());
orderItems.add(new OrderItem(column, asc));
setOrders(orderItems);
}
}
}
}
/**
* 排序字段是否是sql
*/
private boolean sortIsSQL(String sort) {
return sort != null && (sort.contains(",") || sort.trim().contains(" "));
}
/**
* 解析排序sql
*/
private List<OrderItem> parseOrderSQL(String orderSQL) {
List<OrderItem> orders = new ArrayList<>();
if (StrUtil.isNotBlank(orderSQL)) {
for (String item : orderSQL.split(",")) {
String[] temp = item.trim().split(" ");
if (!temp[0].isEmpty()) {
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(temp[0]) : temp[0];
boolean asc = temp.length == 1 || !temp[temp.length - 1].equals(Constants.ORDER_DESC_VALUE);
orders.add(new OrderItem(column, asc));
}
}
}
return orders;
}
/**
* 设置默认排序方式
*
* @param orderItems 排序方式
* @return PageParam
*/
public PageParam<T, U> setDefaultOrder(List<OrderItem> orderItems) {
if (orders() == null || orders().size() == 0) {
setOrders(orderItems);
}
return this;
}
/**
* 设置默认排序方式
*
* @param orderSQL 排序方式
* @return PageParam
*/
public PageParam<T, U> setDefaultOrder(String orderSQL) {
setDefaultOrder(parseOrderSQL(orderSQL));
return this;
}
/**
* 获取查询条件
*
* @param excludes 不包含的字段
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapper(String... excludes) {
return buildWrapper(null, Arrays.asList(excludes));
}
/**
* 获取查询条件
*
* @param columns 只包含的字段
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapperWith(String... columns) {
return buildWrapper(Arrays.asList(columns), null);
}
/**
* 构建QueryWrapper
*
* @param columns 包含的字段
* @param excludes 排除的字段
* @return QueryWrapper
*/
private QueryWrapper<T> buildWrapper(List<String> columns, List<String> excludes) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = BeanUtil.beanToMap(where, false, true);
for (String fieldName : map.keySet()) {
Object fieldValue = map.get(fieldName);
Field field = ReflectUtil.getField(where.getClass(), fieldName);
// 过滤不包含的字段
if (columns != null && !columns.contains(fieldName)) {
continue;
}
// 过滤排除的字段
if (excludes != null && excludes.contains(fieldName)) {
continue;
}
// 过滤逻辑删除字段
if (field.getAnnotation(TableLogic.class) != null) {
continue;
}
// 过滤租户id字段
if (fieldName.equals(TENANT_ID_FIELD)) {
continue;
}
// 获取注解指定的查询字段及查询方式
QueryType queryType = QueryType.LIKE;
QueryField queryField = field.getAnnotation(QueryField.class);
if (queryField != null) {
if (StrUtil.isNotEmpty(queryField.value())) {
fieldName = queryField.value();
}
if (queryField.type() != null) {
queryType = queryField.type();
}
} else {
// 过滤非本表的字段
TableField tableField = field.getAnnotation(TableField.class);
if (tableField != null && !tableField.exist()) {
continue;
}
}
// 字段名驼峰转下划线
if (this.isToUnderlineCase) {
fieldName = StrUtil.toUnderlineCase(fieldName);
}
//
switch (queryType) {
case EQ:
queryWrapper.eq(fieldName, fieldValue);
break;
case NE:
queryWrapper.ne(fieldName, fieldValue);
break;
case GT:
queryWrapper.gt(fieldName, fieldValue);
break;
case GE:
queryWrapper.ge(fieldName, fieldValue);
break;
case LT:
queryWrapper.lt(fieldName, fieldValue);
break;
case LE:
queryWrapper.le(fieldName, fieldValue);
break;
case LIKE:
queryWrapper.like(fieldName, fieldValue);
break;
case NOT_LIKE:
queryWrapper.notLike(fieldName, fieldValue);
break;
case LIKE_LEFT:
queryWrapper.likeLeft(fieldName, fieldValue);
break;
case LIKE_RIGHT:
queryWrapper.likeRight(fieldName, fieldValue);
break;
case IS_NULL:
queryWrapper.isNull(fieldName);
break;
case IS_NOT_NULL:
queryWrapper.isNotNull(fieldName);
break;
case IN:
queryWrapper.in(fieldName, fieldValue);
break;
case NOT_IN:
queryWrapper.notIn(fieldName, fieldValue);
break;
case IN_STR:
if (fieldValue instanceof String) {
queryWrapper.in(fieldName, Arrays.asList(((String) fieldValue).split(",")));
}
break;
case NOT_IN_STR:
if (fieldValue instanceof String) {
queryWrapper.notIn(fieldName, Arrays.asList(((String) fieldValue).split(",")));
}
break;
}
}
return queryWrapper;
}
/**
* 获取包含排序的查询条件
*
* @return 包含排序的QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper() {
return getOrderWrapper(getWrapper());
}
/**
* 获取包含排序的查询条件
*
* @param queryWrapper 不含排序的QueryWrapper
* @return 包含排序的QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper(QueryWrapper<T> queryWrapper) {
if (queryWrapper == null) {
queryWrapper = new QueryWrapper<>();
}
for (OrderItem orderItem : orders()) {
if (orderItem.isAsc()) {
queryWrapper.orderByAsc(orderItem.getColumn());
} else {
queryWrapper.orderByDesc(orderItem.getColumn());
}
}
return queryWrapper;
}
/**
* 获取集合中的第一条数据
*
* @param records 集合
* @return 第一条数据
*/
public T getOne(List<T> records) {
return CommonUtil.listGetOne(records);
}
/**
* 代码排序集合
*
* @param records 集合
* @return 排序后的集合
*/
public List<T> sortRecords(List<T> records) {
List<OrderItem> orderItems = orders();
if (records == null || records.size() < 2 || orderItems == null || orderItems.size() == 0) {
return records;
}
Comparator<T> comparator = null;
for (OrderItem item : orderItems) {
if (item.getColumn() == null) {
continue;
}
String field = this.isToUnderlineCase ? StrUtil.toCamelCase(item.getColumn()) : item.getColumn();
Function keyExtractor = t -> ReflectUtil.getFieldValue(t, field);
if (comparator == null) {
if (item.isAsc()) {
comparator = Comparator.comparing(keyExtractor);
} else {
comparator = Comparator.comparing(keyExtractor, Comparator.reverseOrder());
}
} else {
if (item.isAsc()) {
comparator.thenComparing(keyExtractor);
} else {
comparator.thenComparing(keyExtractor, Comparator.reverseOrder());
}
}
}
if (comparator != null) {
return records.stream().sorted(comparator).collect(Collectors.toList());
}
return records;
}
}

View File

@@ -0,0 +1,51 @@
package com.gxwebsoft.common.core.web;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
import java.util.List;
/**
* 分页查询返回结果
*
* @author WebSoft
* @since 2017-06-10 10:10:02
*/
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "当前页数据")
private List<T> list;
@Schema(description = "总数量")
private Long count;
public PageResult() {
}
public PageResult(List<T> list) {
this(list, null);
}
public PageResult(List<T> list, Long count) {
setList(list);
setCount(count);
}
public List<T> getList() {
return this.list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getCount() {
return this.count;
}
public void setCount(Long count) {
this.count = count;
}
}

View File

@@ -0,0 +1,139 @@
package com.gxwebsoft.common.system.controller;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.websocket.WebSocketServer;
import com.gxwebsoft.common.system.entity.ChatMessage;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Tag(name = "AI")
@RestController
@RequestMapping("/api/chat")
public class AiController extends BaseController {
@Resource
private WebSocketServer webSocketServer;
@PostMapping("/message")
public ApiResult<?> message(@RequestBody ChatMessage message) throws IOException {
Map<String, String> paramsJsonStr = new HashMap<>();
paramsJsonStr.put("query", message.getQuery());
paramsJsonStr.put("opsType", "0");
Map<String, String> formData = new HashMap<>();
formData.put("user", message.getUser());
formData.put("responseMode", "streaming");
formData.put("paramsJsonStr", JSONUtil.toJSONString(paramsJsonStr));
formData.put("authCode", "a8cc4a0a-aea3-4ea5-811a-80316520a3d3");
// 使用 Java 自带的 HttpURLConnection 发送流式请求
try {
URL url = new URL("https://ai-console.gxshucheng.com/ai-console-api/run/v1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
connection.setConnectTimeout(600000);
connection.setReadTimeout(600000);
// 写入请求体
try (OutputStream os = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
for (Map.Entry<String, String> entry : formData.entrySet()) {
writeFormField(writer, entry.getKey(), entry.getValue());
}
// 添加文件上传部分(可选)
// writeFilePart(writer, "file", "test.txt", "text/plain", "This is the file content.");
writer.append("--").append(boundary).append("--").append("\r\n");
writer.flush();
}
StringBuilder responseStr = new StringBuilder();
// 读取响应流
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println("Received chunk: " + line); // 打印接收到的每一部分数据
// 这里可以对每一部分数据进行处理,例如解析或发送给前端
if (!line.isEmpty()) {
String[] dataList = line.split("data: ");
if (dataList.length == 2) {
// System.out.println(dataList[1]);
Map data = JSONUtil.parseObject(dataList[1], Map.class);
if (data.get("event") != null && data.get("event").equals("message")) {
String answer = (String) data.get("answer");
String task_id = (String) data.get("task_id");
if (answer != null && !answer.isEmpty()) {
HashMap<String, String> answerData = new HashMap<>();
answerData.put("answer", answer);
answerData.put("taskId", task_id);
webSocketServer.sendMessage(message.getUser(), JSONUtil.toJSONString(answerData));
}
System.out.println("answer: " + answer);
responseStr.append(answer);
}else if (data.get("event") != null && data.get("event").equals("message_end")) {
String task_id = (String) data.get("task_id");
HashMap<String, String> answerData = new HashMap<>();
answerData.put("answer", "__END__");
answerData.put("taskId", task_id);
webSocketServer.sendMessage(message.getUser(), JSONUtil.toJSONString(answerData));
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
System.out.println(stackTraceElement);
}
webSocketServer.sendMessage(message.getUser(), "出错了,请晚点再来提问吧~");
return fail("出错了,请晚点再来提问吧~");
}
// 返回成功响应
return success("Stream processing completed");
}
private static final String boundary = "---" + System.currentTimeMillis() + "---";
private static void writeFormField(PrintWriter writer, String fieldName, String value) {
writer.append("--").append(boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"\r\n");
writer.append("\r\n");
writer.append(value).append("\r\n");
}
@PostMapping("/messageStop")
public ApiResult<?> stop(@RequestBody Map<String, Object> data) {
if (data.get("taskId") == null) return success();
String taskId = data.get("taskId").toString();
Map<String, Integer> postData = new HashMap<>();
postData.put("user", getLoginUserId());
String token = "Bearer app-UxV82WXIRrScpf53exkJ7dIw";
if (data.get("type") != null) {
token = "Bearer app-7AFseF5UTEJpZGkW93S0wybh";
}
String res = HttpRequest.post("http://workflow.gxshucheng.com:8010/v1/chat-messages/" + taskId + "/stop")
.header("Authorization", token)
.header("Content-Type", "application/json")
.body(JSONObject.toJSONString(postData))
.execute().body();
System.out.println("stop res:" + res);
return success();
}
}

View File

@@ -0,0 +1,117 @@
package com.gxwebsoft.common.system.controller;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Cache;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.SettingService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 缓存控制器
*
* @author WebSoft
* @since 2022-11-19 13:54:27
*/
@Tag(name = "缓存管理")
@RestController
@RequestMapping("/api/system/cache")
public class CacheController extends BaseController {
@Resource
private SettingService settingService;
@Resource
private CacheClient cacheClient;
@Resource
private RedisUtil redisUtil;
@Resource
private StringRedisTemplate stringRedisTemplate;
@PreAuthorize("hasAuthority('sys:cache:list')")
@Operation(summary = "查询全部缓存")
@GetMapping()
public ApiResult<HashMap<String, Object>> list() {
String key = "cache".concat(getTenantId().toString()).concat("*");
final Set<String> keys = stringRedisTemplate.keys(key);
final HashMap<String, Object> map = new HashMap<>();
final ArrayList<Object> list = new ArrayList<>();
assert keys != null;
keys.forEach(d -> {
final Cache cache = new Cache();
cache.setKey(d);
try {
final String content = stringRedisTemplate.opsForValue().get(d);
if(content != null){
cache.setContent(stringRedisTemplate.opsForValue().get(d));
}
} catch (Exception e) {
e.printStackTrace();
}
list.add(cache);
});
map.put("count",keys.size());
map.put("list",list);
return success(map);
}
@PreAuthorize("hasAuthority('sys:cache:list')")
@Operation(summary = "根据key查询缓存信息")
@GetMapping("/{key}")
public ApiResult<?> get(@PathVariable("key") String key) {
final String s = redisUtil.get(key + getTenantId());
if(StrUtil.isNotBlank(s)){
return success("读取成功", JSONObject.parseObject(s));
}
return fail("缓存不存在!");
}
@PreAuthorize("hasAuthority('sys:cache:save')")
@Operation(summary = "添加缓存")
@PostMapping()
public ApiResult<?> add(@RequestBody Cache cache) {
if (cache.getExpireTime() != null) {
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent(),cache.getExpireTime(), TimeUnit.MINUTES);
return success("缓存成功");
}
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent());
return success("缓存成功");
}
@PreAuthorize("hasAuthority('sys:cache:save')")
@Operation(summary = "删除缓存")
@DeleteMapping("/{key}")
public ApiResult<?> remove(@PathVariable("key") String key) {
if (Boolean.TRUE.equals(stringRedisTemplate.delete(key))) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:cache:save')")
@Operation(summary = "缓存皮肤")
@PostMapping("/theme")
public ApiResult<?> saveTheme(@RequestBody Cache cache) {
final User loginUser = getLoginUser();
final String username = loginUser.getUsername();
if (username.equals("admin")) {
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent());
return success("缓存成功");
}
return success("缓存失败");
}
}

View File

@@ -0,0 +1,177 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Dict;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.param.DictDataParam;
import com.gxwebsoft.common.system.param.DictParam;
import com.gxwebsoft.common.system.service.DictDataService;
import com.gxwebsoft.common.system.service.DictService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
/**
* 字典控制器
*
* @author WebSoft
* @since 2020-03-14 11:29:03
*/
@Tag(name = "字典管理(业务类)")
@RestController
@RequestMapping("/api/system/dict")
public class DictController extends BaseController {
@Resource
private DictService dictService;
@Resource
private DictDataService dictDataService;
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "分页查询字典")
@GetMapping("/page")
public ApiResult<PageResult<Dict>> page(DictParam param) {
PageParam<Dict, DictParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "查询全部字典")
@GetMapping()
public ApiResult<List<Dict>> list(DictParam param) {
PageParam<Dict, DictParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "查询全部字典")
@GetMapping("/tree")
public ApiResult<?> tree() {
final HashMap<Object, Object> result = new HashMap<>();
final List<DictData> dictData = dictDataService.listRel(new DictDataParam());
final Map<String, List<DictData>> dataCollect = dictData.stream().collect(Collectors.groupingBy(DictData::getDictCode));
for (String code : dataCollect.keySet()) {
Dict dict = new Dict();
dict.setDictCode(code);
final Set<Set<String>> list = new LinkedHashSet<>();
Set<String> codes = new LinkedHashSet<>();
for(DictData item : dictData){
if (item.getDictCode().equals(code)) {
codes.add(item.getDictDataCode());
}
}
list.add(codes);
dict.setItems(list);
result.put(code,dict.getItems());
}
return success(result);
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "根据id查询字典")
@GetMapping("/{id}")
public ApiResult<Dict> get(@PathVariable("id") Integer id) {
return success(dictService.getById(id));
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "添加字典")
@PostMapping()
public ApiResult<?> add(@RequestBody Dict dict) {
if (dictService.count(new LambdaQueryWrapper<Dict>()
.eq(Dict::getDictCode, dict.getDictCode())) > 0) {
return fail("字典标识已存在");
}
if (dictService.count(new LambdaQueryWrapper<Dict>()
.eq(Dict::getDictName, dict.getDictName())) > 0) {
return fail("字典名称已存在");
}
if (dictService.save(dict)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:update')")
@Operation(summary = "修改字典")
@PutMapping()
public ApiResult<?> update(@RequestBody Dict dict) {
if (dictService.count(new LambdaQueryWrapper<Dict>()
.eq(Dict::getDictCode, dict.getDictCode())
.ne(Dict::getDictId, dict.getDictId())) > 0) {
return fail("字典标识已存在");
}
if (dictService.count(new LambdaQueryWrapper<Dict>()
.eq(Dict::getDictName, dict.getDictName())
.ne(Dict::getDictId, dict.getDictId())) > 0) {
return fail("字典名称已存在");
}
if (dictService.updateById(dict)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "删除字典")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "批量添加字典")
@PostMapping("/batch")
public ApiResult<List<String>> saveBatch(@RequestBody List<Dict> list) {
if (CommonUtil.checkRepeat(list, Dict::getDictCode)) {
return fail("字典标识不能重复", null);
}
if (CommonUtil.checkRepeat(list, Dict::getDictName)) {
return fail("字典名称不能重复", null);
}
List<Dict> codeExists = dictService.list(new LambdaQueryWrapper<Dict>()
.in(Dict::getDictCode, list.stream().map(Dict::getDictCode)
.collect(Collectors.toList())));
if (codeExists.size() > 0) {
return fail("字典标识已存在", codeExists.stream().map(Dict::getDictCode)
.collect(Collectors.toList())).setCode(2);
}
List<Dict> nameExists = dictService.list(new LambdaQueryWrapper<Dict>()
.in(Dict::getDictName, list.stream().map(Dict::getDictCode)
.collect(Collectors.toList())));
if (nameExists.size() > 0) {
return fail("字典名称已存在", nameExists.stream().map(Dict::getDictName)
.collect(Collectors.toList())).setCode(3);
}
if (dictService.saveBatch(list)) {
return success("添加成功", null);
}
return fail("添加失败", null);
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "批量删除字典")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,124 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.param.DictDataParam;
import com.gxwebsoft.common.system.service.DictDataService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 字典数据控制器
*
* @author WebSoft
* @since 2020-03-14 11:29:04
*/
@Tag(name = "字典数据管理(业务类)")
@RestController
@RequestMapping("/api/system/dict-data")
public class DictDataController extends BaseController {
@Resource
private DictDataService dictDataService;
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "分页查询字典数据")
@GetMapping("/page")
public ApiResult<PageResult<DictData>> page(DictDataParam param) {
return success(dictDataService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "查询全部字典数据")
@GetMapping()
public ApiResult<List<DictData>> list(DictDataParam param) {
return success(dictDataService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "根据id查询字典数据")
@GetMapping("/{id}")
public ApiResult<DictData> get(@PathVariable("id") Integer id) {
return success(dictDataService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "添加字典数据")
@PostMapping()
public ApiResult<?> add(@RequestBody DictData dictData) {
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
.eq(DictData::getDictId, dictData.getDictId())
.eq(DictData::getDictDataName, dictData.getDictDataName())) > 0) {
return fail("字典数据名称已存在");
}
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
.eq(DictData::getDictId, dictData.getDictId())
.eq(DictData::getDictDataCode, dictData.getDictDataCode())) > 0) {
return fail("字典数据标识已存在");
}
if (dictDataService.save(dictData)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:update')")
@Operation(summary = "修改字典数据")
@PutMapping()
public ApiResult<?> update(@RequestBody DictData dictData) {
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
.eq(DictData::getDictId, dictData.getDictId())
.eq(DictData::getDictDataName, dictData.getDictDataName())
.ne(DictData::getDictDataId, dictData.getDictDataId())) > 0) {
return fail("字典数据名称已存在");
}
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
.eq(DictData::getDictId, dictData.getDictId())
.eq(DictData::getDictDataCode, dictData.getDictDataCode())
.ne(DictData::getDictDataId, dictData.getDictDataId())) > 0) {
return fail("字典数据标识已存在");
}
if (dictDataService.updateById(dictData)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "删除字典数据")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictDataService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "批量添加字典数据")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<DictData> dictDataList) {
if (dictDataService.saveBatch(dictDataList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "批量删除字典数据")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictDataService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,148 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Dictionary;
import com.gxwebsoft.common.system.param.DictionaryParam;
import com.gxwebsoft.common.system.service.DictionaryService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* 字典控制器
*
* @author WebSoft
* @since 2020-03-14 11:29:03
*/
@Tag(name = "字典管理(系统类)")
@RestController
@RequestMapping("/api/system/dictionary")
public class DictionaryController extends BaseController {
@Resource
private DictionaryService dictionaryService;
@PreAuthorize("hasAuthority('sys:dictionary:list')")
@Operation(summary = "分页查询字典")
@GetMapping("/page")
public ApiResult<PageResult<Dictionary>> page(DictionaryParam param) {
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictionaryService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:dictionary:list')")
@Operation(summary = "查询全部字典")
@GetMapping()
public ApiResult<List<Dictionary>> list(DictionaryParam param) {
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(dictionaryService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:dictionary:list')")
@Operation(summary = "根据id查询字典")
@GetMapping("/{id}")
public ApiResult<Dictionary> get(@PathVariable("id") Integer id) {
return success(dictionaryService.getById(id));
}
@PreAuthorize("hasAuthority('sys:dictionary:save')")
@Operation(summary = "添加字典")
@PostMapping()
public ApiResult<?> add(@RequestBody Dictionary dictionary) {
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictCode, dictionary.getDictCode())) > 0) {
return fail("字典标识已存在");
}
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictName, dictionary.getDictName())) > 0) {
return fail("字典名称已存在");
}
if (dictionaryService.save(dictionary)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dictionary:update')")
@Operation(summary = "修改字典")
@PutMapping()
public ApiResult<?> update(@RequestBody Dictionary dictionary) {
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictCode, dictionary.getDictCode())
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
return fail("字典标识已存在");
}
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
.eq(Dictionary::getDictName, dictionary.getDictName())
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
return fail("字典名称已存在");
}
if (dictionaryService.updateById(dictionary)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dictionary:remove')")
@Operation(summary = "删除字典")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictionaryService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dictionary:save')")
@Operation(summary = "批量添加字典")
@PostMapping("/batch")
public ApiResult<List<String>> saveBatch(@RequestBody List<Dictionary> list) {
if (CommonUtil.checkRepeat(list, Dictionary::getDictCode)) {
return fail("字典标识不能重复", null);
}
if (CommonUtil.checkRepeat(list, Dictionary::getDictName)) {
return fail("字典名称不能重复", null);
}
List<Dictionary> codeExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
.in(Dictionary::getDictCode, list.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())));
if (codeExists.size() > 0) {
return fail("字典标识已存在", codeExists.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())).setCode(2);
}
List<Dictionary> nameExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
.in(Dictionary::getDictName, list.stream().map(Dictionary::getDictCode)
.collect(Collectors.toList())));
if (nameExists.size() > 0) {
return fail("字典名称已存在", nameExists.stream().map(Dictionary::getDictName)
.collect(Collectors.toList())).setCode(3);
}
if (dictionaryService.saveBatch(list)) {
return success("添加成功", null);
}
return fail("添加失败", null);
}
@PreAuthorize("hasAuthority('sys:dictionary:remove')")
@Operation(summary = "批量删除字典")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,123 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.DictionaryData;
import com.gxwebsoft.common.system.param.DictionaryDataParam;
import com.gxwebsoft.common.system.service.DictionaryDataService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 字典数据控制器
*
* @author WebSoft
* @since 2020-03-14 11:29:04
*/
@Tag(name = "字典数据管理(系统类)")
@RestController
@RequestMapping("/api/system/dictionary-data")
public class DictionaryDataController extends BaseController {
@Resource
private DictionaryDataService dictionaryDataService;
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "分页查询字典数据")
@GetMapping("/page")
public ApiResult<PageResult<DictionaryData>> page(DictionaryDataParam param) {
return success(dictionaryDataService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "查询全部字典数据")
@GetMapping()
public ApiResult<List<DictionaryData>> list(DictionaryDataParam param) {
return success(dictionaryDataService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:dict:list')")
@Operation(summary = "根据id查询字典数据")
@GetMapping("/{id}")
public ApiResult<DictionaryData> get(@PathVariable("id") Integer id) {
return success(dictionaryDataService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "添加字典数据")
@PostMapping()
public ApiResult<?> add(@RequestBody DictionaryData dictionaryData) {
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())) > 0) {
return fail("字典数据名称已存在");
}
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())) > 0) {
return fail("字典数据标识已存在");
}
if (dictionaryDataService.save(dictionaryData)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:update')")
@Operation(summary = "修改字典数据")
@PutMapping()
public ApiResult<?> update(@RequestBody DictionaryData dictionaryData) {
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
return fail("字典数据名称已存在");
}
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
return fail("字典数据标识已存在");
}
if (dictionaryDataService.updateById(dictionaryData)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "删除字典数据")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (dictionaryDataService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:dict:save')")
@Operation(summary = "批量添加字典数据")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<DictionaryData> dictDataList) {
if (dictionaryDataService.saveBatch(dictDataList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:dict:remove')")
@Operation(summary = "批量删除字典数据")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryDataService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,127 @@
package com.gxwebsoft.common.system.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Domain;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.param.DomainParam;
import com.gxwebsoft.common.system.service.DomainService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 授权域名控制器
*
* @author 科技小王子
* @since 2024-09-19 23:56:33
*/
@Tag(name = "授权域名管理")
@RestController
@RequestMapping("/api/system/domain")
public class DomainController extends BaseController {
@Resource
private DomainService domainService;
@Operation(summary = "分页查询授权域名")
@GetMapping("/page")
public ApiResult<PageResult<Domain>> page(DomainParam param) {
// 使用关联查询
return success(domainService.pageRel(param));
}
@Operation(summary = "查询全部授权域名")
@GetMapping()
public ApiResult<List<Domain>> list(DomainParam param) {
// 使用关联查询
return success(domainService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:domain:list')")
@OperationLog
@Operation(summary = "根据id查询授权域名")
@GetMapping("/{id}")
public ApiResult<Domain> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(domainService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:domain:save')")
@OperationLog
@Operation(summary = "添加授权域名")
@PostMapping()
public ApiResult<?> save(@RequestBody Domain domain) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
domain.setUserId(loginUser.getUserId());
}
if (domainService.save(domain)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:domain:update')")
@OperationLog
@Operation(summary = "修改授权域名")
@PutMapping()
public ApiResult<?> update(@RequestBody Domain domain) {
if (domainService.updateById(domain)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:domain:remove')")
@OperationLog
@Operation(summary = "删除授权域名")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (domainService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:domain:save')")
@OperationLog
@Operation(summary = "批量添加授权域名")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Domain> list) {
if (domainService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:domain:update')")
@OperationLog
@Operation(summary = "批量修改授权域名")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Domain> batchParam) {
if (batchParam.update(domainService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:domain:remove')")
@OperationLog
@Operation(summary = "批量删除授权域名")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (domainService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,48 @@
package com.gxwebsoft.common.system.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.EmailRecord;
import com.gxwebsoft.common.system.service.EmailRecordService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.mail.MessagingException;
/**
* 邮件功能控制器
*
* @author WebSoft
* @since 2020-03-21 00:37:11
*/
@Tag(name = "邮件功能")
@RestController
@RequestMapping("/api/system/email")
public class EmailController extends BaseController {
@Resource
private EmailRecordService emailRecordService;
@PreAuthorize("hasAuthority('sys:email:send')")
@Operation(summary = "发送邮件")
@PostMapping()
public ApiResult<?> send(@RequestBody EmailRecord emailRecord) {
try {
emailRecordService.sendFullTextEmail(emailRecord.getTitle(), emailRecord.getContent(),
emailRecord.getReceiver().split(","));
emailRecord.setCreateUserId(getLoginUserId());
emailRecordService.save(emailRecord);
return success("发送成功");
} catch (MessagingException e) {
e.printStackTrace();
}
return fail("发送失败");
}
}

View File

@@ -0,0 +1,55 @@
package com.gxwebsoft.common.system.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.LoginRecord;
import com.gxwebsoft.common.system.param.LoginRecordParam;
import com.gxwebsoft.common.system.service.LoginRecordService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* 登录日志控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:31
*/
@Tag(name = "登录日志")
@RestController
@RequestMapping("/api/system/login-record")
public class LoginRecordController extends BaseController {
@Resource
private LoginRecordService loginRecordService;
@PreAuthorize("hasAuthority('sys:login-record:list')")
@Operation(summary = "分页查询登录日志")
@GetMapping("/page")
public ApiResult<PageResult<LoginRecord>> page(LoginRecordParam param) {
return success(loginRecordService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:login-record:list')")
@Operation(summary = "查询全部登录日志")
@GetMapping()
public ApiResult<List<LoginRecord>> list(LoginRecordParam param) {
return success(loginRecordService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:login-record:list')")
@Operation(summary = "根据id查询登录日志")
@GetMapping("/{id}")
public ApiResult<LoginRecord> get(@PathVariable("id") Integer id) {
return success(loginRecordService.getByIdRel(id));
}
}

View File

@@ -0,0 +1,314 @@
package com.gxwebsoft.common.system.controller;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.security.JwtSubject;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.ExistenceParam;
import com.gxwebsoft.common.system.entity.LoginRecord;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.param.LoginParam;
import com.gxwebsoft.common.system.param.SmsCaptchaParam;
import com.gxwebsoft.common.system.param.UpdatePasswordParam;
import com.gxwebsoft.common.system.result.CaptchaResult;
import com.gxwebsoft.common.system.result.LoginResult;
import com.gxwebsoft.common.system.service.*;
import com.wf.captcha.SpecCaptcha;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* 登录认证控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:11
*/
@Tag(name = "登录认证")
@RestController
@RequestMapping("/api")
public class MainController extends BaseController {
@Resource
private ConfigProperties configProperties;
@Resource
private UserService userService;
@Resource
private RoleMenuService roleMenuService;
@Resource
private LoginRecordService loginRecordService;
@Resource
private CacheClient cacheClient;
@Resource
private RedisUtil redisUtil;
@Operation(summary = "检查用户是否存在")
@GetMapping("/existence")
public ApiResult<?> existence(ExistenceParam<User> param) {
if (param.isExistence(userService, User::getUserId)) {
return success("已存在", param.getValue());
}
return fail("不存在");
}
@Operation(summary = "获取登录用户信息")
@GetMapping("/auth/user")
public ApiResult<User> userInfo() {
final Integer loginUserId = getLoginUserId();
if(loginUserId != null){
return success(userService.getByIdRel(getLoginUserId()));
}
return fail("loginUserId不存在",null);
}
@Operation(summary = "获取登录用户菜单")
@GetMapping("/auth/menu")
public ApiResult<List<Menu>> userMenu() {
List<Menu> menus = roleMenuService.listMenuByUserId(getLoginUserId(), Menu.TYPE_MENU);
return success(CommonUtil.toTreeData(menus, 0, Menu::getParentId, Menu::getMenuId, Menu::setChildren));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "修改个人信息")
@PutMapping("/auth/user")
public ApiResult<User> updateInfo(@RequestBody User user) {
user.setUserId(getLoginUserId());
// 不能修改的字段
user.setUsername(null);
user.setPassword(null);
user.setEmailVerified(null);
user.setOrganizationId(null);
user.setStatus(null);
if (userService.updateById(user)) {
return success(userService.getByIdRel(user.getUserId()));
}
return fail("保存失败", null);
}
@PreAuthorize("hasAuthority('sys:auth:password')")
@Operation(summary = "修改自己密码")
@PutMapping("/auth/password")
public ApiResult<?> updatePassword(@RequestBody UpdatePasswordParam param) {
if (StrUtil.hasBlank(param.getOldPassword(), param.getPassword())) {
return fail("参数不能为空");
}
Integer userId = getLoginUserId();
if (userId == null) {
return fail("未登录");
}
if (!userService.comparePassword(userService.getById(userId).getPassword(), param.getOldPassword())) {
return fail("原密码输入不正确");
}
User user = new User();
user.setUserId(userId);
user.setPassword(userService.encodePassword(param.getPassword()));
if (userService.updateById(user)) {
return success("修改成功");
}
return fail("修改失败");
}
@Operation(summary = "图形验证码")
@GetMapping("/captcha")
public ApiResult<CaptchaResult> captcha() {
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
return success(new CaptchaResult(specCaptcha.toBase64(), specCaptcha.text().toLowerCase()));
}
@Operation(summary = "企业微信登录链接")
@GetMapping("/wxWorkQrConnect")
public ApiResult<?> wxWorkQrConnect() throws UnsupportedEncodingException {
final JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", 10048);
final String corpId = settingInfo.getString("corpId");
String encodedReturnUrl = URLEncoder.encode("https://oa.gxwebsoft.com/api/open/wx-work/login","UTF-8");
String url = "https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=" +corpId+ "&redirect_uri=" +encodedReturnUrl+ "&state=ww_login@gxwebsoft&usertype=admin";
return success("获取成功",url);
}
@Operation(summary = "短信验证码")
@PostMapping("/sendSmsCaptcha")
public ApiResult<?> sendSmsCaptcha(@RequestBody SmsCaptchaParam param) {
// 读取短信配置信息
String string = redisUtil.get("setting:sms:" + getTenantId());
JSONObject jsonObject = JSONObject.parseObject(string);
String accessKeyId = jsonObject.getString("accessKeyId");
String accessKeySecret = jsonObject.getString("accessKeySecret");
String userTemplateId = jsonObject.getString("userTemplateId");
String sign = jsonObject.getString("sign");
if(accessKeyId != null){
DefaultProfile profile = DefaultProfile.getProfile("regionld", accessKeyId, accessKeySecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", param.getPhone());
request.putQueryParameter("SignName", sign);
request.putQueryParameter("TemplateCode", userTemplateId);
// 生成短信验证码
Random randObj = new Random();
String code = Integer.toString(100000 + randObj.nextInt(900000));
request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println("response = " + response);
String json = response.getData();
System.out.println("json = " + json);
Gson g = new Gson();
HashMap result = g.fromJson(json, HashMap.class);
System.out.println("result = " + result);
if("OK".equals(result.get("Message"))) {
System.out.println("======================== = " + result);
cacheClient.set(param.getPhone(),code,5L,TimeUnit.MINUTES);
String key = "code:" + param.getPhone();
redisUtil.set(key,code,5L,TimeUnit.MINUTES);
return success("发送成功",result.get("Message"));
}else{
return fail("发送失败");
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
return fail("发送失败");
}
@Operation(summary = "重置密码")
@PutMapping("/password")
public ApiResult<?> resetPassword(@RequestBody User user) {
if (user.getPassword() == null) {
return fail("参数不正确");
}
if (user.getCode() == null) {
return fail("验证码不能为空");
}
// 短信验证码校验
String code = cacheClient.get(user.getPhone(), String.class);
if (!StrUtil.equals(code,user.getCode())) {
return fail("验证码不正确");
}
user.setUserId(getLoginUserId());
user.setPassword(userService.encodePassword(user.getPassword()));
if (userService.updateById(user)) {
return success("密码修改成功");
} else {
return fail("密码修改失败");
}
}
@Operation(summary = "短信验证码登录")
@PostMapping("/loginBySms")
public ApiResult<LoginResult> loginBySms(@RequestBody LoginParam param, HttpServletRequest request) {
final String phone = param.getPhone();
final Integer tenantId = param.getTenantId();
final String code = param.getCode();
User user = userService.getByUsername(phone, tenantId);
// 验证码校验
String key = "code:" + param.getPhone();
if(!code.equals(redisUtil.get(key))){
String message = "验证码不正确";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId,request);
return fail(message, null);
}
if (user == null) {
String message = "账号不存在";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId,request);
return fail(message, null);
}
if (!user.getStatus().equals(0)) {
String message = "账号被冻结";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId, request);
return fail(message, null);
}
loginRecordService.saveAsync(phone, LoginRecord.TYPE_LOGIN, null, tenantId, request);
// 设置过期时间
Long tokenExpireTime = configProperties.getTokenExpireTime();
final JSONObject register = cacheClient.getSettingInfo("register", tenantId);
if(register != null){
final String ExpireTime = register.getString("tokenExpireTime");
if (ExpireTime != null) {
tokenExpireTime = Long.valueOf(ExpireTime);
}
}
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(phone, tenantId),
tokenExpireTime, configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, user));
}
@Operation(summary = "会员注册")
@PostMapping("/register")
public ApiResult<LoginResult> register(@RequestBody LoginParam param, HttpServletRequest request) {
final String phone = param.getPhone();
final Integer tenantId = param.getTenantId();
final String code = param.getCode();
User user = userService.getByUsername(phone, tenantId);
// 验证码校验
String key = "code:" + param.getPhone();
if(!code.equals(redisUtil.get(key))){
String message = "验证码不正确";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId,request);
return fail(message, null);
}
if (user == null) {
String message = "账号不存在";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId,request);
return fail(message, null);
}
if (!user.getStatus().equals(0)) {
String message = "账号被冻结";
loginRecordService.saveAsync(phone, LoginRecord.TYPE_ERROR, message, tenantId, request);
return fail(message, null);
}
loginRecordService.saveAsync(phone, LoginRecord.TYPE_LOGIN, null, tenantId, request);
// 设置过期时间
Long tokenExpireTime = configProperties.getTokenExpireTime();
final JSONObject register = cacheClient.getSettingInfo("register", tenantId);
if(register != null){
final String ExpireTime = register.getString("tokenExpireTime");
if (ExpireTime != null) {
tokenExpireTime = Long.valueOf(ExpireTime);
}
}
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(phone, tenantId),
tokenExpireTime, configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, user));
}
}

View File

@@ -0,0 +1,145 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.Plug;
import com.gxwebsoft.common.system.param.MenuParam;
import com.gxwebsoft.common.system.service.MenuService;
import com.gxwebsoft.common.system.service.PlugService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 菜单控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:23
*/
@Tag(name = "菜单管理")
@RestController
@RequestMapping("/api/system/menu")
public class MenuController extends BaseController {
@Resource
private MenuService menuService;
@Resource
private PlugService plugService;
@PreAuthorize("hasAuthority('sys:menu:list')")
@Operation(summary = "分页查询菜单")
@GetMapping("/page")
public ApiResult<PageResult<Menu>> page(MenuParam param) {
PageParam<Menu, MenuParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(menuService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:menu:list')")
@Operation(summary = "查询全部菜单")
@GetMapping()
public ApiResult<List<Menu>> list(MenuParam param) {
PageParam<Menu, MenuParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number");
return success(menuService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:menu:list')")
@Operation(summary = "根据id查询菜单")
@GetMapping("/{id}")
public ApiResult<Menu> get(@PathVariable("id") Integer id) {
return success(menuService.getById(id));
}
@PreAuthorize("hasAuthority('sys:menu:save')")
@Operation(summary = "添加菜单")
@PostMapping()
public ApiResult<?> add(@RequestBody Menu menu) {
if (menu.getParentId() == null) {
menu.setParentId(0);
}
if (menuService.save(menu)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@Operation(summary = "修改菜单")
@PutMapping()
public ApiResult<?> update(@RequestBody Menu menu) {
if (menuService.updateById(menu)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:menu:remove')")
@Operation(summary = "删除菜单")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (menuService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:menu:save')")
@Operation(summary = "批量添加菜单")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Menu> menus) {
if (menuService.saveBatch(menus)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@Operation(summary = "批量修改菜单")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<Menu> batchParam) {
if (batchParam.update(menuService, "menu_id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:menu:remove')")
@Operation(summary = "批量删除菜单")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (menuService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@Operation(summary = "菜单克隆")
@PostMapping("/clone")
public ApiResult<?> onClone(@RequestBody MenuParam param){
if(menuService.cloneMenu(param)){
return success("克隆成功,请刷新");
}
return fail("克隆失败");
}
@PreAuthorize("hasAuthority('sys:menu:update')")
@Operation(summary = "安装插件")
@GetMapping("/install/{id}")
public ApiResult<?> install(@PathVariable("id") Integer id){
if(menuService.install(id)){
// 更新安装次数
final Plug plug = plugService.getOne(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, id));
plug.setInstalls(plug.getInstalls() + 1);
plugService.updateById(plug);
return success("安装成功");
}
return fail("安装失败",id);
}
}

View File

@@ -0,0 +1,61 @@
package com.gxwebsoft.common.system.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.OperationRecord;
import com.gxwebsoft.common.system.param.OperationRecordParam;
import com.gxwebsoft.common.system.service.OperationRecordService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 操作日志控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:12
*/
@Tag(name = "操作日志")
@RestController
@RequestMapping("/api/system/operation-record")
public class OperationRecordController extends BaseController {
@Resource
private OperationRecordService operationRecordService;
/**
* 分页查询操作日志
*/
@PreAuthorize("hasAuthority('sys:operation-record:list')")
@Operation(summary = "分页查询操作日志")
@GetMapping("/page")
public ApiResult<PageResult<OperationRecord>> page(OperationRecordParam param) {
return success(operationRecordService.pageRel(param));
}
/**
* 查询全部操作日志
*/
@PreAuthorize("hasAuthority('sys:operation-record:list')")
@Operation(summary = "查询全部操作日志")
@GetMapping()
public ApiResult<List<OperationRecord>> list(OperationRecordParam param) {
return success(operationRecordService.listRel(param));
}
/**
* 根据id查询操作日志
*/
@PreAuthorize("hasAuthority('sys:operation-record:list')")
@Operation(summary = "根据id查询操作日志")
@GetMapping("/{id}")
public ApiResult<OperationRecord> get(@PathVariable("id") Integer id) {
return success(operationRecordService.getByIdRel(id));
}
}

View File

@@ -0,0 +1,130 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.Organization;
import com.gxwebsoft.common.system.param.OrganizationParam;
import com.gxwebsoft.common.system.service.OrganizationService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 组织机构控制器
*
* @author WebSoft
* @since 2020-03-14 11:29:04
*/
@Tag(name = "组织机构管理")
@RestController
@RequestMapping("/api/system/organization")
public class OrganizationController extends BaseController {
@Resource
private OrganizationService organizationService;
@PreAuthorize("hasAuthority('sys:org:list')")
@Operation(summary = "分页查询组织机构")
@GetMapping("/page")
public ApiResult<PageResult<Organization>> page(OrganizationParam param) {
return success(organizationService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:org:list')")
@Operation(summary = "查询全部组织机构")
@GetMapping()
public ApiResult<List<Organization>> list(OrganizationParam param) {
return success(organizationService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:org:list')")
@Operation(summary = "根据id查询组织机构")
@GetMapping("/{id}")
public ApiResult<Organization> get(@PathVariable("id") Integer id) {
return success(organizationService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:org:save')")
@Operation(summary = "添加组织机构")
@PostMapping()
public ApiResult<?> add(@RequestBody Organization organization) {
if (organization.getParentId() == null) {
organization.setParentId(0);
}
if (organizationService.count(new LambdaQueryWrapper<Organization>()
.eq(Organization::getOrganizationName, organization.getOrganizationName())
.eq(Organization::getParentId, organization.getParentId())) > 0) {
return fail("机构名称已存在");
}
if (organizationService.save(organization)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:org:update')")
@Operation(summary = "修改组织机构")
@PutMapping()
public ApiResult<?> update(@RequestBody Organization organization) {
if (organization.getOrganizationName() != null) {
if (organization.getParentId() == null) {
organization.setParentId(0);
}
if (organizationService.count(new LambdaQueryWrapper<Organization>()
.eq(Organization::getOrganizationName, organization.getOrganizationName())
.eq(Organization::getParentId, organization.getParentId())
.ne(Organization::getOrganizationId, organization.getOrganizationId())) > 0) {
return fail("机构名称已存在");
}
}
if (organizationService.updateById(organization)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:org:remove')")
@Operation(summary = "删除组织机构")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (organizationService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:org:save')")
@Operation(summary = "批量添加组织机构")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Organization> organizationList) {
if (organizationService.saveBatch(organizationList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:org:update')")
@Operation(summary = "批量修改组织机构")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<Organization> batchParam) {
if (batchParam.update(organizationService, Organization::getOrganizationId)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:org:remove')")
@Operation(summary = "批量删除组织机构")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (organizationService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,161 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.Plug;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.param.PlugParam;
import com.gxwebsoft.common.system.service.MenuService;
import com.gxwebsoft.common.system.service.PlugService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 插件扩展控制器
*
* @author 科技小王子
* @since 2023-05-18 11:57:37
*/
@Tag(name = "插件扩展管理")
@RestController
@RequestMapping("/api/system/plug")
public class PlugController extends BaseController {
@Resource
private PlugService plugService;
@Resource
private MenuService menuService;
@PreAuthorize("hasAuthority('sys:plug:list')")
@Operation(summary = "分页查询插件扩展")
@GetMapping("/page")
public ApiResult<PageResult<Plug>> page(PlugParam param) {
// 如果不传userId只显示审核通过的插件
if (param.getUserId() == null) {
param.setStatus(20);
}
// 使用关联查询
return success(plugService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:plug:list')")
@Operation(summary = "查询全部插件扩展")
@GetMapping()
public ApiResult<List<Plug>> list(PlugParam param) {
// 使用关联查询
return success(plugService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:plug:list')")
@Operation(summary = "根据id查询插件扩展")
@GetMapping("/{id}")
public ApiResult<Plug> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(plugService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:plug:save')")
@Operation(summary = "添加插件扩展")
@PostMapping()
public ApiResult<?> save(@RequestBody Plug plug) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
plug.setUserId(loginUser.getUserId());
}
if (plugService.save(plug)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:plug:update')")
@Operation(summary = "修改插件扩展")
@PutMapping()
public ApiResult<?> update(@RequestBody Plug plug) {
if (plugService.updateById(plug)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:plug:remove')")
@Operation(summary = "删除插件扩展")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (plugService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:plug:save')")
@Operation(summary = "批量添加插件扩展")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Plug> list) {
if (plugService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:plug:update')")
@Operation(summary = "批量修改插件扩展")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Plug> batchParam) {
if (batchParam.update(plugService, "menu_id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:plug:remove')")
@Operation(summary = "批量删除插件扩展")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (plugService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:plug:save')")
@Operation(summary = "发布插件")
@PostMapping("/plug")
public ApiResult<?> plug(@RequestBody Plug plug){
final Integer menuId = plug.getParentId();
// 查重
final long count = plugService.count(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, menuId));
if(count > 0){
return fail("请勿重复发布");
}
// 准备数据
final Menu menu = menuService.getById(menuId);
plug.setUserId(getLoginUserId());
plug.setMenuId(menuId);
plug.setTenantId(getTenantId());
plug.setIcon(menu.getIcon());
plug.setPath(menu.getPath());
plug.setComponent(menu.getComponent());
plug.setAuthority(menu.getAuthority());
plug.setTitle(menu.getTitle());
plug.setMenuType(menu.getMenuType());
plug.setMeta(menu.getMeta());
plug.setParentId(menu.getParentId());
plug.setHide(menu.getHide());
plug.setSortNumber(menu.getSortNumber());
if(plugService.save(plug)){
return success("发布成功");
}
return fail("发布失败");
}
}

View File

@@ -0,0 +1,77 @@
package com.gxwebsoft.common.system.controller;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/redis-util")
@Tag(name = "Redis缓存工具接口")
public class RedisUtilController extends BaseController {
private CacheClient cacheClient;
private final StringRedisTemplate redisTemplate;
private static final String SPLIT = ":";
private static final String PREFIX_ENTITY_LIKE = "focus:user";
private static final String PREFIX_USER_LIKE = "like:user";
private static final String PREFIX_FOLLOWEE = "followee";
private static final String PREFIX_FOLLOWER = "follower";
public RedisUtilController(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Operation(summary = "添加关注")
@PostMapping("/addFocus")
public ApiResult<?> addFocus(@RequestBody User user) {
final Integer userId = user.getUserId();
redisTemplate.opsForZSet().incrementScore(getFocusKey(userId), userId.toString(), 1);
return success("关注成功");
}
/**
* 某个用户的关注数
* @return like:entity:[entityId] ->set(userId)
*/
public static String getFocusKey(Integer userId) {
return PREFIX_ENTITY_LIKE + SPLIT + userId;
}
/**
* 某个用户的赞
* @return like:entity:[entityId] ->set(userId)
*/
public static String getEntityLikeKey(int entityType, int entityId) {
return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;
}
/**
* 某个用户的赞
* @return like:user:[userId] ->int
*/
public static String getUserLikeKey(int userId) {
return PREFIX_USER_LIKE + SPLIT + userId;
}
/**
* 某个用户关注的实体用户Id实体Id
* @return followee:[userId:entityType] ->zSet(entityId,now)
*/
public static String getFolloweeKey(int userId, int entityType) {
return PREFIX_FOLLOWEE + SPLIT + userId + SPLIT + entityType;
}
/**
* 某个实体拥有的粉丝实体Id用户Id)
* @return follower:[entityType:entityId] ->zSet(entityId,now)
*/
public static String getFollowerKey(int entityType, int entityId) {
return PREFIX_FOLLOWER + SPLIT + entityType + SPLIT + entityId;
}
}

View File

@@ -0,0 +1,144 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Role;
import com.gxwebsoft.common.system.param.RoleParam;
import com.gxwebsoft.common.system.service.RoleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* 角色控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:02
*/
@Tag(name = "角色管理")
@RestController
@RequestMapping("/api/system/role")
public class RoleController extends BaseController {
@Resource
private RoleService roleService;
@PreAuthorize("hasAuthority('sys:role:list')")
@Operation(summary = "分页查询角色")
@GetMapping("/page")
public ApiResult<PageResult<Role>> page(RoleParam param) {
PageParam<Role, RoleParam> page = new PageParam<>(param);
return success(roleService.page(page, page.getWrapper()));
}
@PreAuthorize("hasAuthority('sys:role:list')")
@Operation(summary = "查询全部角色")
@GetMapping()
public ApiResult<List<Role>> list(RoleParam param) {
PageParam<Role, RoleParam> page = new PageParam<>(param);
return success(roleService.list(page.getOrderWrapper()));
}
@PreAuthorize("hasAuthority('sys:role:list')")
@Operation(summary = "根据id查询角色")
@GetMapping("/{id}")
public ApiResult<Role> get(@PathVariable("id") Integer id) {
return success(roleService.getById(id));
}
@PreAuthorize("hasAuthority('sys:role:save')")
@Operation(summary = "添加角色")
@PostMapping()
public ApiResult<?> save(@RequestBody Role role) {
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, role.getRoleCode())) > 0) {
return fail("角色标识已存在");
}
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, role.getRoleName())) > 0) {
return fail("角色名称已存在");
}
if (roleService.save(role)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:role:update')")
@Operation(summary = "修改角色")
@PutMapping()
public ApiResult<?> update(@RequestBody Role role) {
if (role.getRoleCode() != null && roleService.count(new LambdaQueryWrapper<Role>()
.eq(Role::getRoleCode, role.getRoleCode())
.ne(Role::getRoleId, role.getRoleId())) > 0) {
return fail("角色标识已存在");
}
if (role.getRoleName() != null && roleService.count(new LambdaQueryWrapper<Role>()
.eq(Role::getRoleName, role.getRoleName())
.ne(Role::getRoleId, role.getRoleId())) > 0) {
return fail("角色名称已存在");
}
if (roleService.updateById(role)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:role:remove')")
@Operation(summary = "删除角色")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (roleService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:role:save')")
@Operation(summary = "批量添加角色")
@PostMapping("/batch")
public ApiResult<List<String>> saveBatch(@RequestBody List<Role> list) {
// 校验是否重复
if (CommonUtil.checkRepeat(list, Role::getRoleName)) {
return fail("角色名称存在重复", null);
}
if (CommonUtil.checkRepeat(list, Role::getRoleCode)) {
return fail("角色标识存在重复", null);
}
// 校验是否存在
List<Role> codeExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleCode,
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
if (codeExists.size() > 0) {
return fail("角色标识已存在", codeExists.stream().map(Role::getRoleCode)
.collect(Collectors.toList())).setCode(2);
}
List<Role> nameExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleName,
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
if (nameExists.size() > 0) {
return fail("角色标识已存在", nameExists.stream().map(Role::getRoleCode)
.collect(Collectors.toList())).setCode(3);
}
if (roleService.saveBatch(list)) {
return success("添加成功", null);
}
return fail("添加失败", null);
}
@PreAuthorize("hasAuthority('sys:role:remove')")
@Operation(summary = "批量删除角色")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (roleService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,96 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.RoleMenu;
import com.gxwebsoft.common.system.service.MenuService;
import com.gxwebsoft.common.system.service.RoleMenuService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* 角色菜单控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:01
*/
@Tag(name = "角色菜单管理")
@RestController
@RequestMapping("/api/system/role-menu")
public class RoleMenuController extends BaseController {
@Resource
private RoleMenuService roleMenuService;
@Resource
private MenuService menuService;
@PreAuthorize("hasAuthority('sys:role:list')")
@Operation(summary = "查询角色菜单")
@GetMapping("/{id}")
public ApiResult<List<Menu>> list(@PathVariable("id") Integer roleId) {
List<Menu> menus = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSortNumber));
List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
.eq(RoleMenu::getRoleId, roleId));
for (Menu menu : menus) {
menu.setChecked(roleMenus.stream().anyMatch((d) -> d.getMenuId().equals(menu.getMenuId())));
}
return success(menus);
}
@Transactional(rollbackFor = {Exception.class})
@PreAuthorize("hasAuthority('sys:role:update')")
@Operation(summary = "修改角色菜单")
@PutMapping("/{id}")
public ApiResult<?> update(@PathVariable("id") Integer roleId, @RequestBody List<Integer> menuIds) {
roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
if (menuIds != null && menuIds.size() > 0) {
List<RoleMenu> roleMenuList = new ArrayList<>();
for (Integer menuId : menuIds) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenuList.add(roleMenu);
}
if (!roleMenuService.saveBatch(roleMenuList)) {
throw new BusinessException("保存失败");
}
}
return success("保存成功");
}
@PreAuthorize("hasAuthority('sys:role:update')")
@Operation(summary = "添加角色菜单")
@PostMapping("/{id}")
public ApiResult<?> addRoleAuth(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
if (roleMenuService.save(roleMenu)) {
return success();
}
return fail();
}
@PreAuthorize("hasAuthority('sys:role:update')")
@Operation(summary = "移除角色菜单")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
if (roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>()
.eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMenuId, menuId))) {
return success();
}
return fail();
}
}

View File

@@ -0,0 +1,178 @@
package com.gxwebsoft.common.system.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.Setting;
import com.gxwebsoft.common.system.entity.Tenant;
import com.gxwebsoft.common.system.param.SettingParam;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.common.system.service.TenantService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 系统设置控制器
*
* @author WebSoft
* @since 2022-11-19 13:54:27
*/
@Tag(name = "系统设置管理")
@RestController
@RequestMapping("/api/system/setting")
public class SettingController extends BaseController {
@Resource
private SettingService settingService;
@Resource
private TenantService tenantService;
@Resource
private RedisUtil redisUtil;
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "分页查询系统设置")
@GetMapping("/page")
public ApiResult<PageResult<Setting>> page(SettingParam param) {
// 使用关联查询
return success(settingService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "查询全部系统设置")
@GetMapping()
public ApiResult<List<Setting>> list(SettingParam param) {
// 使用关联查询
return success(settingService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "根据id查询系统设置")
@GetMapping("/{id}")
public ApiResult<Setting> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(settingService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "添加系统设置")
@PostMapping()
public ApiResult<?> save(@RequestBody Setting setting) {
if (settingService.save(setting)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "修改系统设置")
@PutMapping()
public ApiResult<?> update(@RequestBody Setting setting) {
if (settingService.updateById(setting)) {
// 更新系统设置信息到缓存
String key = "setting:" + setting.getSettingKey() + ":" + getTenantId();
System.out.println("key = " + key);
redisUtil.set(key, JSON.parseObject(setting.getContent()));
// 创建微信支付Bean
// settingService.initConfig(setting);
// 更新租户信息
if (setting.getSettingKey().equals("setting")) {
System.out.println("修改系统设置 = " + setting.getContent());
final String content = setting.getContent();
final JSONObject jsonObject = JSONObject.parseObject(content);
final String siteName = jsonObject.getString("siteName");
final String logo = jsonObject.getString("logo");
System.out.println("siteName = " + siteName);
final Tenant tenant = new Tenant();
tenant.setTenantName(siteName);
tenant.setTenantId(getTenantId());
tenant.setLogo(logo);
tenantService.updateById(tenant);
}
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:setting:remove')")
@Operation(summary = "删除系统设置")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (settingService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "批量添加系统设置")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Setting> list) {
if (settingService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:setting:update')")
@Operation(summary = "批量修改系统设置")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Setting> batchParam) {
if (batchParam.update(settingService, "setting_id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:setting:remove')")
@Operation(summary = "批量删除系统设置")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (settingService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:setting:data')")
@Operation(summary = "查询租户设置信息")
@GetMapping("/data")
public ApiResult<?> data() {
return success(settingService.getData("setting"));
}
@PreAuthorize("hasAuthority('sys:setting:save')")
@Operation(summary = "更新主题皮肤")
@PutMapping("/theme")
public ApiResult<?> theme(@RequestBody Setting setting) {
String key = "theme:".concat(getTenantId().toString());
// 新增
final Setting one = settingService.getOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, setting.getSettingKey()));
if(one == null){
settingService.save(setting);
redisUtil.set(key,setting.getContent());
return success("保存成功");
}
// 更新
final Setting update = settingService.getOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, setting.getSettingKey()));
update.setContent(setting.getContent());
if (settingService.updateById(update)) {
redisUtil.set(key,setting.getContent());
return success("更新成功");
}
return fail("更新失败");
}
@Operation(summary = "更新主题皮肤")
@GetMapping("/getTheme")
public ApiResult<?> getTheme() {
String key = "theme:".concat(getTenantId().toString());
return success("获取成功",redisUtil.get(key));
}
}

View File

@@ -0,0 +1,158 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Menu;
import com.gxwebsoft.common.system.entity.RoleMenu;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.MenuService;
import com.gxwebsoft.common.system.service.RoleMenuService;
import com.gxwebsoft.common.system.service.TenantService;
import com.gxwebsoft.common.system.entity.Tenant;
import com.gxwebsoft.common.system.param.TenantParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 租户控制器
*
* @author 科技小王子
* @since 2023-07-17 17:49:53
*/
@Tag(name = "租户管理")
@RestController
@RequestMapping("/api/system/tenant")
public class TenantController extends BaseController {
@Resource
private TenantService tenantService;
@Resource
private MenuService menuService;
@Resource
private RoleMenuService roleMenuService;
@PreAuthorize("hasAuthority('sys:tenant:list')")
@Operation(summary = "分页查询租户")
@GetMapping("/page")
public ApiResult<PageResult<Tenant>> page(TenantParam param) {
// 使用关联查询
return success(tenantService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:tenant:list')")
@Operation(summary = "查询全部租户")
@GetMapping()
public ApiResult<List<Tenant>> list(TenantParam param) {
// 使用关联查询
return success(tenantService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:tenant:list')")
@Operation(summary = "根据id查询租户")
@GetMapping("/{id}")
public ApiResult<Tenant> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(tenantService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:tenant:save')")
@Operation(summary = "添加租户")
@PostMapping()
public ApiResult<?> save(@RequestBody Tenant tenant) {
System.out.println("tenant = " + tenant);
if (tenantService.save(tenant)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:tenant:update')")
@Operation(summary = "修改租户")
@PutMapping()
public ApiResult<?> update(@RequestBody Tenant tenant) {
if (tenantService.updateById(tenant)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:tenant:remove')")
@Operation(summary = "删除租户")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (tenantService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:tenant:save')")
@Operation(summary = "批量添加租户")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Tenant> list) {
if (tenantService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:tenant:update')")
@Operation(summary = "批量修改租户")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Tenant> batchParam) {
if (batchParam.update(tenantService, "tenant_id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:tenant:remove')")
@Operation(summary = "批量删除租户")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (tenantService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@Operation(summary = "租户角色权限初始化")
@GetMapping("/role-menu/{id}")
public ApiResult<List<Menu>> initialization(@PathVariable("id") Integer roleId) {
List<Menu> menus = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSortNumber));
List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
.eq(RoleMenu::getRoleId, roleId));
for (Menu menu : menus) {
menu.setChecked(roleMenus.stream().anyMatch((d) -> d.getMenuId().equals(menu.getMenuId())));
}
List<Integer> menuIds = menus.stream().map(Menu::getMenuId).collect(Collectors.toList());
roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
if (menuIds.size() > 0) {
List<RoleMenu> roleMenuList = new ArrayList<>();
for (Integer menuId : menuIds) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenuList.add(roleMenu);
}
if (!roleMenuService.saveBatch(roleMenuList)) {
throw new BusinessException("保存失败");
}
}
return success(menus);
}
}

View File

@@ -0,0 +1,135 @@
package com.gxwebsoft.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.entity.UserCollection;
import com.gxwebsoft.common.system.param.UserCollectionParam;
import com.gxwebsoft.common.system.service.UserCollectionService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 我的收藏控制器
*
* @author 科技小王子
* @since 2024-04-28 18:08:32
*/
@Tag(name = "用户收藏")
@RestController
@RequestMapping("/api/system/user-collection")
public class UserCollectionController extends BaseController {
@Resource
private UserCollectionService userCollectionService;
@PreAuthorize("hasAuthority('sys:userCollection:list')")
@Operation(summary = "分页查询我的收藏")
@GetMapping("/page")
public ApiResult<PageResult<UserCollection>> page(UserCollectionParam param) {
// 使用关联查询
return success(userCollectionService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:userCollection:list')")
@Operation(summary = "查询全部我的收藏")
@GetMapping()
public ApiResult<List<UserCollection>> list(UserCollectionParam param) {
// 使用关联查询
return success(userCollectionService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:userCollection:list')")
@Operation(summary = "根据id查询我的收藏")
@GetMapping("/{id}")
public ApiResult<UserCollection> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(userCollectionService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:userCollection:save')")
@OperationLog
@Operation(summary = "添加和取消收藏")
@PostMapping()
public ApiResult<?> save(@RequestBody UserCollection userCollection) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
userCollection.setUserId(loginUser.getUserId());
userCollection.setTid(userCollection.getTid());
final UserCollection one = userCollectionService.getOne(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUserId, loginUser.getUserId()).eq(UserCollection::getTid, userCollection.getTid()).last("limit 1"));
if (one != null) {
userCollectionService.removeById(one.getId());
return success("已取消收藏");
}
if (userCollectionService.save(userCollection)) {
return success("已添加收藏");
}
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:userCollection:update')")
@OperationLog
@Operation(summary = "修改我的收藏")
@PutMapping()
public ApiResult<?> update(@RequestBody UserCollection userCollection) {
if (userCollectionService.updateById(userCollection)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:userCollection:remove')")
@OperationLog
@Operation(summary = "删除我的收藏")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (userCollectionService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:userCollection:save')")
@OperationLog
@Operation(summary = "批量添加我的收藏")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<UserCollection> list) {
if (userCollectionService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:userCollection:update')")
@OperationLog
@Operation(summary = "批量修改我的收藏")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<UserCollection> batchParam) {
if (batchParam.update(userCollectionService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:userCollection:remove')")
@OperationLog
@Operation(summary = "批量删除我的收藏")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (userCollectionService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,401 @@
package com.gxwebsoft.common.system.controller;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.*;
import com.gxwebsoft.common.system.param.UserImportParam;
import com.gxwebsoft.common.system.param.UserParam;
import com.gxwebsoft.common.system.service.DictionaryDataService;
import com.gxwebsoft.common.system.service.OrganizationService;
import com.gxwebsoft.common.system.service.RoleService;
import com.gxwebsoft.common.system.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* 用户控制器
*
* @author WebSoft
* @since 2018-12-24 16:10:41
*/
@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/system/user")
public class UserController extends BaseController {
@Resource
private UserService userService;
@Resource
private RoleService roleService;
@Resource
private OrganizationService organizationService;
@Resource
private DictionaryDataService dictionaryDataService;
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "分页查询用户")
@GetMapping("/page")
public ApiResult<PageResult<User>> page(UserParam param) {
return success(userService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "分页查询用户")
@GetMapping("/pageAdminByPhone")
public ApiResult<List<User>> pageAdminByPhone(UserParam param) {
return success(userService.pageAdminByPhone(param));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "查询全部用户")
@GetMapping()
public ApiResult<List<User>> list(UserParam param) {
return success(userService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "根据id查询用户")
@GetMapping("/{id}")
public ApiResult<User> get(@PathVariable("id") Integer id) {
return success(userService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "根据手机号码查询用户")
@GetMapping("/getByPhone/{phone}")
public ApiResult<User> getByPhone(@PathVariable("phone") String phone) {
return success(userService.getByPhone(phone));
}
@PreAuthorize("hasAuthority('sys:user:save')")
@Operation(summary = "添加用户")
@PostMapping()
public ApiResult<?> add(@RequestBody User user) {
user.setStatus(0);
user.setPassword(userService.encodePassword(user.getPassword()));
if (userService.saveUser(user)) {
return success("添加成功",user.getUserId());
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:user:save')")
@Operation(summary = "批量添加用户")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<User> userList) {
userList.forEach(d -> {
d.setStatus(0);
if (d.getPassword() != null) {
d.setPassword(userService.encodePassword(d.getPassword()));
}
});
if (userService.saveBatch(userList)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:user:save')")
@Operation(summary = "批量添加用户并返回userId")
@PostMapping("/batchBackUserId")
public ApiResult<?> saveBatchBackUserId(@RequestBody List<User> userList) {
userList.forEach(d -> {
d.setStatus(0);
d.setPassword(userService.encodePassword(d.getPassword()));
});
final Set<String> phones = userList.stream().map(User::getPhone).collect(Collectors.toSet());
if (userService.saveBatch(userList)) {
final UserParam userParam = new UserParam();
userParam.setPhones(phones);
userParam.setLimit(500L);
final PageResult<User> result = userService.pageRel(userParam);
final Set<Integer> collect = result.getList().stream().map(User::getUserId).collect(Collectors.toSet());
return success("添加成功",collect);
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "修改用户")
@PutMapping()
public ApiResult<?> update(@RequestBody User user) {
user.setStatus(null);
user.setUsername(null);
user.setPassword(null);
if (userService.updateUser(user)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:remove')")
@OperationLog
@Operation(summary = "删除用户")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (userService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "批量修改用户")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<User> batchParam) {
if (batchParam.update(userService, User::getUserId)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:remove')")
@OperationLog
@Operation(summary = "批量删除用户")
@Transactional(rollbackFor = {Exception.class})
@DeleteMapping("/batch")
public ApiResult<?> deleteBatch(@RequestBody List<Integer> ids) {
if (userService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "修改用户状态")
@PutMapping("/status")
public ApiResult<?> updateStatus(@RequestBody User user) {
if (user.getUserId() == null || user.getStatus() == null || !Arrays.asList(0, 1).contains(user.getStatus())) {
return fail("参数不正确");
}
User u = new User();
u.setUserId(user.getUserId());
u.setStatus(user.getStatus());
if (userService.updateById(u)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "修改推荐状态")
@PutMapping("/recommend")
public ApiResult<?> updateRecommend(@RequestBody User user) {
if (user.getUserId() == null || user.getRecommend() == null || !Arrays.asList(0, 1).contains(user.getRecommend())) {
return fail("参数不正确");
}
User u = new User();
u.setUserId(user.getUserId());
u.setRecommend(user.getRecommend());
if (userService.updateById(u)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "批量修改用户状态")
@PutMapping("/status/batch")
public ApiResult<?> updateStatusBatch(@RequestBody BatchParam<Integer> batchParam) {
if (!Arrays.asList(0, 1).contains(batchParam.getData())) {
return fail("状态值不正确");
}
if (userService.update(new LambdaUpdateWrapper<User>()
.in(User::getUserId, batchParam.getIds())
.set(User::getStatus, batchParam.getData()))) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "重置密码")
@PutMapping("/password")
public ApiResult<?> resetPassword(@RequestBody User user) {
if (user.getUserId() == null || StrUtil.isBlank(user.getPassword())) {
return fail("参数不正确");
}
User u = new User();
u.setUserId(user.getUserId());
u.setPassword(userService.encodePassword(user.getPassword()));
if (userService.updateById(u)) {
return success("重置成功");
} else {
return fail("重置失败");
}
}
@PreAuthorize("hasAuthority('sys:user:update')")
@OperationLog
@Operation(summary = "批量重置密码")
@PutMapping("/password/batch")
public ApiResult<?> resetPasswordBatch(@RequestBody BatchParam<String> batchParam) {
if (batchParam.getIds() == null || batchParam.getIds().size() == 0) {
return fail("请选择用户");
}
if (batchParam.getData() == null) {
return fail("请输入密码");
}
if (userService.update(new LambdaUpdateWrapper<User>()
.in(User::getUserId, batchParam.getIds())
.set(User::getPassword, userService.encodePassword(batchParam.getData())))) {
return success("重置成功");
} else {
return fail("重置失败");
}
}
@Operation(summary = "检查用户是否存在")
@GetMapping("/existence")
public ApiResult<?> existence(ExistenceParam<User> param) {
if (param.isExistence(userService, User::getUserId)) {
return success(param.getValue() + "已存在");
}
return fail(param.getValue() + "不存在");
}
/**
* excel导入用户
*/
@PreAuthorize("hasAuthority('sys:user:save')")
@Operation(summary = "导入用户")
@Transactional(rollbackFor = {Exception.class})
@PostMapping("/import")
public ApiResult<List<String>> importBatch(MultipartFile file) {
ImportParams importParams = new ImportParams();
try {
List<UserImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(),
UserImportParam.class, importParams);
// 校验是否重复
if (CommonUtil.checkRepeat(list, UserImportParam::getUsername)) {
return fail("账号存在重复", null);
}
if (CommonUtil.checkRepeat(list, UserImportParam::getPhone)) {
return fail("手机号存在重复", null);
}
// 校验是否存在
List<User> usernameExists = userService.list(new LambdaQueryWrapper<User>().in(User::getUsername,
list.stream().map(UserImportParam::getUsername).collect(Collectors.toList())));
if (usernameExists.size() > 0) {
return fail("账号已经存在",
usernameExists.stream().map(User::getUsername).collect(Collectors.toList()));
}
List<User> phoneExists = userService.list(new LambdaQueryWrapper<User>().in(User::getPhone,
list.stream().map(UserImportParam::getPhone).collect(Collectors.toList())));
if (phoneExists.size() > 0) {
return fail("手机号已经存在",
phoneExists.stream().map(User::getPhone).collect(Collectors.toList()));
}
// 添加
List<User> users = new ArrayList<>();
for (UserImportParam one : list) {
User u = new User();
u.setStatus(0);
u.setUsername(one.getUsername());
u.setPassword(userService.encodePassword(one.getPassword()));
u.setNickname(one.getNickname());
u.setPhone(one.getPhone());
Role role = roleService.getOne(new QueryWrapper<Role>()
.eq("role_name", one.getRoleName()), false);
if (role == null) {
return fail("角色不存在", Collections.singletonList(one.getRoleName()));
} else {
u.setRoles(Collections.singletonList(role));
}
Organization organization = organizationService.getOne(new QueryWrapper<Organization>()
.eq("organization_full_name", one.getOrganizationName()), false);
if (organization == null) {
return fail("机构不存在", Collections.singletonList(one.getOrganizationName()));
} else {
u.setOrganizationId(organization.getOrganizationId());
}
DictionaryData sex = dictionaryDataService.getByDictCodeAndName("sex", one.getSexName());
if (sex == null) {
return fail("性别不存在", Collections.singletonList(one.getSexName()));
} else {
u.setSex(sex.getDictDataCode());
}
}
if (userService.saveBatch(users)) {
return success("导入成功", null);
}
} catch (Exception e) {
e.printStackTrace();
}
return fail("导入失败", null);
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@PostMapping("/getAvatarByMpWx")
@Operation(summary = "更新微信头像")
public ApiResult<?> getAvatarByMpWx(@RequestBody User user){
user.setAvatar("https://oa.gxwebsoft.com/assets/logo.7ccfefb9.svg");
if (userService.updateUser(user)) {
return success("更新成功");
}
return fail("更新失败");
}
@PostMapping("/updatePointsBySign")
@Operation(summary = "签到成功累加积分")
public ApiResult<?> updatePointsBySign(){
final User loginUser = getLoginUser();
loginUser.setPoints(loginUser.getPoints() + 1);
if (userService.updateUser(loginUser)) {
return success("签到成功");
}
return fail("签到失败");
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@PutMapping("/updateUserBalance")
@Operation(summary = "更新用户余额")
public ApiResult<?> updateUserBalance(@RequestBody User user){
if (getLoginUser() == null) {
return fail("请先登录");
}
if (userService.updateUser(user)) {
return success("操作成功");
}
return fail("操作失败");
}
@PreAuthorize("hasAuthority('sys:user:list')")
@OperationLog
@Operation(summary = "统计用户余额")
@GetMapping("/countUserBalance")
public ApiResult<?> countUserBalance(User param) {
final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.gt(User::getBalance, 0);
if (!param.getOrganizationId().equals(0)) {
wrapper.eq(User::getOrganizationId,param.getOrganizationId());
}
final List<User> list = userService.list(wrapper);
final BigDecimal totalBalance = list.stream().map(User::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
// System.out.println("统计用户余额 = " + totalBalance);
return success("统计成功",totalBalance);
}
}

View File

@@ -0,0 +1,158 @@
package com.gxwebsoft.common.system.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.utils.FileServerUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.service.UserFileService;
import com.gxwebsoft.common.system.entity.UserFile;
import com.gxwebsoft.common.system.param.UserFileParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 用户文件控制器
*
* @author WebSoft
* @since 2022-07-21 14:34:40
*/
@Tag(name = "用户文件管理")
@RestController
@RequestMapping("/api/system/user-file")
public class UserFileController extends BaseController {
@Resource
private UserFileService userFileService;
@Operation(summary = "分页查询用户文件")
@GetMapping("/page")
public ApiResult<PageResult<UserFile>> page(UserFileParam param, HttpServletRequest request) {
param.setUserId(getLoginUserId());
PageParam<UserFile, UserFileParam> page = new PageParam<>(param);
page.setDefaultOrder("is_directory desc");
PageParam<UserFile, UserFileParam> result = userFileService.page(page, page.getWrapper());
List<UserFile> records = result.getRecords();
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/system/user-file") + "/file";
for (UserFile record : records) {
if (StrUtil.isNotBlank(record.getPath())) {
record.setUrl(requestURL + "/" + record.getPath());
if (FileServerUtil.isImage(record.getContentType())) {
record.setThumbnail(requestURL + "/thumbnail/" + record.getPath());
}
record.setDownloadUrl(requestURL + "/download/" + record.getPath());
}
}
return success(records, result.getTotal());
}
@Operation(summary = "查询全部用户文件")
@GetMapping()
public ApiResult<List<UserFile>> list(UserFileParam param, HttpServletRequest request) {
param.setUserId(getLoginUserId());
PageParam<UserFile, UserFileParam> page = new PageParam<>(param);
page.setDefaultOrder("is_directory desc");
List<UserFile> records = userFileService.list(page.getOrderWrapper());
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/system/user-file") + "/file";
for (UserFile record : records) {
if (StrUtil.isNotBlank(record.getPath())) {
record.setUrl(requestURL + "/" + record.getPath());
if (FileServerUtil.isImage(record.getContentType())) {
record.setThumbnail(requestURL + "/thumbnail/" + record.getPath());
}
record.setDownloadUrl(requestURL + "/download/" + record.getPath());
}
}
return success(records);
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "添加用户文件")
@PostMapping()
public ApiResult<?> save(@RequestBody UserFile userFile) {
userFile.setUserId(getLoginUserId());
if (userFile.getParentId() == null) {
userFile.setParentId(0);
}
if (userFile.getIsDirectory() != null && userFile.getIsDirectory().equals(1)) {
if (userFileService.count(new LambdaQueryWrapper<UserFile>()
.eq(UserFile::getName, userFile.getName())
.eq(UserFile::getParentId, userFile.getParentId())
.eq(UserFile::getUserId, userFile.getUserId())) > 0) {
return fail("文件夹名称已存在");
}
}
if (userFileService.save(userFile)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "修改用户文件")
@PutMapping()
public ApiResult<?> update(@RequestBody UserFile userFile) {
Integer loginUserId = getLoginUserId();
UserFile old = userFileService.getById(userFile.getId());
UserFile entity = new UserFile();
if (StrUtil.isNotBlank(userFile.getName())) {
entity.setName(userFile.getName());
}
if (userFile.getParentId() != null) {
entity.setParentId(userFile.getParentId());
}
if (!old.getUserId().equals(loginUserId) ||
(entity.getName() == null && entity.getParentId() == null)) {
return fail("修改失败");
}
if (old.getIsDirectory() != null && old.getIsDirectory().equals(1)) {
if (userFileService.count(new LambdaQueryWrapper<UserFile>()
.eq(UserFile::getName, entity.getName() == null ? old.getName() : entity.getName())
.eq(UserFile::getParentId, entity.getParentId() == null ? old.getParentId() : entity.getParentId())
.eq(UserFile::getUserId, loginUserId)
.ne(UserFile::getId, old.getId())) > 0) {
return fail("文件夹名称已存在");
}
}
if (userFileService.update(entity, new LambdaUpdateWrapper<UserFile>()
.eq(UserFile::getId, userFile.getId())
.eq(UserFile::getUserId, loginUserId))) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "删除用户文件")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (userFileService.remove(new LambdaUpdateWrapper<UserFile>()
.eq(UserFile::getId, id)
.eq(UserFile::getUserId, getLoginUserId()))) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:auth:user')")
@Operation(summary = "批量删除用户文件")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (userFileService.remove(new LambdaUpdateWrapper<UserFile>()
.in(UserFile::getId, ids)
.eq(UserFile::getUserId, getLoginUserId()))) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,183 @@
package com.gxwebsoft.common.system.controller;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.entity.UserReferee;
import com.gxwebsoft.common.system.param.UserRefereeParam;
import com.gxwebsoft.common.system.service.UserRefereeService;
import com.gxwebsoft.common.system.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 用户推荐关系表控制器
*
* @author 科技小王子
* @since 2023-10-07 22:56:36
*/
@Tag(name = "用户")
@RestController
@RequestMapping("/api/system/user-referee")
public class UserRefereeController extends BaseController {
@Resource
private UserRefereeService userRefereeService;
@Resource
private UserService userService;
@PreAuthorize("hasAuthority('sys:userReferee:list')")
@OperationLog
@Operation(summary = "分页查询用户推荐关系表")
@GetMapping("/page")
public ApiResult<PageResult<UserReferee>> page(UserRefereeParam param) {
// 使用关联查询
return success(userRefereeService.pageRel(param));
}
@PreAuthorize("hasAuthority('sys:userReferee:list')")
@OperationLog
@Operation(summary = "查询全部用户推荐关系表")
@GetMapping()
public ApiResult<List<UserReferee>> list(UserRefereeParam param) {
// 使用关联查询
return success(userRefereeService.listRel(param));
}
@PreAuthorize("hasAuthority('sys:userReferee:list')")
@OperationLog
@Operation(summary = "根据id查询用户推荐关系表")
@GetMapping("/{id}")
public ApiResult<UserReferee> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(userRefereeService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('sys:userReferee:save')")
@OperationLog
@Operation(summary = "添加用户推荐关系表")
@PostMapping()
public ApiResult<?> save(@RequestBody UserReferee userReferee) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
userReferee.setUserId(loginUser.getUserId());
}
if (userRefereeService.save(userReferee)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:userReferee:update')")
@OperationLog
@Operation(summary = "修改用户推荐关系表")
@PutMapping()
public ApiResult<?> update(@RequestBody UserReferee userReferee) {
if (userRefereeService.updateById(userReferee)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:userReferee:remove')")
@OperationLog
@Operation(summary = "删除用户推荐关系表")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (userRefereeService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('sys:userReferee:save')")
@OperationLog
@Operation(summary = "批量添加用户推荐关系表")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<UserReferee> list) {
if (userRefereeService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('sys:userReferee:update')")
@OperationLog
@Operation(summary = "批量修改用户推荐关系表")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<UserReferee> batchParam) {
if (batchParam.update(userRefereeService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('sys:userReferee:remove')")
@OperationLog
@Operation(summary = "批量删除用户推荐关系表")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (userRefereeService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@Operation(summary = "查询推荐人信息")
@GetMapping("/getReferee/{id}")
public ApiResult<User> getReferee(@PathVariable("id") Integer id) {
if (id == null) {
return fail("参数错误", null);
}
final UserReferee referee = userRefereeService.getOne(new LambdaQueryWrapper<UserReferee>()
.eq(UserReferee::getUserId, id)
.eq(UserReferee::getDeleted, 0));
if (ObjectUtil.isEmpty(referee)) {
return fail("查询失败", null);
}
final User user = userService.getByIdRel(referee.getDealerId());
if (ObjectUtil.isNotEmpty(user)) {
return success(user);
}
return fail("查询失败", null);
}
@Operation(summary = "查询推荐人列表")
@GetMapping("/getRefereeList/{id}")
public ApiResult<List<User>> getRefereeList(@PathVariable("id") Integer id) {
if (id == null) {
return fail("参数错误", null);
}
final List<UserReferee> refereeList = userRefereeService.list(new LambdaQueryWrapper<UserReferee>()
.eq(UserReferee::getDealerId, id)
.eq(UserReferee::getDeleted, 0));
if (ObjectUtil.isEmpty(refereeList)) {
return fail("查询失败", null);
}
final List<User> users = userService.list(
new LambdaQueryWrapper<User>()
.in(User::getUserId, refereeList.stream().map(UserReferee::getUserId).toList())
);
if (ObjectUtil.isNotEmpty(users)) {
return success(users);
}
return fail("查询失败", null);
}
}

Some files were not shown because too many files have changed in this diff Show More