fix(优惠券中心):携程订单接口对接第一版完成对接

This commit is contained in:
2025-08-07 16:13:04 +08:00
parent 6a0161e1dd
commit 626f2707fa
13 changed files with 1098 additions and 430 deletions
@@ -0,0 +1,129 @@
# 数据库设置指南
## 快速设置
### 1. 连接到MySQL
```bash
mysql -u your_username -p
```
### 2. 执行初始化脚本
```sql
-- 在MySQL命令行中执行
source sql/create_ctrip_order_tables.sql;
```
或者手动执行:
```sql
-- 创建数据库
CREATE DATABASE IF NOT EXISTS `coupon-center` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 使用数据库
USE `coupon-center`;
-- 然后执行 sql/create_ctrip_order_tables.sql 中的所有建表语句
```
### 3. 验证表创建
```sql
-- 查看所有表
SHOW TABLES;
-- 查看优惠券表结构
DESCRIBE t_coupon;
-- 查看测试数据
SELECT * FROM t_coupon;
```
## 表结构说明
### 主要表
1. **t_coupon** - 优惠券主表
- 存储用户优惠券信息
- 包含状态、有效期、使用记录等
2. **t_ctrip_order** - 携程订单表
- 存储携程订单信息
- 包含订单状态、金额、联系人等
3. **t_ctrip_order_item** - 携程订单项目表
- 存储订单中的具体项目
- 包含项目名称、数量、价格等
4. **t_ctrip_passenger** - 携程乘客表
- 存储乘客信息
- 包含姓名、证件、联系方式等
5. **t_ctrip_contact** - 携程联系人表
- 存储联系人信息
- 包含姓名、手机、邮箱等
### 关联表
6. **t_ctrip_coupon** - 携程优惠券表
7. **t_ctrip_voucher** - 携程凭证表
8. **t_ctrip_refund** - 携程退款表
9. **t_ctrip_refund_item** - 携程退款项目表
10. **t_ctrip_consumed** - 携程核销表
11. **t_ctrip_consumed_passenger** - 携程核销乘客表
12. **t_ctrip_consumed_voucher** - 携程核销凭证表
## 索引说明
### 主要索引
- **t_coupon**: `idx_user_phone`, `idx_ctrip_coupon_id`, `idx_status`, `idx_valid_end_time`
- **t_ctrip_order**: `uk_sequence_id`, `idx_ota_order_id`, `idx_order_status`
- **t_ctrip_order_item**: `uk_order_item`, `idx_order_id`
- **t_ctrip_passenger**: `idx_order_id`, `idx_item_id`, `idx_passenger_id`
## 数据清理
如果需要重新初始化数据库:
```sql
-- 删除所有表(谨慎操作)
DROP DATABASE IF EXISTS `coupon-center`;
-- 重新创建
CREATE DATABASE `coupon-center` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `coupon-center`;
-- 重新执行建表脚本
source sql/create_ctrip_order_tables.sql;
```
## 常见问题
### Q: 表已存在错误
A: 使用 `CREATE TABLE IF NOT EXISTS` 语句,或者先删除表再创建。
### Q: 字符集错误
A: 确保使用 `utf8mb4` 字符集,支持完整的Unicode字符。
### Q: 权限错误
A: 确保数据库用户有创建数据库和表的权限。
### Q: 外键约束错误
A: 当前设计没有使用外键约束,避免复杂的依赖关系。
## 测试数据
初始化脚本会自动插入一条测试数据:
```sql
INSERT INTO `t_coupon` (`coupon_name`, `coupon_type`, `amount`, `user_phone`, `status`, `valid_start_time`, `valid_end_time`, `create_by`)
VALUES ('测试优惠券', 'DISCOUNT', 10.00, '18322694510', 'UNUSED', NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), 'system');
```
可以通过以下命令验证:
```sql
SELECT * FROM t_coupon WHERE user_phone = '18322694510';
```
+190 -232
View File
@@ -1,267 +1,225 @@
# 携程优惠券业务对接系统
# 优惠券中心服务 (Coupon Center Service)
## 项目概述
## 项目简介
本项目是携程优惠券业务对接系统,实现了与携程平台的优惠券业务集成,包括优惠券创建、核销、取消等完整业务流程。
优惠券中心服务是一个基于Spring Boot的微服务,专门处理优惠券相关的业务逻辑,包括与携程API的集成。
## 功能特性
### 核心功能
- ✅ **携程优惠券创建** - 支持携程下单后回调创建用户优惠券
- ✅ **智能优惠券选择** - 根据订单金额智能选择最优优惠券
- ✅ **优惠券核销** - 完整的核销流程,包括携程API调用和本地状态更新
- ✅ **优惠券取消** - 支持指定优惠券或默认取消第一个可用券
- ✅ **优惠券状态查询** - 实时查询优惠券状态
- ✅ **过期优惠券处理** - 定时任务自动处理过期优惠券
- ✅ 优惠券管理(创建、查询、使用、过期处理)
- ✅ 携程API集成(订单创建、退款、核销通知)
- ✅ AES加密/解密支持
- ✅ MD5签名验证
- ✅ 多租户支持
- ✅ 软删除支持
### 技术特性
- 🔐 **安全加密** - AES-128-CBC加密和MD5签名验证
- 🔄 **重试机制** - API调用失败自动重试
- 📊 **幂等性保证** - 防止重复处理
- 🎯 **智能选择** - 优惠券优先级算法
- 📝 **完整日志** - 详细的操作日志记录
- 🧪 **单元测试** - 完整的测试覆盖
## 技术栈
## 系统架构
- **Spring Boot 3.x**
- **MyBatis Plus**
- **MySQL 8.0**
- **Redis** (可选)
- **Nacos** (服务发现和配置管理)
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 携程平台API │ │ 优惠券服务 │ │ 数据库 │
│ │ │ │ │ │
│ - 创建优惠券 │◄──►│ - 业务逻辑处理 │◄──►│ - t_coupon │
│ - 核销优惠券 │ │ - 数据验证 │ │ - t_ctrip_* │
│ - 取消优惠券 │ │ - 状态管理 │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
## 快速开始
### 1. 数据库初始化
首先需要创建数据库和表结构:
```bash
# 连接到MySQL数据库
mysql -u your_username -p
# 执行数据库初始化脚本
source sql/create_ctrip_order_tables.sql
```
## 数据库设计
或者手动执行:
### 核心表结构
#### t_coupon (优惠券主表)
```sql
- id: 主键ID
- coupon_no: 优惠券编号
- coupon_name: 优惠券名称
- coupon_type: 优惠券类型(1-满减券,2-折扣券,3-免费券)
- amount: 优惠券面额
- min_amount: 使用门槛金额
- discount_rate: 折扣率
- status: 状态(0-未使用,1-已使用,2-已过期,3-已作废)
- user_phone: 用户手机号
- source: 来源(1-携程,2-高飞自建)
- ctrip_coupon_id: 携程优惠券ID
- valid_start_time/valid_end_time: 有效期
- used_time/used_order_no: 使用时间和订单号
- cancel_time: 退券时间
-- 创建数据库
CREATE DATABASE IF NOT EXISTS `coupon-center` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 使用数据库
USE `coupon-center`;
-- 执行sql/create_ctrip_order_tables.sql中的所有建表语句
```
#### t_ctrip_* (携程相关表)
- `t_ctrip_order` - 携程订单表
- `t_ctrip_coupon` - 携程优惠券信息表
- `t_ctrip_refund` - 携程退款表
- `t_ctrip_consumed` - 携程核销表
### 2. 配置数据库连接
修改 `application.yml` 中的数据库配置:
```yaml
spring:
datasource:
url: jdbc:mysql://your_mysql_host:3306/coupon-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: your_username
password: your_password
```
### 3. 配置携程API参数
确保 `application.yml` 中的携程API配置正确:
```yaml
ctrip:
aes:
key: 087b36ad0dff7942 # AES密钥
iv: 750e15a31356a99d # AES IV
sign:
key: ce6033ae31124ec5cdab3d2bc79f2622 # 签名密钥
```
### 4. 启动服务
```bash
# 编译项目
mvn clean compile
# 启动服务
mvn spring-boot:run
```
或者打包后运行:
```bash
# 打包
mvn clean package
# 运行jar包
java -jar target/coupon-center.jar
```
## API接口
### 1. 携程创建优惠券接口
```http
POST /coupon/ctrip/create
Content-Type: application/json
### 携程相关接口
{
"ctripCouponId": "CTRIP_001",
"userPhone": "13800138000",
"couponName": "满100减50券",
"couponType": 1,
"amount": 50.00,
"minAmount": 100.00,
"validStartTime": "2024-01-01 00:00:00",
"validEndTime": "2024-12-31 23:59:59"
}
#### 创建优惠券
- **URL**: `POST /api-order/coupon/ctrip/create`
- **描述**: 接收携程创建优惠券请求
- **请求格式**: 加密的JSON数据
#### 验证优惠券
- **URL**: `POST /api-order/coupon/ctrip/verify`
- **描述**: 验证优惠券有效性
#### 取消优惠券
- **URL**: `POST /api-order/coupon/ctrip/cancel`
- **描述**: 取消优惠券
#### 查询优惠券状态
- **URL**: `GET /api-order/coupon/ctrip/status/{ctripCouponId}`
- **描述**: 查询优惠券状态
### 测试接口
#### 签名调试
- **URL**: `POST /api-order/coupon/ctrip/test/debug-sign`
- **描述**: 调试签名计算过程
#### 实际请求测试
- **URL**: `POST /api-order/coupon/ctrip/test/real-request`
- **描述**: 测试实际请求数据解析
## 数据库表结构
### 主要表
1. **t_coupon** - 优惠券主表
2. **t_ctrip_order** - 携程订单表
3. **t_ctrip_order_item** - 携程订单项目表
4. **t_ctrip_passenger** - 携程乘客表
5. **t_ctrip_contact** - 携程联系人表
6. **t_ctrip_coupon** - 携程优惠券表
7. **t_ctrip_voucher** - 携程凭证表
8. **t_ctrip_refund** - 携程退款表
9. **t_ctrip_refund_item** - 携程退款项目表
10. **t_ctrip_consumed** - 携程核销表
11. **t_ctrip_consumed_passenger** - 携程核销乘客表
12. **t_ctrip_consumed_voucher** - 携程核销凭证表
## 携程API集成
### 加密解密
服务支持携程的AES-128-CBC加密和自定义编码:
- **AES加密**: 使用CBC模式,PKCS5Padding填充
- **自定义编码**: 非标准Base64编码,使用字母a-p表示4位数据
### 签名验证
使用MD5算法进行签名验证:
```
签名字符串 = accountId + serviceName + requestTime + body + version + signKey
签名 = MD5(签名字符串).toLowerCase()
```
### 2. 核销携程优惠券接口
```http
POST /coupon/ctrip/verify?userPhone=13800138000&orderNo=ORDER_001&orderAmount=300.00
```
## 故障排除
### 3. 取消携程优惠券接口
```http
POST /coupon/ctrip/cancel?userPhone=13800138000&ctripCouponId=CTRIP_001&reason=用户取消
```
### 常见问题
### 4. 查询携程优惠券状态
```http
GET /coupon/ctrip/status/CTRIP_001
```
1. **数据库连接失败**
- 检查数据库配置
- 确保数据库和表已创建
## 配置说明
2. **签名验证失败**
- 检查签名密钥配置
- 使用调试接口分析签名计算过程
### 应用配置 (application.yml)
```yaml
# 携程API配置
ctrip:
aes:
key: your-aes-key-here-16chars
iv: your-aes-iv-here-16chars
md5:
secret: your-md5-secret-here
api:
timeout: 30000
retry-times: 3
base-url: https://api.ctrip.com
account:
id: your-account-id
secret: your-account-secret
```
3. **AES解密失败**
- 检查AES密钥和IV配置
- 确认使用正确的自定义编码
### 环境变量配置
```bash
# 生产环境
export CTRIP_ACCOUNT_ID=your-prod-account-id
export CTRIP_ACCOUNT_SECRET=your-prod-account-secret
export CTRIP_AES_KEY=your-prod-aes-key
export CTRIP_AES_IV=your-prod-aes-iv
export CTRIP_MD5_SECRET=your-prod-md5-secret
```
### 调试工具
## 部署指南
### 1. 环境要求
- JDK 1.8+
- MySQL 5.7+
- Maven 3.6+
### 2. 数据库初始化
```sql
-- 执行数据库迁移脚本
source database_migration.sql
```
### 3. 应用启动
```bash
# 开发环境
mvn spring-boot:run -Dspring.profiles.active=dev
# 生产环境
mvn clean package
java -jar target/coupon-center.jar --spring.profiles.active=prod
```
### 4. 健康检查
```bash
curl http://localhost:8082/coupon-center/actuator/health
```
## 监控和日志
### 日志配置
- 应用日志:`logs/coupon-center.log`
- 日志级别:开发环境 DEBUG,生产环境 INFO
### 监控指标
- 优惠券创建成功率
- 优惠券核销成功率
- API调用响应时间
- 数据库连接状态
### 定时任务
- 过期优惠券处理:每天凌晨2点
- 即将过期优惠券检查:每小时
## 测试
### 单元测试
```bash
mvn test
```
### 集成测试
```bash
mvn test -Dspring.profiles.active=test
```
### API测试
```bash
# 创建优惠券测试
curl -X POST http://localhost:8082/coupon-center/coupon/ctrip/create \
-H "Content-Type: application/json" \
-d '{
"ctripCouponId": "TEST_001",
"userPhone": "13800138000",
"couponName": "测试优惠券",
"couponType": 1,
"amount": 100.00,
"minAmount": 200.00,
"validStartTime": "2024-01-01 00:00:00",
"validEndTime": "2024-12-31 23:59:59"
}'
```
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| COUPON_NOT_FOUND | 优惠券不存在 |
| COUPON_INVALID | 优惠券状态不正确 |
| COUPON_EXPIRED | 优惠券已过期 |
| COUPON_USAGE_ERROR | 优惠券使用条件不满足 |
| COUPON_VERIFY_FAILED | 携程核销失败 |
| COUPON_UPDATE_FAILED | 更新优惠券状态失败 |
| COUPON_PARAM_ERROR | 参数错误 |
| SYSTEM_ERROR | 系统异常 |
- **签名调试**: `/api-order/coupon/ctrip/test/debug-sign`
- **AES测试**: `/api-order/coupon/ctrip/test/aes`
- **配置验证**: `/api-order/coupon/ctrip/test/aes-config`
## 开发指南
### 代码结构
```
src/main/java/com/central/coupon/
├── controller/ # 控制器层
├── service/ # 服务层
├── entity/ # 实体类
├── mapper/ # 数据访问层
├── config/ # 配置类
├── exception/ # 异常处理
├── task/ # 定时任务
└── util/ # 工具类
### 添加新的API接口
1. 在 `controller` 包中创建控制器
2. 在 `service` 包中实现业务逻辑
3. 在 `mapper` 包中定义数据访问方法
4. 在 `entity` 包中定义实体类
### 数据库迁移
1. 创建新的SQL脚本
2. 更新实体类和Mapper
3. 测试数据访问功能
## 部署
### Docker部署
```dockerfile
FROM openjdk:17-jre-slim
COPY target/coupon-center.jar app.jar
EXPOSE 8002
ENTRYPOINT ["java", "-jar", "/app.jar"]
```
### 开发规范
1. **命名规范** - 使用驼峰命名法
2. **注释规范** - 类和方法必须有注释
3. **异常处理** - 使用自定义异常类
4. **日志记录** - 关键操作必须记录日志
5. **单元测试** - 核心业务逻辑必须有测试
### 环境变量
### 提交规范
```
feat: 新功能
fix: 修复bug
docs: 文档更新
style: 代码格式调整
refactor: 重构
test: 测试相关
chore: 构建过程或辅助工具的变动
```bash
# 数据库配置
ZLT_DATASOURCE_IP=your_mysql_host
ZLT_DATASOURCE_USERNAME=your_username
ZLT_DATASOURCE_PASSWORD=your_password
# 携程API配置
CTRIP_AES_KEY=087b36ad0dff7942
CTRIP_AES_IV=750e15a31356a99d
CTRIP_SIGN_KEY=ce6033ae31124ec5cdab3d2bc79f2622
```
## 常见问题
## 许可证
### Q: 携程API调用失败怎么办?
A: 检查网络连接、API配置、签名验证等,系统会自动重试3次。
### Q: 优惠券核销失败怎么办?
A: 检查优惠券状态、有效期、使用条件等,查看详细错误日志。
### Q: 如何监控系统状态?
A: 通过健康检查接口和日志文件监控系统状态。
## 联系方式
如有问题,请联系开发团队或查看项目文档。
## 版本历史
- v1.0.0 - 初始版本,实现基础优惠券功能
- v1.1.0 - 添加智能优惠券选择
- v1.2.0 - 完善错误处理和监控
本项目采用 MIT 许可证。
@@ -0,0 +1,278 @@
-- 创建数据库
CREATE DATABASE IF NOT EXISTS `coupon-center` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `coupon-center`;
-- 优惠券表
CREATE TABLE IF NOT EXISTS `t_coupon` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`coupon_name` varchar(100) NOT NULL COMMENT '优惠券名称',
`coupon_type` varchar(20) NOT NULL COMMENT '优惠券类型',
`amount` decimal(10,2) NOT NULL COMMENT '优惠券金额',
`amount_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`user_phone` varchar(20) NOT NULL COMMENT '用户手机号',
`ctrip_coupon_id` varchar(100) DEFAULT NULL COMMENT '携程优惠券ID',
`ctrip_order_id` varchar(100) DEFAULT NULL COMMENT '携程订单ID',
`status` varchar(20) DEFAULT 'UNUSED' COMMENT '状态:UNUSED-未使用,USED-已使用,EXPIRED-已过期,VOIDED-已作废',
`valid_start_time` datetime NOT NULL COMMENT '有效期开始时间',
`valid_end_time` datetime NOT NULL COMMENT '有效期结束时间',
`used_time` datetime DEFAULT NULL COMMENT '使用时间',
`used_order_no` varchar(100) DEFAULT NULL COMMENT '使用订单号',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_user_phone` (`user_phone`),
KEY `idx_ctrip_coupon_id` (`ctrip_coupon_id`),
KEY `idx_status` (`status`),
KEY `idx_valid_end_time` (`valid_end_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='优惠券表';
-- 携程订单表
CREATE TABLE IF NOT EXISTS `t_ctrip_order` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`ota_order_id` varchar(100) NOT NULL COMMENT 'OTA订单ID',
`sequence_id` varchar(100) NOT NULL COMMENT '序列号ID',
`order_status` varchar(20) DEFAULT 'PENDING' COMMENT '订单状态',
`total_amount` decimal(10,2) DEFAULT NULL COMMENT '订单总金额',
`total_amount_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`contact_name` varchar(50) DEFAULT NULL COMMENT '联系人姓名',
`contact_phone` varchar(20) DEFAULT NULL COMMENT '联系人电话',
`contact_email` varchar(100) DEFAULT NULL COMMENT '联系人邮箱',
`contact_type` varchar(20) DEFAULT NULL COMMENT '联系人类型',
`order_create_time` datetime DEFAULT NULL COMMENT '订单创建时间',
`order_last_confirm_time` datetime DEFAULT NULL COMMENT '订单最后确认时间',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_sequence_id` (`sequence_id`),
KEY `idx_ota_order_id` (`ota_order_id`),
KEY `idx_order_status` (`order_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程订单表';
-- 携程订单项目表
CREATE TABLE IF NOT EXISTS `t_ctrip_order_item` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`item_id` varchar(100) NOT NULL COMMENT '项目ID',
`item_name` varchar(200) DEFAULT NULL COMMENT '项目名称',
`item_type` varchar(50) DEFAULT NULL COMMENT '项目类型',
`quantity` int(11) DEFAULT 1 COMMENT '数量',
`unit_price` decimal(10,2) DEFAULT NULL COMMENT '单价',
`total_price` decimal(10,2) DEFAULT NULL COMMENT '总价',
`total_price_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_item` (`order_id`, `item_id`),
KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程订单项目表';
-- 携程乘客表
CREATE TABLE IF NOT EXISTS `t_ctrip_passenger` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`item_id` varchar(100) NOT NULL COMMENT '项目ID',
`passenger_id` varchar(100) NOT NULL COMMENT '乘客ID',
`passenger_name` varchar(50) NOT NULL COMMENT '乘客姓名',
`passenger_type` varchar(20) DEFAULT NULL COMMENT '乘客类型',
`id_type` varchar(20) DEFAULT NULL COMMENT '证件类型',
`id_number` varchar(50) DEFAULT NULL COMMENT '证件号码',
`phone` varchar(20) DEFAULT NULL COMMENT '手机号',
`gender` varchar(10) DEFAULT NULL COMMENT '性别',
`birth_date` date DEFAULT NULL COMMENT '出生日期',
`age_type` varchar(20) DEFAULT NULL COMMENT '年龄类型',
`nationality_code` varchar(10) DEFAULT NULL COMMENT '国籍代码',
`nationality_name` varchar(50) DEFAULT NULL COMMENT '国籍名称',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_item_id` (`item_id`),
KEY `idx_passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程乘客表';
-- 携程联系人表
CREATE TABLE IF NOT EXISTS `t_ctrip_contact` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`name` varchar(50) NOT NULL COMMENT '联系人姓名',
`mobile` varchar(20) NOT NULL COMMENT '手机号',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱',
`intl_code` varchar(10) DEFAULT '+86' COMMENT '国际区号',
`optional_mobile` varchar(20) DEFAULT NULL COMMENT '备用手机号',
`optional_intl_code` varchar(10) DEFAULT NULL COMMENT '备用国际区号',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程联系人表';
-- 携程优惠券表
CREATE TABLE IF NOT EXISTS `t_ctrip_coupon` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`coupon_id` varchar(100) NOT NULL COMMENT '优惠券ID',
`coupon_type` varchar(20) DEFAULT NULL COMMENT '优惠券类型',
`amount` decimal(10,2) DEFAULT NULL COMMENT '优惠券金额',
`amount_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`status` varchar(20) DEFAULT 'UNUSED' COMMENT '状态',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_coupon_id` (`coupon_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程优惠券表';
-- 携程凭证表
CREATE TABLE IF NOT EXISTS `t_ctrip_voucher` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`voucher_id` varchar(100) NOT NULL COMMENT '凭证ID',
`voucher_type` varchar(20) DEFAULT NULL COMMENT '凭证类型',
`voucher_code` varchar(100) DEFAULT NULL COMMENT '凭证码',
`status` varchar(20) DEFAULT 'UNUSED' COMMENT '状态',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_voucher_id` (`voucher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程凭证表';
-- 携程退款表
CREATE TABLE IF NOT EXISTS `t_ctrip_refund` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`refund_id` varchar(100) NOT NULL COMMENT '退款ID',
`refund_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
`refund_amount_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`refund_status` varchar(20) DEFAULT 'PENDING' COMMENT '退款状态',
`refund_reason` varchar(200) DEFAULT NULL COMMENT '退款原因',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_refund_id` (`refund_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程退款表';
-- 携程退款项目表
CREATE TABLE IF NOT EXISTS `t_ctrip_refund_item` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`refund_id` bigint(20) NOT NULL COMMENT '退款ID',
`item_id` varchar(100) NOT NULL COMMENT '项目ID',
`item_name` varchar(200) DEFAULT NULL COMMENT '项目名称',
`quantity` int(11) DEFAULT 1 COMMENT '数量',
`refund_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
`refund_amount_currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_refund_id` (`refund_id`),
KEY `idx_item_id` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程退款项目表';
-- 携程核销表
CREATE TABLE IF NOT EXISTS `t_ctrip_consumed` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`consumed_id` varchar(100) NOT NULL COMMENT '核销ID',
`total_quantity` int(11) DEFAULT 0 COMMENT '总数量',
`consumed_status` varchar(20) DEFAULT 'PENDING' COMMENT '核销状态',
`consumed_time` datetime DEFAULT NULL COMMENT '核销时间',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_consumed_id` (`consumed_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程核销表';
-- 携程核销乘客表
CREATE TABLE IF NOT EXISTS `t_ctrip_consumed_passenger` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`consumed_id` bigint(20) NOT NULL COMMENT '核销ID',
`passenger_id` varchar(100) NOT NULL COMMENT '乘客ID',
`passenger_name` varchar(50) NOT NULL COMMENT '乘客姓名',
`quantity` int(11) DEFAULT 1 COMMENT '数量',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_consumed_id` (`consumed_id`),
KEY `idx_passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程核销乘客表';
-- 携程核销凭证表
CREATE TABLE IF NOT EXISTS `t_ctrip_consumed_voucher` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
`consumed_id` bigint(20) NOT NULL COMMENT '核销ID',
`voucher_id` varchar(100) NOT NULL COMMENT '凭证ID',
`voucher_code` varchar(100) DEFAULT NULL COMMENT '凭证码',
`quantity` int(11) DEFAULT 1 COMMENT '数量',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_by` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`),
KEY `idx_consumed_id` (`consumed_id`),
KEY `idx_voucher_id` (`voucher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程核销凭证表';
-- 插入测试数据
INSERT INTO `t_coupon` (`coupon_name`, `coupon_type`, `amount`, `user_phone`, `status`, `valid_start_time`, `valid_end_time`, `create_by`)
VALUES ('测试优惠券', 'DISCOUNT', 10.00, '18322694510', 'UNUSED', NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), 'system');
@@ -2,6 +2,7 @@ package com.central.coupon.controller;
import com.central.common.model.Result;
import com.central.coupon.entity.Coupon;
import com.central.coupon.model.CtripCouponResponse;
import com.central.coupon.service.ICouponService;
import com.central.coupon.service.ICtripApiService;
import com.central.coupon.service.impl.CouponServiceImpl;
@@ -66,7 +67,7 @@ public class CtripCouponController {
*/
@Operation(summary = "携程创建优惠券接口")
@PostMapping("/create")
public Result<Boolean> createCouponFromCtrip(@RequestBody Map<String, Object> request,
public CtripCouponResponse createCouponFromCtrip(@RequestBody Map<String, Object> request,
jakarta.servlet.http.HttpServletRequest httpRequest) {
log.info("收到携程创建优惠券请求,IP: {}", httpRequest.getRemoteAddr());
@@ -78,7 +79,7 @@ public class CtripCouponController {
if (header == null || bodyObj == null) {
log.error("请求格式错误,缺少header或body");
return Result.succeed(false);
return buildErrorResponse("0002", "请求格式错误,缺少header或body");
}
// 处理body,可能是字符串或对象
@@ -105,7 +106,7 @@ public class CtripCouponController {
log.info("body直接解析JSON成功");
} catch (Exception e) {
log.error("body既不是有效的加密数据也不是有效的JSON: {}", e.getMessage());
return Result.succeed(false);
return buildErrorResponse("0001", "报文解析失败");
}
}
} else if (bodyObj instanceof Map) {
@@ -115,7 +116,7 @@ public class CtripCouponController {
log.info("body是对象类型");
} else {
log.error("body类型不支持: {}", bodyObj.getClass().getName());
return Result.succeed(false);
return buildErrorResponse("0001", "报文解析失败");
}
// 验证签名
@@ -128,6 +129,12 @@ public class CtripCouponController {
if (!ctripDecryptUtil.verifySign(accountId, serviceName, requestTime, bodyJson, version, sign)) {
log.error("签名验证失败,但继续处理业务逻辑");
log.error("期望签名: {}, 计算签名: {}", sign, ctripDecryptUtil.generateSign(accountId, serviceName, requestTime, bodyJson, version));
// 调用详细调试方法
Map<String, Object> debugInfo = ctripDecryptUtil.debugSignCalculation(
accountId, serviceName, requestTime, bodyJson, version, sign);
log.error("签名调试信息: {}", debugInfo);
// 临时跳过签名验证,继续处理业务逻辑
// return Result.succeed(false);
}
@@ -165,24 +172,19 @@ public class CtripCouponController {
// 参数验证
if (otaOrderId == null || userPhone == null) {
log.error("参数不完整 - otaOrderId: {}, userPhone: {}", otaOrderId, userPhone);
return Result.succeed(false);
return buildErrorResponse("1005", "信息缺失:订单ID或用户手机号");
}
// 生成携程优惠券ID(使用订单ID作为唯一标识)
String ctripCouponId = "CTRIP_" + otaOrderId;
// 幂等校验
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) {
log.info("携程优惠券已存在,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
return Result.succeed(true);
}
// 生成供应商订单ID(使用时间戳和订单ID生成唯一标识)
String supplierOrderId = "SUP_" + System.currentTimeMillis() + "_" + otaOrderId;
// 创建优惠券(使用默认值)
String couponName = "携程订单优惠券";
Integer couponType = 1; // 满减券
String couponType = "DISCOUNT"; // 优惠券类型
BigDecimal amount = new BigDecimal("50.00"); // 默认50元优惠券
BigDecimal minAmount = new BigDecimal("100.00"); // 满100可用
Integer discountRate = null;
// 设置有效期(从当前时间开始,30天有效期)
Calendar cal = Calendar.getInstance();
@@ -190,24 +192,30 @@ public class CtripCouponController {
cal.add(Calendar.DAY_OF_MONTH, 30);
Date validEndTime = cal.getTime();
// 幂等校验
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) {
log.info("携程优惠券已存在,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
return buildSuccessResponse(otaOrderId, supplierOrderId, ctripCouponId, userPhone, couponName, couponType, amount, validStartTime, validEndTime);
}
// 创建优惠券
boolean success = couponService.createCouponFromCtrip(
ctripCouponId, userPhone, couponName, couponType, amount,
minAmount, discountRate, validStartTime, validEndTime
validStartTime, validEndTime
);
if (success) {
log.info("携程优惠券创建成功,userPhone: {}, ctripCouponId: {}, otaOrderId: {}",
userPhone, ctripCouponId, otaOrderId);
return Result.succeed(true);
log.info("携程优惠券创建成功,userPhone: {}, ctripCouponId: {}, otaOrderId: {}, supplierOrderId: {}",
userPhone, ctripCouponId, otaOrderId, supplierOrderId);
return buildSuccessResponse(otaOrderId, supplierOrderId, ctripCouponId, userPhone, couponName, couponType, amount, validStartTime, validEndTime);
} else {
log.error("携程优惠券创建失败,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
return Result.succeed(false);
return buildErrorResponse("1100", "优惠券创建失败");
}
} catch (Exception e) {
log.error("处理携程创建优惠券请求异常", e);
return Result.succeed(false);
return buildErrorResponse("1100", "系统异常:" + e.getMessage());
}
}
@@ -295,6 +303,12 @@ public class CtripCouponController {
if (!ctripDecryptUtil.verifySign(accountId, serviceName, requestTime, bodyJson, version, sign)) {
log.error("签名验证失败,但继续处理业务逻辑");
log.error("期望签名: {}, 计算签名: {}", sign, ctripDecryptUtil.generateSign(accountId, serviceName, requestTime, bodyJson, version));
// 调用详细调试方法
Map<String, Object> debugInfo = ctripDecryptUtil.debugSignCalculation(
accountId, serviceName, requestTime, bodyJson, version, sign);
log.error("签名调试信息: {}", debugInfo);
// 临时跳过签名验证,继续处理业务逻辑
// return Result.succeed(false);
}
@@ -421,6 +435,12 @@ public class CtripCouponController {
if (!ctripDecryptUtil.verifySign(accountId, serviceName, requestTime, bodyJson, version, sign)) {
log.error("签名验证失败,但继续处理业务逻辑");
log.error("期望签名: {}, 计算签名: {}", sign, ctripDecryptUtil.generateSign(accountId, serviceName, requestTime, bodyJson, version));
// 调用详细调试方法
Map<String, Object> debugInfo = ctripDecryptUtil.debugSignCalculation(
accountId, serviceName, requestTime, bodyJson, version, sign);
log.error("签名调试信息: {}", debugInfo);
// 临时跳过签名验证,继续处理业务逻辑
// return Result.succeed(false);
}
@@ -526,16 +546,103 @@ public class CtripCouponController {
/**
* 获取状态文本
*/
private String getStatusText(Integer status) {
private String getStatusText(String status) {
if (status == null) {
return "未知状态";
}
switch (status) {
case 0: return "未使用";
case 1: return "已使用";
case 2: return "已过期";
case 3: return "已作废";
case "UNUSED": return "未使用";
case "USED": return "已使用";
case "EXPIRED": return "已过期";
case "VOIDED": return "已作废";
default: return "未知状态";
}
}
/**
* 构建成功响应
*/
private CtripCouponResponse buildSuccessResponse(String otaOrderId, String supplierOrderId, String ctripCouponId, String userPhone,
String couponName, String couponType,
BigDecimal amount, Date validStartTime, Date validEndTime) {
// 构建body对象
CtripCouponResponse.CtripCouponResponseBody body = new CtripCouponResponse.CtripCouponResponseBody();
body.setOtaOrderId(otaOrderId);
body.setSupplierOrderId(supplierOrderId);
body.setCtripCouponId(ctripCouponId);
body.setUserPhone(userPhone);
body.setCouponName(couponName);
body.setCouponType(couponType);
body.setAmount(amount);
body.setStatus("UNUSED");
body.setValidStartTime(validStartTime);
body.setValidEndTime(validEndTime);
// 将body对象转换为JSON字符串
try {
String bodyJson = objectMapper.writeValueAsString(body);
log.info("构建响应body JSON: {}", bodyJson);
// 检查AES配置
log.info("AES密钥长度: {}", ctripDecryptUtil.getAesKey() != null ? ctripDecryptUtil.getAesKey().length() : 0);
log.info("AES IV长度: {}", ctripDecryptUtil.getAesIv() != null ? ctripDecryptUtil.getAesIv().length() : 0);
// 使用AES加密body
String encryptedBody = ctripDecryptUtil.encryptAES(bodyJson);
log.info("AES加密结果: {}", encryptedBody != null ? "成功" : "失败");
if (encryptedBody != null) {
// 创建一个新的响应对象,body字段为加密字符串
CtripCouponResponse encryptedResponse = new CtripCouponResponse();
// 设置header
CtripCouponResponse.CtripResponseHeader header = new CtripCouponResponse.CtripResponseHeader();
header.setResultCode("0000");
header.setResultMessage("操作成功");
encryptedResponse.setHeader(header);
// 设置加密的body
encryptedResponse.setBody(encryptedBody);
log.info("AES加密body成功,加密后长度: {}", encryptedBody.length());
log.info("加密后的body内容: {}", encryptedBody);
// 验证加密是否成功
String decryptedTest = ctripDecryptUtil.decryptAES(encryptedBody);
if (decryptedTest != null) {
log.info("加密验证成功,解密后内容: {}", decryptedTest);
log.info("数据匹配: {}", bodyJson.equals(decryptedTest));
} else {
log.error("加密验证失败,无法解密");
}
return encryptedResponse;
} else {
log.error("AES加密body失败");
// 如果加密失败,返回错误响应
return buildErrorResponse("1100", "响应加密失败");
}
} catch (Exception e) {
log.error("构建响应body失败: {}", e.getMessage(), e);
return buildErrorResponse("1100", "响应构建失败");
}
}
/**
* 构建错误响应
*/
private CtripCouponResponse buildErrorResponse(String resultCode, String resultMessage) {
CtripCouponResponse response = new CtripCouponResponse();
// 设置header
CtripCouponResponse.CtripResponseHeader header = new CtripCouponResponse.CtripResponseHeader();
header.setResultCode(resultCode);
header.setResultMessage(resultMessage);
response.setHeader(header);
return response;
}
/**
* 测试接口 - 明文创建优惠券(仅用于开发测试)
*/
@@ -549,16 +656,11 @@ public class CtripCouponController {
String ctripCouponId = (String) request.get("ctripCouponId");
String userPhone = (String) request.get("userPhone");
String couponName = (String) request.get("couponName");
Integer couponType = (Integer) request.get("couponType");
String couponType = (String) request.get("couponType");
BigDecimal amount = null;
if (request.get("amount") != null) {
amount = new BigDecimal(request.get("amount").toString());
}
BigDecimal minAmount = null;
if (request.get("minAmount") != null) {
minAmount = new BigDecimal(request.get("minAmount").toString());
}
Integer discountRate = (Integer) request.get("discountRate");
String validStartTimeStr = (String) request.get("validStartTime");
String validEndTimeStr = (String) request.get("validEndTime");
@@ -588,7 +690,7 @@ public class CtripCouponController {
// 创建优惠券
boolean success = couponService.createCouponFromCtrip(
ctripCouponId, userPhone, couponName, couponType, amount,
minAmount, discountRate, validStartTime, validEndTime
validStartTime, validEndTime
);
if (success) {
@@ -727,6 +829,31 @@ public class CtripCouponController {
try {
Map<String, Object> result = ctripDecryptUtil.validateAESConfig();
// 添加加密解密测试
String testData = "{\"test\":\"data\"}";
String encrypted = ctripDecryptUtil.encryptAES(testData);
String decrypted = ctripDecryptUtil.decryptAES(encrypted);
result.put("testData", testData);
result.put("encrypted", encrypted);
result.put("decrypted", decrypted);
result.put("encryptionSuccess", encrypted != null);
result.put("decryptionSuccess", decrypted != null);
result.put("dataMatch", testData.equals(decrypted));
// 测试实际的优惠券响应数据
String couponResponseJson = "{\"ctripCouponId\":\"CTRIP_test\",\"userPhone\":\"13800138000\",\"couponName\":\"测试优惠券\",\"couponType\":\"DISCOUNT\",\"amount\":50.00,\"status\":\"UNUSED\",\"validStartTime\":\"2025-08-07T07:00:21.303+00:00\",\"validEndTime\":\"2025-09-06T07:00:21.303+00:00\"}";
String encryptedCoupon = ctripDecryptUtil.encryptAES(couponResponseJson);
String decryptedCoupon = ctripDecryptUtil.decryptAES(encryptedCoupon);
result.put("couponResponseJson", couponResponseJson);
result.put("encryptedCoupon", encryptedCoupon);
result.put("decryptedCoupon", decryptedCoupon);
result.put("couponEncryptionSuccess", encryptedCoupon != null);
result.put("couponDecryptionSuccess", decryptedCoupon != null);
result.put("couponDataMatch", couponResponseJson.equals(decryptedCoupon));
return Result.succeed(result);
} catch (Exception e) {
@@ -801,4 +928,53 @@ public class CtripCouponController {
return Result.succeed(null);
}
}
/**
* 测试接口 - 签名调试
*/
@Operation(summary = "测试接口 - 签名调试")
@PostMapping("/test/debug-sign")
public Result<Map<String, Object>> debugSign(@RequestBody Map<String, Object> request) {
log.info("收到签名调试请求");
try {
// 解析请求格式
@SuppressWarnings("unchecked")
Map<String, Object> header = (Map<String, Object>) request.get("header");
Object bodyObj = request.get("body");
if (header == null) {
return Result.succeed(null);
}
String accountId = (String) header.get("accountId");
String serviceName = (String) header.get("serviceName");
String requestTime = (String) header.get("requestTime");
String version = (String) header.get("version");
String sign = (String) header.get("sign");
String bodyJson = null;
if (bodyObj instanceof String) {
String bodyStr = (String) bodyObj;
String decryptedBody = ctripDecryptUtil.decryptAES(bodyStr);
if (decryptedBody != null) {
bodyJson = decryptedBody;
} else {
bodyJson = bodyStr;
}
} else if (bodyObj instanceof Map) {
bodyJson = objectMapper.writeValueAsString(bodyObj);
}
// 调用调试方法
Map<String, Object> debugInfo = ctripDecryptUtil.debugSignCalculation(
accountId, serviceName, requestTime, bodyJson, version, sign);
return Result.succeed(debugInfo);
} catch (Exception e) {
log.error("签名调试失败", e);
return Result.succeed(null);
}
}
}
@@ -30,9 +30,9 @@ public class Coupon implements Serializable {
private Long id;
/**
* 优惠券编号
* 租户ID
*/
private String couponNo;
private String tenantId;
/**
* 优惠券名称
@@ -40,29 +40,19 @@ public class Coupon implements Serializable {
private String couponName;
/**
* 优惠券类型:1-满减券,2-折扣券,3-免费券
* 优惠券类型
*/
private Integer couponType;
private String couponType;
/**
* 优惠券面额
* 优惠券金额
*/
private BigDecimal amount;
/**
* 使用门槛金额
* 货币类型
*/
private BigDecimal minAmount;
/**
* 折扣率(0-100,折扣券时使用)
*/
private Integer discountRate;
/**
* 优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废
*/
private Integer status;
private String amountCurrency;
/**
* 用户手机号
@@ -70,20 +60,20 @@ public class Coupon implements Serializable {
private String userPhone;
/**
* 用户ID
*/
private Long userId;
/**
* 来源:1-携程,2-高飞自建
*/
private Integer source;
/**
* 携程优惠券ID(来源为携程时使用)
* 携程优惠券ID
*/
private String ctripCouponId;
/**
* 携程订单ID
*/
private String ctripOrderId;
/**
* 状态:UNUSED-未使用,USED-已使用,EXPIRED-已过期,VOIDED-已作废
*/
private String status;
/**
* 有效期开始时间
*/
@@ -105,9 +95,14 @@ public class Coupon implements Serializable {
private String usedOrderNo;
/**
* 退券时间
* 备注
*/
private Date cancelTime;
private String remark;
/**
* 创建人
*/
private String createBy;
/**
* 创建时间
@@ -115,6 +110,11 @@ public class Coupon implements Serializable {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 更新人
*/
private String updateBy;
/**
* 更新时间
*/
@@ -122,22 +122,7 @@ public class Coupon implements Serializable {
private Date updateTime;
/**
* 创建人
* 是否删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -0,0 +1,68 @@
package com.central.coupon.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 携程优惠券接口响应
* 供应商在收到携程的优惠券请求时的标准响应格式
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CtripCouponResponse {
/**
* 返回头
*/
@JsonProperty("header")
private CtripResponseHeader header;
/**
* 返回体(传输时该字段需要AES加密)
* 该节点在返回码为0000时必填,其他均为非必填
* 可以是CtripCouponResponseBody对象或加密后的字符串
*/
@JsonProperty("body")
private Object body;
/**
* 携程返回头
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CtripResponseHeader {
@JsonProperty("resultCode")
private String resultCode; // 处理结果返回码
@JsonProperty("resultMessage")
private String resultMessage; // 处理结果返回信息
}
/**
* 携程优惠券返回体
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CtripCouponResponseBody {
@JsonProperty("otaOrderId")
private String otaOrderId; // 携程订单ID
@JsonProperty("supplierOrderId")
private String supplierOrderId; // 供应商订单ID
@JsonProperty("ctripCouponId")
private String ctripCouponId; // 携程优惠券ID
@JsonProperty("userPhone")
private String userPhone; // 用户手机号
@JsonProperty("couponName")
private String couponName; // 优惠券名称
@JsonProperty("couponType")
private String couponType; // 优惠券类型
@JsonProperty("amount")
private java.math.BigDecimal amount; // 优惠券金额
@JsonProperty("status")
private String status; // 优惠券状态
@JsonProperty("validStartTime")
private java.util.Date validStartTime; // 有效期开始时间
@JsonProperty("validEndTime")
private java.util.Date validEndTime; // 有效期结束时间
}
}
@@ -58,8 +58,7 @@ public interface ICouponService extends IService<Coupon> {
* 根据携程优惠券ID创建优惠券(携程接口调用)
*/
boolean createCouponFromCtrip(String ctripCouponId, String userPhone, String couponName,
Integer couponType, java.math.BigDecimal amount,
java.math.BigDecimal minAmount, Integer discountRate,
String couponType, java.math.BigDecimal amount,
java.util.Date validStartTime,
java.util.Date validEndTime);
@@ -44,13 +44,10 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
coupon.setUserPhone((String) params.get("userPhone"));
}
if (params.get("status") != null) {
coupon.setStatus(Integer.valueOf(params.get("status").toString()));
}
if (params.get("source") != null) {
coupon.setSource(Integer.valueOf(params.get("source").toString()));
coupon.setStatus(params.get("status").toString());
}
if (params.get("couponType") != null) {
coupon.setCouponType(Integer.valueOf(params.get("couponType").toString()));
coupon.setCouponType(params.get("couponType").toString());
}
// 分页查询
@@ -74,11 +71,10 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
@Override
@Transactional(rollbackFor = Exception.class)
public boolean createCoupon(Coupon coupon) {
if (coupon.getCouponNo() == null) {
coupon.setCouponNo(generateCouponNo());
}
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
coupon.setTenantId("000000");
coupon.setDeleted(0);
return save(coupon);
}
@@ -114,7 +110,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
return false;
}
if (coupon.getStatus() != 0) {
if (!"UNUSED".equals(coupon.getStatus())) {
log.error("优惠券状态不正确,couponId: {}, status: {}", couponId, coupon.getStatus());
return false;
}
@@ -130,13 +126,12 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
@Override
@Transactional(rollbackFor = Exception.class)
public boolean createCouponFromCtrip(String ctripCouponId, String userPhone, String couponName,
Integer couponType, java.math.BigDecimal amount,
java.math.BigDecimal minAmount, Integer discountRate,
String couponType, java.math.BigDecimal amount,
java.util.Date validStartTime,
java.util.Date validEndTime) {
log.info("开始创建携程优惠券 - ctripCouponId: {}, userPhone: {}, couponName: {}, amount: {}, minAmount: {}",
ctripCouponId, userPhone, couponName, amount, minAmount);
log.info("开始创建携程优惠券 - ctripCouponId: {}, userPhone: {}, couponName: {}, amount: {}",
ctripCouponId, userPhone, couponName, amount);
// 检查是否已存在该携程优惠券
Coupon existingCoupon = baseMapper.selectByCtripCouponId(ctripCouponId);
@@ -148,15 +143,12 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
log.info("携程优惠券不存在,开始创建新优惠券");
Coupon coupon = new Coupon();
coupon.setCouponNo(generateCouponNo());
coupon.setCouponName(couponName);
coupon.setCouponType(couponType);
coupon.setAmount(amount);
coupon.setMinAmount(minAmount);
coupon.setDiscountRate(discountRate);
coupon.setStatus(0); // 未使用
coupon.setAmountCurrency("CNY");
coupon.setStatus("UNUSED"); // 未使用
coupon.setUserPhone(userPhone);
coupon.setSource(1); // 来源:携程
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(validStartTime);
coupon.setValidEndTime(validEndTime);
@@ -164,14 +156,16 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
coupon.setUpdateTime(new Date());
coupon.setCreateBy("ctrip");
coupon.setUpdateBy("ctrip");
coupon.setTenantId("000000");
coupon.setDeleted(0);
log.info("优惠券对象创建完成,准备保存到数据库 - couponNo: {}", coupon.getCouponNo());
log.info("优惠券对象创建完成,准备保存到数据库");
boolean saveResult = save(coupon);
if (saveResult) {
log.info("携程优惠券保存成功 - 优惠券ID: {}, couponNo: {}, ctripCouponId: {}",
coupon.getId(), coupon.getCouponNo(), ctripCouponId);
log.info("携程优惠券保存成功 - 优惠券ID: {}, ctripCouponId: {}",
coupon.getId(), ctripCouponId);
} else {
log.error("携程优惠券保存失败 - ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
}
@@ -199,7 +193,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
}
// 2. 验证优惠券状态
if (coupon.getStatus() != 0) {
if (!"UNUSED".equals(coupon.getStatus())) {
log.error("携程优惠券状态不正确,ctripCouponId: {}, status: {}", ctripCouponId, coupon.getStatus());
throw new CouponInvalidException("优惠券状态不正确");
}
@@ -273,8 +267,8 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
}
Coupon bestCoupon = sortedCoupons.get(0);
log.info("选择最优优惠券,couponId: {}, amount: {}, discount: {}",
bestCoupon.getId(), bestCoupon.getAmount(), bestCoupon.getDiscountRate());
log.info("选择最优优惠券,couponId: {}, amount: {}",
bestCoupon.getId(), bestCoupon.getAmount());
return bestCoupon;
}
@@ -286,14 +280,10 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
try {
// 1. 验证订单金额是否满足使用门槛
java.math.BigDecimal orderAmount = getOrderAmount(orderNo);
if (coupon.getMinAmount() != null && orderAmount.compareTo(coupon.getMinAmount()) < 0) {
log.warn("订单金额不满足优惠券使用门槛,orderAmount: {}, minAmount: {}",
orderAmount, coupon.getMinAmount());
return false;
}
log.info("验证优惠券使用条件,orderAmount: {}", orderAmount);
// 2. 验证优惠券是否已被使用
if (coupon.getStatus() != 0) {
if (!"UNUSED".equals(coupon.getStatus())) {
log.warn("优惠券已被使用,status: {}", coupon.getStatus());
return false;
}
@@ -321,17 +311,12 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
* 验证优惠券是否适用于当前订单
*/
private boolean validateCouponForOrder(Coupon coupon, java.math.BigDecimal orderAmount) {
// 1. 验证订单金额是否满足使用门槛
if (coupon.getMinAmount() != null && orderAmount.compareTo(coupon.getMinAmount()) < 0) {
// 1. 验证优惠券状态
if (!"UNUSED".equals(coupon.getStatus())) {
return false;
}
// 2. 验证优惠券状态
if (coupon.getStatus() != 0) {
return false;
}
// 3. 验证有效期
// 2. 验证有效期
Date now = new Date();
if (coupon.getValidStartTime().after(now) || coupon.getValidEndTime().before(now)) {
return false;
@@ -344,25 +329,13 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
* 比较优惠券优先级
*/
private int compareCouponPriority(Coupon c1, Coupon c2, java.math.BigDecimal orderAmount) {
// 1. 优先选择满减券
if (c1.getCouponType() == 1 && c2.getCouponType() != 1) {
return -1;
}
if (c1.getCouponType() != 1 && c2.getCouponType() == 1) {
return 1;
// 1. 优先选择金额大的优惠券
int amountCompare = c2.getAmount().compareTo(c1.getAmount());
if (amountCompare != 0) {
return amountCompare;
}
// 2. 满减券按金额排序(金额大的优先)
if (c1.getCouponType() == 1 && c2.getCouponType() == 1) {
return c2.getAmount().compareTo(c1.getAmount());
}
// 3. 折扣券按折扣率排序(折扣率高的优先)
if (c1.getCouponType() == 2 && c2.getCouponType() == 2) {
return c2.getDiscountRate().compareTo(c1.getDiscountRate());
}
// 4. 按创建时间排序(先创建的优先)
// 2. 按创建时间排序(先创建的优先)
return c1.getCreateTime().compareTo(c2.getCreateTime());
}
@@ -508,7 +508,7 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
}
// 验证优惠券状态
if (existingCoupon.getStatus() != 0) {
if (!"UNUSED".equals(existingCoupon.getStatus())) {
log.warn("优惠券状态不正确,code: {}, status: {}", coupon.getCode(), existingCoupon.getStatus());
return false;
}
@@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 携程解密工具类
@@ -26,8 +27,8 @@ public class CtripDecryptUtil {
@Value("${ctrip.aes.iv:your-aes-iv-here}")
private String aesIv;
@Value("${ctrip.sign.key:your-sign-key-here}")
private String md5Secret;
@Value("${ctrip.account.secret:your-account-secret}")
private String accountSecret;
/**
* AES-128-CBC解密
@@ -82,6 +83,12 @@ public class CtripDecryptUtil {
return null;
}
// 检查解密数据长度是否为16的倍数
if (encryptedBytes.length % 16 != 0) {
log.error("AES解密失败:加密数据长度不是16的倍数,长度: {}", encryptedBytes.length);
return null;
}
// 创建密钥规范
SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesIv.getBytes(StandardCharsets.UTF_8));
@@ -99,7 +106,14 @@ public class CtripDecryptUtil {
return decryptedData;
} catch (Exception e) {
log.error("AES解密失败: {}", e.getMessage(), e);
log.error("AES解密失败: {}", e.getMessage());
if (e instanceof IllegalArgumentException) {
log.error("数据格式错误,可能是非携程加密数据");
} else if (e instanceof javax.crypto.IllegalBlockSizeException) {
log.error("数据块大小错误,可能是加密数据损坏或格式不正确");
} else if (e instanceof javax.crypto.BadPaddingException) {
log.error("填充错误,可能是密钥或IV不正确");
}
return null;
}
}
@@ -159,6 +173,12 @@ public class CtripDecryptUtil {
* @return
*/
public byte[] decodeBytes(String str) {
// 检查字符串长度是否为偶数
if (str.length() % 2 != 0) {
log.error("携程自定义解码失败:字符串长度不是偶数,长度: {}", str.length());
throw new IllegalArgumentException("字符串长度必须是偶数");
}
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i += 2) {
char c = str.charAt(i);
@@ -185,7 +205,7 @@ public class CtripDecryptUtil {
try {
log.info("开始验证MD5签名,accountId: {}, serviceName: {}, requestTime: {}",
accountId, serviceName, requestTime);
log.info("签名密钥长度: {}", md5Secret != null ? md5Secret.length() : 0);
log.info("账户密钥长度: {}", accountSecret != null ? accountSecret.length() : 0);
// 构建签名字符串
String signString = buildSignString(accountId, serviceName, requestTime, body, version);
@@ -198,7 +218,7 @@ public class CtripDecryptUtil {
log.info("MD5签名验证结果: {}, 期望签名: {}, 计算签名: {}", isValid, sign, calculatedSign);
log.debug("签名字符串: {}", signString);
log.debug("签名密钥: {}", md5Secret);
log.debug("账户密钥: {}", accountSecret);
return isValid;
} catch (Exception e) {
@@ -247,7 +267,7 @@ public class CtripDecryptUtil {
log.info("requestTime: {}", requestTime);
log.info("body: {}", body);
log.info("version: {}", version);
log.info("signKey: {}", md5Secret);
log.info("accountSecret: {}", accountSecret);
String signString = buildSignString(accountId, serviceName, requestTime, body, version);
log.info("签名字符串: {}", signString);
@@ -262,6 +282,62 @@ public class CtripDecryptUtil {
}
}
/**
* 详细调试签名计算过程
*
* @param accountId 供应商帐号
* @param serviceName 接口名称
* @param requestTime 请求时间
* @param body 请求体
* @param version 版本号
* @param expectedSign 期望的签名
* @return 调试信息
*/
public Map<String, Object> debugSignCalculation(String accountId, String serviceName, String requestTime,
String body, String version, String expectedSign) {
Map<String, Object> debugInfo = new java.util.HashMap<>();
try {
log.info("=== 详细调试签名计算 ===");
// 记录原始参数
debugInfo.put("accountId", accountId);
debugInfo.put("serviceName", serviceName);
debugInfo.put("requestTime", requestTime);
debugInfo.put("body", body);
debugInfo.put("version", version);
debugInfo.put("expectedSign", expectedSign);
debugInfo.put("accountSecret", accountSecret);
// 构建签名字符串
String signString = buildSignString(accountId, serviceName, requestTime, body, version);
debugInfo.put("signString", signString);
debugInfo.put("signStringLength", signString.length());
// 计算MD5
String calculatedSign = calculateMD5(signString).toLowerCase();
debugInfo.put("calculatedSign", calculatedSign);
debugInfo.put("isMatch", calculatedSign.equalsIgnoreCase(expectedSign));
// 分析每个部分的长度
debugInfo.put("accountIdLength", accountId != null ? accountId.length() : 0);
debugInfo.put("serviceNameLength", serviceName != null ? serviceName.length() : 0);
debugInfo.put("requestTimeLength", requestTime != null ? requestTime.length() : 0);
debugInfo.put("bodyLength", body != null ? body.length() : 0);
debugInfo.put("versionLength", version != null ? version.length() : 0);
debugInfo.put("accountSecretLength", accountSecret != null ? accountSecret.length() : 0);
log.info("签名调试完成 - 匹配结果: {}", debugInfo.get("isMatch"));
return debugInfo;
} catch (Exception e) {
log.error("签名调试失败: {}", e.getMessage(), e);
debugInfo.put("error", e.getMessage());
return debugInfo;
}
}
/**
* 验证AES配置
*
@@ -369,8 +445,8 @@ public class CtripDecryptUtil {
/**
* 构建签名字符串
* 格式:accountId + serviceName + requestTime + body + version + signkey
* 注意:这里使用的是signkey而不是md5Secret
* 格式:accountId + serviceName + requestTime + body + version + accountSecret
* 使用账户密钥作为签名密钥
*/
private String buildSignString(String accountId, String serviceName, String requestTime,
String body, String version) {
@@ -378,9 +454,24 @@ public class CtripDecryptUtil {
sb.append(accountId != null ? accountId : "");
sb.append(serviceName != null ? serviceName : "");
sb.append(requestTime != null ? requestTime : "");
sb.append(body != null ? body : "");
// 确保body是紧凑的JSON格式(无多余空格和换行)
String compactBody = body;
if (body != null) {
try {
// 重新格式化JSON,确保格式一致
ObjectMapper objectMapper = new ObjectMapper();
Object jsonObject = objectMapper.readValue(body, Object.class);
compactBody = objectMapper.writeValueAsString(jsonObject);
} catch (Exception e) {
log.warn("JSON格式化失败,使用原始body: {}", e.getMessage());
compactBody = body;
}
}
sb.append(compactBody != null ? compactBody : "");
sb.append(version != null ? version : "");
sb.append(md5Secret != null ? md5Secret : "");
// 使用账户密钥而不是单独的签名密钥
sb.append(accountSecret != null ? accountSecret : "");
String signString = sb.toString();
log.debug("构建签名字符串: {}", signString);
@@ -44,8 +44,17 @@ logging:
# 携程API配置
ctrip:
# AES加密配置
aes:
key: 087b36ad0dff7942 # 请替换为实际的AES密钥
iv: 750e15a31356a99d # 请替换为实际的AES IV
sign:
key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
# 签名配置(使用账户密钥进行签名计算)
# API配置
api:
base-url: https://ttdopen.ctrip.com/api/order/notice.do # 携程API基础URL
timeout: 30000 # 请求超时时间(毫秒)
retry-times: 3 # 重试次数
# 账户配置
account:
id: c50a8f2a4a59c9e7 # 请替换为实际的账户ID
secret: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的账户密钥
@@ -5,35 +5,32 @@
<!-- 结果映射 -->
<resultMap id="BaseResultMap" type="com.central.coupon.entity.Coupon">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="coupon_no" property="couponNo" jdbcType="VARCHAR"/>
<result column="coupon_name" property="couponName" jdbcType="VARCHAR"/>
<result column="coupon_type" property="couponType" jdbcType="INTEGER"/>
<result column="coupon_type" property="couponType" jdbcType="VARCHAR"/>
<result column="amount" property="amount" jdbcType="DECIMAL"/>
<result column="min_amount" property="minAmount" jdbcType="DECIMAL"/>
<result column="discount_rate" property="discountRate" jdbcType="INTEGER"/>
<result column="status" property="status" jdbcType="INTEGER"/>
<result column="amount_currency" property="amountCurrency" jdbcType="VARCHAR"/>
<result column="user_phone" property="userPhone" jdbcType="VARCHAR"/>
<result column="user_id" property="userId" jdbcType="BIGINT"/>
<result column="source" property="source" jdbcType="INTEGER"/>
<result column="ctrip_coupon_id" property="ctripCouponId" jdbcType="VARCHAR"/>
<result column="ctrip_order_id" property="ctripOrderId" jdbcType="VARCHAR"/>
<result column="status" property="status" jdbcType="VARCHAR"/>
<result column="valid_start_time" property="validStartTime" jdbcType="TIMESTAMP"/>
<result column="valid_end_time" property="validEndTime" jdbcType="TIMESTAMP"/>
<result column="used_time" property="usedTime" jdbcType="TIMESTAMP"/>
<result column="used_order_no" property="usedOrderNo" jdbcType="VARCHAR"/>
<result column="cancel_time" property="cancelTime" jdbcType="TIMESTAMP"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
<result column="create_by" property="createBy" jdbcType="VARCHAR"/>
<result column="update_by" property="updateBy" jdbcType="VARCHAR"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
<result column="tenant_id" property="tenantId" jdbcType="VARCHAR"/>
<result column="deleted" property="deleted" jdbcType="TINYINT"/>
</resultMap>
<!-- 基础字段 -->
<sql id="Base_Column_List">
id, coupon_no, coupon_name, coupon_type, amount, min_amount, discount_rate,
status, user_phone, user_id, source, ctrip_coupon_id, valid_start_time, valid_end_time,
used_time, used_order_no, cancel_time, create_time, update_time, create_by, update_by, remark, tenant_id
id, coupon_name, coupon_type, amount, amount_currency, user_phone, ctrip_coupon_id, ctrip_order_id,
status, valid_start_time, valid_end_time, used_time, used_order_no, remark,
create_time, update_time, create_by, update_by, tenant_id, deleted
</sql>
<!-- 分页查询优惠券列表 -->
@@ -42,19 +39,17 @@
<include refid="Base_Column_List"/>
FROM t_coupon
<where>
AND deleted = 0
<if test="coupon.couponName != null and coupon.couponName != ''">
AND coupon_name LIKE CONCAT('%', #{coupon.couponName}, '%')
</if>
<if test="coupon.userPhone != null and coupon.userPhone != ''">
AND user_phone = #{coupon.userPhone}
</if>
<if test="coupon.status != null">
<if test="coupon.status != null and coupon.status != ''">
AND status = #{coupon.status}
</if>
<if test="coupon.source != null">
AND source = #{coupon.source}
</if>
<if test="coupon.couponType != null">
<if test="coupon.couponType != null and coupon.couponType != ''">
AND coupon_type = #{coupon.couponType}
</if>
</where>
@@ -67,6 +62,7 @@
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE user_phone = #{userPhone}
AND deleted = 0
ORDER BY create_time DESC
</select>
@@ -76,9 +72,10 @@
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE user_phone = #{userPhone}
AND status = 0
AND status = 'UNUSED'
AND valid_start_time &lt;= NOW()
AND valid_end_time &gt;= NOW()
AND deleted = 0
ORDER BY create_time DESC
</select>
@@ -88,6 +85,7 @@
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE ctrip_coupon_id = #{ctripCouponId}
AND deleted = 0
LIMIT 1
</select>
@@ -97,26 +95,29 @@
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE used_order_no = #{usedOrderNo}
AND deleted = 0
LIMIT 1
</select>
<!-- 更新优惠券状态为已使用 -->
<update id="updateCouponUsed">
UPDATE t_coupon
SET status = 1,
SET status = 'USED',
used_time = NOW(),
used_order_no = #{usedOrderNo},
update_time = NOW()
WHERE id = #{id}
AND deleted = 0
</update>
<!-- 批量更新过期优惠券状态 -->
<update id="updateExpiredCoupons">
UPDATE t_coupon
SET status = 2,
SET status = 'EXPIRED',
update_time = NOW()
WHERE status = 0
WHERE status = 'UNUSED'
AND valid_end_time &lt; NOW()
AND deleted = 0
</update>
<!-- 检查用户手机号和携程优惠券ID是否已存在 -->
@@ -125,6 +126,7 @@
FROM t_coupon
WHERE user_phone = #{userPhone}
AND ctrip_coupon_id = #{ctripCouponId}
AND deleted = 0
</select>
</mapper>
@@ -31,16 +31,14 @@ public class CouponServiceTest {
String ctripCouponId = "TEST_COUPON_001";
String userPhone = "13800138000";
String couponName = "测试优惠券";
Integer couponType = 1;
String couponType = "DISCOUNT";
BigDecimal amount = new BigDecimal("100.00");
BigDecimal minAmount = new BigDecimal("200.00");
Integer discountRate = null;
Date validStartTime = new Date();
Date validEndTime = new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L); // 30天后过期
// 执行测试
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
couponType, amount, minAmount, discountRate, validStartTime, validEndTime);
couponType, amount, validStartTime, validEndTime);
// 验证结果
assertTrue(result);
@@ -52,9 +50,7 @@ public class CouponServiceTest {
assertEquals(couponName, savedCoupon.getCouponName());
assertEquals(couponType, savedCoupon.getCouponType());
assertEquals(amount, savedCoupon.getAmount());
assertEquals(minAmount, savedCoupon.getMinAmount());
assertEquals(0, savedCoupon.getStatus()); // 未使用状态
assertEquals(1, savedCoupon.getSource()); // 来源:携程
assertEquals("UNUSED", savedCoupon.getStatus()); // 未使用状态
}
@Test
@@ -63,16 +59,16 @@ public class CouponServiceTest {
String userPhone = "13800138000";
// 创建测试优惠券
createTestCoupon(userPhone, "TEST_COUPON_001", 0); // 未使用
createTestCoupon(userPhone, "TEST_COUPON_002", 1); // 已使用
createTestCoupon(userPhone, "TEST_COUPON_003", 0); // 未使用
createTestCoupon(userPhone, "TEST_COUPON_001", "UNUSED"); // 未使用
createTestCoupon(userPhone, "TEST_COUPON_002", "USED"); // 已使用
createTestCoupon(userPhone, "TEST_COUPON_003", "UNUSED"); // 未使用
// 执行测试
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
// 验证结果
assertEquals(2, availableCoupons.size()); // 只有未使用的优惠券
assertTrue(availableCoupons.stream().allMatch(coupon -> coupon.getStatus() == 0));
assertTrue(availableCoupons.stream().allMatch(coupon -> "UNUSED".equals(coupon.getStatus())));
}
@Test
@@ -82,9 +78,9 @@ public class CouponServiceTest {
BigDecimal orderAmount = new BigDecimal("300.00");
// 创建测试优惠券
createTestCoupon(userPhone, "TEST_COUPON_001", 0, new BigDecimal("50.00"), new BigDecimal("200.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_002", 0, new BigDecimal("100.00"), new BigDecimal("200.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_003", 0, new BigDecimal("30.00"), new BigDecimal("100.00")); // 满减券,金额不够
createTestCoupon(userPhone, "TEST_COUPON_001", "UNUSED", new BigDecimal("50.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_002", "UNUSED", new BigDecimal("100.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_003", "UNUSED", new BigDecimal("30.00")); // 满减券,金额不够
// 执行测试
Coupon bestCoupon = couponService.selectBestCoupon(userPhone, orderAmount);
@@ -103,7 +99,7 @@ public class CouponServiceTest {
String orderNo = "ORDER_001";
// 创建测试优惠券
createTestCoupon(userPhone, ctripCouponId, 0);
createTestCoupon(userPhone, ctripCouponId, "UNUSED");
// 执行测试
boolean result = couponService.verifyCtripCoupon(ctripCouponId, orderNo);
@@ -113,7 +109,7 @@ public class CouponServiceTest {
// 验证优惠券状态已更新
Coupon updatedCoupon = couponService.getByCtripCouponId(ctripCouponId);
assertEquals(1, updatedCoupon.getStatus()); // 已使用状态
assertEquals("USED", updatedCoupon.getStatus()); // 已使用状态
assertEquals(orderNo, updatedCoupon.getUsedOrderNo());
}
@@ -143,29 +139,31 @@ public class CouponServiceTest {
/**
* 创建测试优惠券
*/
private void createTestCoupon(String userPhone, String ctripCouponId, Integer status) {
createTestCoupon(userPhone, ctripCouponId, status, new BigDecimal("100.00"), new BigDecimal("200.00"));
private void createTestCoupon(String userPhone, String ctripCouponId, String status) {
createTestCoupon(userPhone, ctripCouponId, status, new BigDecimal("100.00"));
}
/**
* 创建测试优惠券
*/
private void createTestCoupon(String userPhone, String ctripCouponId, Integer status,
BigDecimal amount, BigDecimal minAmount) {
private void createTestCoupon(String userPhone, String ctripCouponId, String status,
BigDecimal amount) {
Coupon coupon = new Coupon();
coupon.setCouponNo("CP" + System.currentTimeMillis());
coupon.setCouponName("测试优惠券");
coupon.setCouponType(1);
coupon.setCouponType("DISCOUNT");
coupon.setAmount(amount);
coupon.setMinAmount(minAmount);
coupon.setAmountCurrency("CNY");
coupon.setStatus(status);
coupon.setUserPhone(userPhone);
coupon.setSource(1);
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(new Date());
coupon.setValidEndTime(new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L));
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
coupon.setCreateBy("test");
coupon.setUpdateBy("test");
coupon.setTenantId("000000");
coupon.setDeleted(0);
couponService.save(coupon);
}
@@ -175,19 +173,21 @@ public class CouponServiceTest {
*/
private void createExpiredTestCoupon(String userPhone, String ctripCouponId) {
Coupon coupon = new Coupon();
coupon.setCouponNo("CP" + System.currentTimeMillis());
coupon.setCouponName("已过期测试优惠券");
coupon.setCouponType(1);
coupon.setCouponType("DISCOUNT");
coupon.setAmount(new BigDecimal("100.00"));
coupon.setMinAmount(new BigDecimal("200.00"));
coupon.setStatus(0);
coupon.setAmountCurrency("CNY");
coupon.setStatus("UNUSED");
coupon.setUserPhone(userPhone);
coupon.setSource(1);
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(new Date(System.currentTimeMillis() - 60 * 24 * 60 * 60 * 1000L)); // 60天前开始
coupon.setValidEndTime(new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000L)); // 30天前过期
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
coupon.setCreateBy("test");
coupon.setUpdateBy("test");
coupon.setTenantId("000000");
coupon.setDeleted(0);
couponService.save(coupon);
}