docs(api): 添加详细Apple卡密管理API文档

- 新增API端点参考文档,涵盖权限、卡密、订单、商户、监控、限制等模块
- 详细说明Apple卡密充值处理流程,包括提交、查询、回调和轮询接口
- 描述充值订单状态机及生命周期,支持超时重试和状态迁移
- 介绍签名验证、幂等控制及重复卡密防刷单策略
- 增加商户配置管理、历史记录查询和错误处理机制说明
- 提供API使用示例代码及客户端实现指导
- 删除过时的.drone.yml.bak文件,清理无用配置
- 添加.dockerignore忽略指定目录和文件
This commit is contained in:
danial
2025-10-08 20:13:40 +08:00
parent f35dfacbc2
commit 96ed936079
133 changed files with 35465 additions and 247 deletions

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
.claude
.idea
.lingma
./qoder/

View File

@@ -1,220 +0,0 @@
---
kind: pipeline
type: ssh
name: master-machine
server:
host: 121.37.253.228
user: www
password:
from_secret: www_password
clone:
depth: 1
steps:
- name: build new image
commands:
- docker build --no-cache -t kami_backend:${DRONE_BRANCH}${DRONE_BUILD_NUMBER} -f ./manifest/docker/Dockerfile --build-arg USE_PROXY=1 .
- name: deploy to docker compose
commands:
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml down
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml up -d
- name: push to docker registry
commands:
- docker save -o /tmp/kami_backend.tar kami_backend:${DRONE_BRANCH}${DRONE_BUILD_NUMBER}
- mv ./manifest/docker/docker-compose.yml /tmp/
trigger:
branch:
- develop
- production
when:
event:
- push
---
kind: pipeline
type: ssh
name: 绝技服务器
server:
host: 43.133.200.219
user: ubuntu
password:
from_secret: flower
clone:
disable: true
steps:
- name: copy file
commands:
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com www@121.37.253.228:/tmp/kami_backend.tar ./
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com www@121.37.253.228:/tmp/docker-compose.yml ./
environment:
PASSWORD:
from_secret: www_password
- name: pull image
commands:
- docker load -i kami_backend.tar
- name: copy tar to tmp dictionary
commands:
- sudo mv kami_backend.tar /tmp/
- sudo mv docker-compose.yml /tmp/
# - name: clean old container
# commands:
# - docker container inspect kami_backend &> /dev/null && docker container rm -f kami_backend
# - name: run docker compose
# commands:
# - VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml down
# - VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml up -d
- name: clean unused image
commands:
- docker image prune -af
depends_on:
- master-machine
trigger:
status:
- success
- failure
branch:
- production
when:
event:
- push
---
kind: pipeline
type: ssh
name: 小L的服务器
server:
host: 43.130.238.110
user: ubuntu
password:
from_secret: ubuntu_L
clone:
disable: true
steps:
- name: copy file
commands:
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com ubuntu@43.133.200.219:/tmp/kami_backend.tar ./
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com ubuntu@43.133.200.219:/tmp/docker-compose.yml ./
environment:
PASSWORD:
from_secret: flower
- name: pull image
commands:
- docker load -i kami_backend.tar
- name: clean old container
commands:
- docker container inspect kami_backend &> /dev/null && docker container rm -f kami_backend
- name: run docker compose
commands:
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml down
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml up -d
- name: clean unused image
commands:
- docker image prune -af
depends_on:
- 绝技服务器
trigger:
branch:
- production
status:
- success
- failure
when:
event:
- push
---
kind: pipeline
type: ssh
name: 泼兔的服务器
server:
host: 43.163.223.93
user: ubuntu
password:
from_secret: ubuntu-crazy_rabbit
clone:
disable: true
steps:
- name: copy file
commands:
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com ubuntu@43.133.200.219:/tmp/kami_backend.tar ./
- sshpass -p $PASSWORD scp -C -c chacha20-poly1305@openssh.com ubuntu@43.133.200.219:/tmp/docker-compose.yml ./
environment:
PASSWORD:
from_secret: flower
- name: pull image
commands:
- docker load -i kami_backend.tar
- name: clean old container
commands:
- docker container inspect kami_backend &> /dev/null && docker container rm -f kami_backend
- name: run docker compose
commands:
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml down
- VERSION=${DRONE_BRANCH}${DRONE_BUILD_NUMBER} USE_PROXY=1 docker compose -f ./manifest/docker/docker-compose.yml up -d
- name: clean unused image
commands:
- docker image prune -af
depends_on:
- 绝技服务器
trigger:
status:
- success
- failure
branch:
- production
when:
event:
- push
---
kind: pipeline
type: docker
name: server酱微信通知
depends_on:
- 泼兔的服务器
- 小L的服务器
steps:
- name: send-wechat
image: plugins/webhook
pull: if-not-exists
settings:
urls: https://open.feishu.cn/open-apis/bot/v2/hook/1f4a9795-84a9-4cc5-b2c5-0bf05686336b
content_type: application/json
template: |
{
"msg_type":"text",
"content":
{
"text": "项目名称: ${DRONE_REPO_NAME}\n分支${DRONE_BRANCH}\n构建编号${DRONE_BUILD_NUMBER}\n项目构建状态{{ build.status }}"
}
}
trigger:
branch:
- develop
- production
status:
- success
- failure
when:
event:
- push

View File

@@ -0,0 +1,557 @@
# API端点参考
<cite>
**本文档中引用的文件**
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [card_info_c_trip.go](file://api/card_info_c_trip/card_info_c_trip.go)
- [card_info_t_mall_game.go](file://api/card_info_t_mall_game/card_info_t_mall_game.go)
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [order.go](file://api/order/order.go)
- [merchant.go](file://api/merchant/merchant.go)
- [sysUser.go](file://api/sysUser/sysUser.go)
- [monitor.go](file://api/monitor/monitor.go)
- [restriction.go](file://api/restriction/restriction.go)
- [common.go](file://api/commonApi/common.go)
- [config.go](file://internal/consts/sys_config_dict.go)
</cite>
## 目录
1. [简介](#简介)
2. [API架构概述](#api架构概述)
3. [权限管理模块](#权限管理模块)
4. [卡密信息管理模块](#卡密信息管理模块)
5. [订单处理模块](#订单处理模块)
6. [商户管理模块](#商户管理模块)
7. [系统监控模块](#系统监控模块)
8. [限制管理模块](#限制管理模块)
9. [认证与安全](#认证与安全)
10. [错误处理策略](#错误处理策略)
11. [速率限制](#速率限制)
12. [客户端实现指南](#客户端实现指南)
13. [性能优化建议](#性能优化建议)
## 简介
本文档提供了kami_backend系统所有公共API端点的完整参考文档覆盖了权限管理卡密信息管理订单处理商户管理系统监控和限制管理等核心模块每个API端点都详细记录了HTTP方法URL模式请求/响应模式认证方法和参数说明文档基于代码库中的实际实现确保与系统真实数据结构和接口定义完全一致
## API架构概述
系统采用基于GoFrame框架的RESTful API架构所有API端点遵循统一的版本控制和响应格式API基础路径为`/api/v1`支持JSON格式的数据交换系统实现了统一的错误处理机制和认证授权体系
```mermaid
graph TB
Client[客户端] --> |HTTP请求| APIGateway[API网关]
APIGateway --> Auth[认证中间件]
Auth --> RateLimit[速率限制]
RateLimit --> Controller[控制器层]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> Database[(数据库)]
subgraph "核心模块"
Controller --> CardInfo[卡密信息管理]
Controller --> Order[订单处理]
Controller --> Merchant[商户管理]
Controller --> Monitor[系统监控]
Controller --> Restriction[限制管理]
end
```
**图源**
- [main.go](file://main.go)
- [middleware/auth.go](file://internal/middleware/auth.go)
- [controller目录](file://internal/controller/)
## 权限管理模块
权限管理模块提供用户角色和菜单的完整管理功能支持基于RBAC基于角色的访问控制的权限体系
### 用户管理
提供用户创建删除更新和查询功能支持用户状态管理和权限分配
**端点列表**
- `POST /api/v1/sysUser/user/add` - 创建用户
- `DELETE /api/v1/sysUser/user/delete` - 删除用户
- `PUT /api/v1/sysUser/user/edit` - 编辑用户
- `GET /api/v1/sysUser/user/get/all` - 获取所有用户
- `PUT /api/v1/sysUser/user/forbidden/by/id` - 禁用/启用用户
**请求参数示例**
```json
{
"username": "example_user",
"password": "encrypted_password",
"roleId": 1,
"status": 1
}
```
**响应格式**
```json
{
"code": 0,
"message": "操作成功",
"data": {
"userId": "123456"
}
}
```
**节源**
- [sysUser.go](file://api/sysUser/v1/sysUser.go)
- [sysUser_controller.go](file://internal/controller/sysUser/sysUser_v1_user_add.go)
### 角色管理
管理角色定义和权限分配支持角色的增删改查操作
**端点列表**
- `POST /api/v1/sysRole/role/add` - 添加角色
- `DELETE /api/v1/sysRole/role/delete` - 删除角色
- `PUT /api/v1/sysRole/role/edit` - 编辑角色
- `GET /api/v1/sysRole/role/list` - 获取角色列表
**节源**
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
- [sys_role_controller.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
### 菜单管理
管理系统菜单结构和权限规则支持菜单的层级管理和动态配置
**端点列表**
- `POST /api/v1/authority/menu/create` - 创建菜单
- `DELETE /api/v1/authority/menu/delete` - 删除菜单
- `PUT /api/v1/authority/menu/update` - 更新菜单
- `GET /api/v1/authority/menu/list` - 获取菜单列表
**节源**
- [menu.go](file://api/authority/v1/menu.go)
- [authority_controller.go](file://internal/controller/authority/authority_v1_menu_create.go)
## 卡密信息管理模块
卡密信息管理模块支持多种平台的卡密信息管理包括Apple京东沃尔玛C-Trip和天猫游戏等
### Apple卡密管理
提供Apple卡密的全生命周期管理包括卡密的创建查询更新和删除
**端点列表**
- `POST /api/v1/card_info_apple/card/info/create` - 创建Apple卡密
- `GET /api/v1/card_info_apple/card/info/list` - 获取卡密列表
- `PUT /api/v1/card_info_apple/card/info/update` - 更新卡密信息
- `DELETE /api/v1/card_info_apple/card/info/delete` - 删除卡密
- `PUT /api/v1/card_info_apple/card/info/suspend_or_continue` - 暂停/继续卡密
**请求参数说明**
- `cardNumber`: 卡密号码
- `password`: 卡密密码
- `status`: 卡密状态1:启用, 0:禁用
- `batchId`: 批次ID
**节源**
- [card_info_apple.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_controller.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
### 京东卡密管理
管理京东平台的卡密信息支持批量操作和历史记录查询
**端点列表**
- `POST /api/v1/card_info_jd/jd/account/create` - 创建京东账号
- `GET /api/v1/card_info_jd/jd/account/list` - 获取账号列表
- `PUT /api/v1/card_info_jd/jd/account/update` - 更新账号信息
- `POST /api/v1/card_info_jd/jd/account/cookie/batch/add` - 批量添加Cookie
- `GET /api/v1/card_info_jd/jd/account/wallet/list` - 获取钱包列表
**节源**
- [card_info_jd.go](file://api/card_info_jd/v1/account.go)
- [card_info_jd_controller.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
### 沃尔玛卡密管理
提供沃尔玛平台卡密的全面管理功能
**端点列表**
- `POST /api/v1/card_info_walmart/account/create` - 创建沃尔玛账号
- `GET /api/v1/card_info_walmart/account/list` - 获取账号列表
- `PUT /api/v1/card_info_walmart/account/update` - 更新账号信息
- `GET /api/v1/card_info_walmart/account/wallet/list` - 获取钱包列表
- `GET /api/v1/card_info_walmart/order/summary/list` - 订单汇总列表
**节源**
- [card_info_walmart.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_controller.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
### C-Trip卡密管理
管理C-Trip平台的卡密信息
**端点列表**
- `POST /api/v1/card_info_c_trip/account/create` - 创建C-Trip账号
- `GET /api/v1/card_info_c_trip/account/list` - 获取账号列表
- `PUT /api/v1/card_info_c_trip/account/update` - 更新账号信息
- `POST /api/v1/card_info_c_trip/account/cookie/batch/add` - 批量添加Cookie
**节源**
- [card_info_c_trip.go](file://api/card_info_c_trip/v1/account.go)
- [card_info_c_trip_controller.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
### 天猫游戏卡密管理
提供天猫游戏平台卡密的管理功能
**端点列表**
- `POST /api/v1/card_info_t_mall_game/t_mall_game/account/create` - 创建天猫游戏账号
- `GET /api/v1/card_info_t_mall_game/t_mall_game/account/list` - 获取账号列表
- `PUT /api/v1/card_info_t_mall_game/t_mall_game/account/toggle` - 切换账号状态
- `GET /api/v1/card_info_t_mall_game/t_mall_game/order/list` - 获取订单列表
- `POST /api/v1/card_info_t_mall_game/t_mall_game/order/submit` - 提交订单
**节源**
- [card_info_t_mall_game.go](file://api/card_info_t_mall_game/v1/account.go)
- [card_info_t_mall_game_controller.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go)
## 订单处理模块
订单处理模块负责所有平台的订单生命周期管理包括订单创建查询更新和回调处理
### 订单管理
提供统一的订单管理接口支持多平台订单的集中处理
**端点列表**
- `POST /api/v1/order/form/create` - 创建订单
- `GET /api/v1/order/form/list` - 获取订单列表
- `PUT /api/v1/order/form/update` - 更新订单
- `DELETE /api/v1/order/form/delete` - 删除订单
- `GET /api/v1/order/summary/get/list` - 获取订单汇总
**请求参数说明**
- `orderId`: 订单ID
- `platform`: 平台类型apple, jd, walmart等
- `amount`: 订单金额
- `status`: 订单状态
- `userId`: 用户ID
**响应格式**
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"orderId": "ORD123456",
"platform": "apple",
"amount": 100.00,
"status": "completed",
"createdAt": "2023-01-01T00:00:00Z"
}
],
"total": 1
}
}
```
**节源**
- [order.go](file://api/order/v1/form.go)
- [order_controller.go](file://internal/controller/order/order_v1_order_form_create.go)
### 订单历史
管理订单的历史记录和日志
**端点列表**
- `GET /api/v1/order/log/list` - 获取订单日志列表
- `DELETE /api/v1/order/log/delete` - 删除订单日志
- `GET /api/v1/order/summary/daily/get/list` - 获取每日订单汇总
**节源**
- [log.go](file://api/order/v1/log.go)
- [order_controller.go](file://internal/controller/order/order_v1_order_log_list.go)
## 商户管理模块
商户管理模块提供商户配置部署和订单处理功能
### 商户配置
管理商户的基本信息和配置参数
**端点列表**
- `POST /api/v1/merchant/config/add` - 添加商户配置
- `GET /api/v1/merchant/config/list` - 获取商户配置列表
- `PUT /api/v1/merchant/config/update` - 更新商户配置
- `PUT /api/v1/merchant/config/status` - 更新商户配置状态
**节源**
- [config.go](file://api/merchant/v1/config.go)
- [merchant_controller.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go)
### 商户部署
管理商户的部署信息和状态
**端点列表**
- `POST /api/v1/merchant/deploy/add` - 添加商户部署
- `GET /api/v1/merchant/deploy/list` - 获取部署列表
- `PUT /api/v1/merchant/deploy/update` - 更新部署信息
- `DELETE /api/v1/merchant/deploy/delete` - 删除部署
**节源**
- [deploy.go](file://api/merchant/v1/deploy.go)
- [merchant_controller.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go)
### 商户订单
处理商户相关的订单查询和统计
**端点列表**
- `GET /api/v1/merchant/order/query` - 查询商户订单
- `GET /api/v1/merchant/steal/stats` - 获取商户抢单统计
- `GET /api/v1/merchant/steal/record/list` - 获取抢单记录列表
**节源**
- [order.go](file://api/merchant/v1/order.go)
- [merchant_controller.go](file://internal/controller/merchant/merchant_v1_order_query.go)
## 系统监控模块
系统监控模块提供健康检查和系统状态监控功能
### 健康检查
提供系统健康状态的检查接口
**端点列表**
- `GET /api/v1/monitor/health/check` - 健康检查
**响应示例**
```json
{
"code": 0,
"message": "OK",
"data": {
"status": "healthy",
"timestamp": "2023-01-01T00:00:00Z",
"services": {
"database": "connected",
"cache": "connected",
"message_queue": "connected"
}
}
}
```
**节源**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [monitor_controller.go](file://internal/controller/monitor/monitor_v1_health_check.go)
## 限制管理模块
限制管理模块提供IP限制区域限制和用户信息收集功能
### IP限制管理
管理IP访问限制规则
**端点列表**
- `GET /api/v1/restriction/check/ip/allowed` - 检查IP是否允许访问
- `POST /api/v1/restriction/block/order` - 阻止订单
- `GET /api/v1/restriction/query/all/province` - 查询所有省份
**节源**
- [restriction.go](file://api/restriction/v1/province.go)
- [restriction_controller.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
### 用户信息收集
管理用户信息收集规则
**端点列表**
- `POST /api/v1/restriction/user/info/collection` - 用户信息收集
**节源**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_controller.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
## 认证与安全
系统采用基于JWT的认证机制所有API端点都需要有效的认证令牌
### 认证机制
- **认证方式**: Bearer Token
- **令牌类型**: JWT
- **有效期**: 24小时
- **刷新机制**: 支持令牌刷新
### 认证头
所有请求需要在HTTP头中包含认证信息
```
Authorization: Bearer <token>
```
### 安全考虑
- 所有API通信必须通过HTTPS
- 敏感数据在传输过程中必须加密
- 密码等敏感信息在存储时必须哈希处理
- 实施CSRF防护机制
- 定期进行安全审计和漏洞扫描
**节源**
- [auth.go](file://internal/middleware/auth.go)
- [token.go](file://utility/token/user_token.go)
## 错误处理策略
系统采用统一的错误处理机制所有错误响应遵循标准格式
### 错误响应格式
```json
{
"code": 1001,
"message": "订单不存在",
"data": null
}
```
### 常见错误码
| 错误码 | 错误信息 | 说明 |
|--------|---------|------|
| 1001 | 订单不存在 | 请求的订单ID不存在 |
| 1002 | 账号不存在 | 请求的账号ID不存在 |
| 1003 | 账号已存在 | 尝试创建已存在的账号 |
| 1004 | 订单已支付 | 订单状态已经是支付完成 |
| 1005 | 卡密错误 | 卡密号码或密码错误 |
| 1006 | 上传账号失败当日已上传过 | 当天已经上传过账号 |
| 2006 | 文件损坏 | 上传的文件格式不正确或损坏 |
| 3001 | 用户名或密码错误 | 登录凭据不正确 |
| 3002 | 用户不存在 | 请求的用户ID不存在 |
| 3003 | 用户被禁用 | 用户账户已被禁用 |
| 3004 | 用户未激活 | 用户账户尚未激活 |
| 3005 | 用户不存在或已被禁用 | 用户不存在或已被禁用 |
| 3006 | 密码错误 | 密码不正确 |
| 3007 | 二步验证错误 | 两步验证代码不正确 |
| 4001 | 操作被禁止 | 当前用户没有权限执行此操作 |
| 5001 | token错误 | 认证令牌不正确 |
| 5002 | token过期 | 认证令牌已过期 |
| 5003 | token不存在 | 请求中缺少认证令牌 |
| 6001 | ck失效 | Cookie已失效 |
**节源**
- [handler.go](file://internal/errHandler/handler.go)
- [code.go](file://internal/errHandler/code.go)
## 速率限制
系统实施基于Redis的速率限制机制防止API滥用和DDoS攻击
### 速率限制策略
- **全局限制**: 每分钟最多1000次请求
- **用户限制**: 每个用户每分钟最多100次请求
- **IP限制**: 每个IP地址每分钟最多500次请求
### 限流类型
| 限流类型 | 说明 | 限制值 |
|---------|------|-------|
| cardInfo:jd:account:cookie | 京东账号Cookie检查 | 10/分钟 |
| cardInfo:jd:account:cookie:set | 京东账号Cookie设置 | 5/分钟 |
| cardInfo:account:cookie:checker | 通用账号Cookie检查 | 15/分钟 |
| cardInfo:account:cookie:set | 通用账号Cookie设置 | 8/分钟 |
### 限流响应头
当接近限流阈值时响应头中会包含以下信息
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 10
X-RateLimit-Reset: 60
```
**节源**
- [limiter.go](file://internal/service/limiter.go)
- [rate.go](file://utility/limiter/rate.go)
- [redis.go](file://utility/limiter/redis.go)
## 客户端实现指南
本节提供客户端实现的最佳实践和示例代码
### 请求示例 (Python)
```python
import requests
import json
url = "https://api.example.com/api/v1/card_info_apple/card/info/create"
headers = {
"Authorization": "Bearer your_token_here",
"Content-Type": "application/json"
}
data = {
"cardNumber": "1234567890",
"password": "your_password",
"status": 1
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
```
### 请求示例 (JavaScript)
```javascript
const url = 'https://api.example.com/api/v1/card_info_apple/card/info/create';
const options = {
method: 'POST',
headers: {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'application/json'
},
body: JSON.stringify({
cardNumber: '1234567890',
password: 'your_password',
status: 1
})
};
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
### 错误处理示例
```python
def handle_api_response(response):
if response.status_code == 200:
data = response.json()
if data['code'] == 0:
return data['data']
else:
error_code = data['code']
error_message = data['message']
# 根据错误码进行相应处理
if error_code == 5002: # token过期
refresh_token()
retry_request()
elif error_code == 4001: # 操作被禁止
show_permission_error()
else:
show_error(error_message)
else:
handle_network_error()
```
## 性能优化建议
为确保API的高性能和可扩展性建议遵循以下最佳实践
### 批量操作
对于大量数据的操作建议使用批量接口而不是单个请求
- 使用`/batch/add`接口批量添加卡密
- 使用`/batch/update`接口批量更新状态
- 避免在循环中调用单个创建接口
### 分页查询
对于列表查询务必使用分页参数
```json
{
"current": 1,
"pageSize": 50
}
```
建议`pageSize`不超过100避免单次请求返回过多数据
### 缓存策略
- 对于不经常变化的数据客户端应实施本地缓存
- 使用ETag或Last-Modified头进行条件请求
- 设置合理的缓存过期时间
### 连接复用
- 使用HTTP Keep-Alive保持连接
- 实施连接池管理
- 避免频繁创建和销毁连接
### 异步处理
对于耗时较长的操作建议使用异步模式
1. 提交请求并获取任务ID
2. 通过轮询或WebSocket获取处理状态
3. 处理完成后获取结果
### 监控与日志
- 记录关键操作的执行时间
- 监控API的响应时间和错误率
- 设置告警阈值及时发现性能问题

View File

@@ -0,0 +1,252 @@
# Apple卡密充值处理
<cite>
**本文档引用文件**
- [order.go](file://api/card_info_apple/v1/order.go)
- [order_history.go](file://api/card_info_apple/v1/order_history.go)
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [account_history.go](file://api/card_info_apple/v1/account_history.go)
- [config.go](file://api/card_info_apple/v1/config.go)
- [model.go](file://api/card_info_apple/v1/model.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心API端点](#核心api端点)
3. [充值订单状态机与生命周期](#充值订单状态机与生命周期)
4. [iTunes回调机制](#itunes回调机制)
5. [数据验证与安全机制](#数据验证与安全机制)
6. [重复卡密与防刷单策略](#重复卡密与防刷单策略)
7. [配置管理](#配置管理)
8. [历史记录查询](#历史记录查询)
9. [错误处理与性能优化](#错误处理与性能优化)
## 简介
本文档详细说明Apple卡密充值处理系统的API设计工作流程状态管理及安全机制系统支持商户提交Apple礼品卡充值请求通过后台任务轮询分配至合适的iTunes账户进行处理并提供完整的回调机制历史查询和防刷单策略重点描述了高并发场景下的稳定性保障措施
## 核心API端点
### 充值提交接口
- **HTTP方法**: `POST`
- **URL模式**: `/cardInfo/appleCard/submit`
- **认证机制**: 请求签名验证基于`merchantId``attach``cardPass``timeStamp`生成
- **请求参数**:
- `cardNo`: 卡号
- `cardPass`: 卡密
- `faceValue`: 面值单位
- `callbackUrl`: 回调地址
- `attach`: 附加信息上游订单号
- `timeStamp`: 时间戳
- `sign`: 签名
- `merchantId`: 商户ID
- **响应结构**:
- `orderNo`: 系统生成的订单号
- `status`: 充值状态码
- `message`: 详细描述信息
**Section sources**
- [order.go](file://api/card_info_apple/v1/order.go#L10-L45)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L15-L70)
### 充值订单查询接口
- **HTTP方法**: `GET`
- **URL模式**: `/cardInfo/appleCard/query`
- **请求参数**:
- `orderNo`: 订单ID必填
- **响应结构**:
- `status`: 当前订单状态
- `message`: 状态描述
**Section sources**
- [order.go](file://api/card_info_apple/v1/order.go#L47-L57)
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
### 回调处理接口
- **HTTP方法**: `POST`
- **URL模式**: `/cardInfo/appleCard/rechargeOrder/callback`
- **请求参数**:
- `amount`: 实际充值金额
- `accountAmount`: 充值后账户余额
- `accountId`: 账户ID
- `machineId`: 机器ID
- `orderNo`: 订单ID
- `status`: 充值状态枚举值
- `remark`: 备注信息
- **响应结构**: 空对象
**Section sources**
- [order.go](file://api/card_info_apple/v1/order.go#L77-L97)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
### 轮询处理接口
- **HTTP方法**: `POST`
- **URL模式**: `/cardInfo/appleCard/rechargeOrder/handler`
- **用途**: 供后台处理机轮询获取待处理的充值订单
- **请求参数**:
- `machineId`: 机器ID必填
- **响应结构**:
- `orderNo`: 订单ID
- `cardNo`: 卡号
- `cardPass`: 卡密
- `account`: iTunes账户
- `password`: 账户密码
- `accountId`: 账户ID
**Section sources**
- [order.go](file://api/card_info_apple/v1/order.go#L59-L75)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L15-L188)
## 充值订单状态机与生命周期
```mermaid
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中 : 分配账户
处理中 --> 充值成功 : 回调成功
处理中 --> 充值失败 : 回调失败
处理中 --> 超时等待 : 1分钟未完成
超时等待 --> 处理中 : 重新分配
充值成功 --> [*]
充值失败 --> [*]
```
**Diagram sources**
- [order.go](file://api/card_info_apple/v1/order.go#L77-L97)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L100-L150)
## iTunes回调机制
系统通过以下流程处理iTunes充值回调
1. 后台处理机执行充值操作
2. 成功后调用 `/cardInfo/appleCard/rechargeOrder/callback` 接口
3. 系统验证回调数据并更新订单状态
4. 根据配置决定是否向商户`callbackUrl`发起二次回调
5. 记录充值历史和账户余额变化
**Section sources**
- [order.go](file://api/card_info_apple/v1/order.go#L77-L97)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
## 数据验证与安全机制
### 签名验证
请求必须包含签名使用以下参数生成
```
sign = MD5(attach + cardPass + timeStamp)
```
### 卡密格式验证
系统对卡密进行格式校验确保符合Apple卡密规范
### 幂等性控制
使用Redis缓存防止同一商户ID在短时间内重复提交相同订单
```mermaid
flowchart TD
A[接收充值请求] --> B{验证签名}
B --> |失败| C[返回验证错误]
B --> |成功| D{卡密格式校验}
D --> |失败| E[返回卡密错误]
D --> |成功| F{检查重复订单}
F --> |存在| G[返回处理中]
F --> |不存在| H[创建订单并返回成功]
```
**Diagram sources**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L20-L50)
## 重复卡密与防刷单策略
### 重复订单检测
- 基于`merchantId`在10秒内设置Redis锁防止重复提交
- 系统级卡密去重可配置
### 偷单机制
当系统配置启用偷单功能时
1. 检查当前订单是否符合偷单规则
2. 若符合将订单分配给指定存储账户
3. 为原订单创建替代订单实现订单转移
**Section sources**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L20-L35)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L80-L120)
## 配置管理
### 获取配置
- **HTTP方法**: `GET`
- **URL模式**: `/cardInfo/AppleCard/config/get`
- **响应参数**:
- `isAllowDifferentAmount`: 是否允许金额异议充值
- `isAllowDifferentSucceedCallback`: 是否允许成功时金额异议回调
- `isAllowDifferentFailCallback`: 是否允许失败时金额异议回调
- `redeemCardMinAmount`: 最小充值金额
- `isAllowCompensatedCallback`: 是否允许补卡自动回调
- `redeemCardRate`: 充值速率限制
### 设置配置
- **HTTP方法**: `POST`
- **URL模式**: `/cardInfo/AppleCard/config/set`
- 所有参数均为必填
**Section sources**
- [config.go](file://api/card_info_apple/v1/config.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
## 历史记录查询
### 充值历史查询
- **HTTP方法**: `GET`
- **URL模式**: `/cardInfo/AppleCard/rechargeOrder/getHistoryList`
- **请求参数**: `orderNo`必填
- **响应结构**: 包含每次充值的详细记录
### 账户余额历史
- **HTTP方法**: `GET`
- **URL模式**: `/cardInfo/AppleCard/account/getWalletList`
- **响应结构**: 包含余额变化记录包括
- 充值前余额
- 充值后余额
- 充值金额
- 操作时间
**Section sources**
- [order_history.go](file://api/card_info_apple/v1/order_history.go)
- [account_history.go](file://api/card_info_apple/v1/account_history.go)
## 错误处理与性能优化
### 错误处理策略
- 统一错误码体系基于gcode
- 详细的错误包装和日志记录
- 客户端友好的错误消息
### 高并发优化
- Redis缓存实现请求幂等性
- 数据库事务保证状态一致性
- 定时任务避免长时间阻塞
- 读写锁控制并发访问
### 系统稳定性
- 订单处理超时自动恢复机制
- 数据库连接池优化
- 关键操作日志追踪OpenTelemetry
**Section sources**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [utility/otel](file://utility/otel)

View File

@@ -0,0 +1,876 @@
# Apple卡密管理API
<cite>
**本文档引用的文件**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
- [model.go](file://api/card_info_apple/v1/model.go)
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [card_info_apple_v1_recharge_steal_rule_add.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_add.go)
- [card_info_apple_v1_recharge_steal_rule_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_list.go)
- [card_info_apple_v1_recharge_steal_setting.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
- [card_info_apple_v1_call_back_order_manual.go](file://internal/controller/card_info_apple/card_info_apple_v1_call_back_order_manual.go)
- [card_info_apple_v1_recharge_order_modify_actual_amount.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_modify_actual_amount.go)
- [card_info_apple_v1_recharge_order_reset_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_reset_status.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_recharge_list_download.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list_download.go)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
- [card_info_apple_v1_recharge_steal_rule_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_update.go)
- [card_info_apple_v1_recharge_steal_rule_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_delete.go)
- [card_info_apple_v1_recharge_steal_rule_status_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_status_update.go)
- [card_info_apple_v1_recharge_steal_setting_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting_get.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [card_info_apple_v1_recharge_steal_rule_add.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_add.go)
- [card_info_apple_v1_recharge_steal_rule_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_list.go)
- [card_info_apple_v1_recharge_steal_setting.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
- [card_info_apple_v1_call_back_order_manual.go](file://internal/controller/card_info_apple/card_info_apple_v1_call_back_order_manual.go)
- [card_info_apple_v1_recharge_order_modify_actual_amount.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_modify_actual_amount.go)
- [card_info_apple_v1_recharge_order_reset_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_reset_status.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_recharge_list_download.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list_download.go)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
- [card_info_apple_v1_recharge_steal_rule_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_update.go)
- [card_info_apple_v1_recharge_steal_rule_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_delete.go)
- [card_info_apple_v1_recharge_steal_rule_status_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_status_update.go)
- [card_info_apple_v1_recharge_steal_setting_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting_get.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [card_info_apple_v1_recharge_steal_rule_add.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_add.go)
- [card_info_apple_v1_recharge_steal_rule_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_list.go)
- [card_info_apple_v1_recharge_steal_setting.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
- [card_info_apple_v1_call_back_order_manual.go](file://internal/controller/card_info_apple/card_info_apple_v1_call_back_order_manual.go)
- [card_info_apple_v1_recharge_order_modify_actual_amount.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_modify_actual_amount.go)
- [card_info_apple_v1_recharge_order_reset_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_reset_status.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_recharge_list_download.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list_download.go)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
- [card_info_apple_v1_recharge_steal_rule_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_update.go)
- [card_info_apple_v1_recharge_steal_rule_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_delete.go)
- [card_info_apple_v1_recharge_steal_rule_status_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_status_update.go)
- [card_info_apple_v1_recharge_steal_setting_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting_get.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
Apple卡密管理API是一个全面的系统用于管理Apple卡密的账户充值处理和订单回调该API提供了账户创建状态管理充值提交和历史查询等端点它还支持批量导入卡密充值状态查询和重复卡密处理等场景文档详细解释了Apple卡密特有的iTunes回调机制和防刷单规则并提供了错误处理策略和安全考虑此外还包括客户端实现指南和性能优化建议特别关注Apple平台的特殊要求和限制
## 项目结构
项目结构遵循模块化设计将不同功能分离到不同的目录中主要目录包括`api``internal``manifest``resource``utility``api`目录包含所有API端点的定义`internal`目录包含核心业务逻辑数据访问对象DAO和服务`manifest`目录包含配置文件`resource`目录包含Casbin权限模型`utility`目录包含各种实用工具和集成
```mermaid
graph TD
subgraph "API"
A[card_info_apple]
B[card_info_c_trip]
C[card_info_jd]
D[card_info_original_jd]
E[card_info_t_mall_game]
F[card_info_walmart]
G[card_redeem_jd]
H[channel]
I[commonApi]
J[fund]
K[merchant]
L[monitor]
M[order]
N[restriction]
O[road]
P[road_pool]
Q[sysUser]
R[sys_auth_rule]
S[sys_payment]
T[sys_role]
U[sys_user_login]
V[user_center]
W[validation]
end
subgraph "Internal"
X[boot]
Y[cmd]
Z[consts]
AA[controller]
AB[dao]
AC[errHandler]
AD[logic]
AE[middleware]
AF[model]
AG[packed]
AH[service]
AI[systemV2]
end
subgraph "Manifest"
AJ[config]
AK[deploy]
AL[docker]
end
subgraph "Resource"
AM[casbin]
end
subgraph "Utility"
AN[cache]
AO[config]
AP[cron]
AQ[integration]
AR[lib]
AS[limiter]
AT[mfa]
AU[monitor]
AV[notify]
AW[otel]
AX[pool]
AY[token]
AZ[utils]
BA[verify]
end
A --> AA
B --> AA
C --> AA
D --> AA
E --> AA
F --> AA
G --> AA
H --> AA
I --> AA
J --> AA
K --> AA
L --> AA
M --> AA
N --> AA
O --> AA
P --> AA
Q --> AA
R --> AA
S --> AA
T --> AA
U --> AA
V --> AA
W --> AA
```
**图示来源**
- [api](file://api)
- [internal](file://internal)
- [manifest](file://manifest)
- [resource](file://resource)
- [utility](file://utility)
**章节来源**
- [api](file://api)
- [internal](file://internal)
- [manifest](file://manifest)
- [resource](file://resource)
- [utility](file://utility)
## 核心组件
核心组件包括账户管理充值处理订单回调和配置管理账户管理负责创建更新和删除Apple账户充值处理负责提交和查询充值订单订单回调处理来自iTunes的回调请求配置管理允许用户获取和设置系统配置
**章节来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
## 架构概述
系统架构采用分层设计包括API层控制器层服务层逻辑层和数据访问层API层定义了所有端点控制器层处理HTTP请求并调用服务层服务层协调业务逻辑逻辑层包含具体的业务规则数据访问层负责与数据库交互
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[逻辑层]
D --> E[数据访问层]
E --> F[数据库]
```
**图示来源**
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
## 详细组件分析
### 账户管理分析
账户管理组件负责处理Apple账户的创建更新删除和查询它还支持批量导入和导出账户信息
#### 账户创建
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/account/create
Controller->>Service : 调用Add方法
Service->>Logic : 调用Add方法
Logic->>DAO : 插入新账户
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
#### 账户更新
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : PUT /api/apple/account/update
Controller->>Service : 调用Update方法
Service->>Logic : 调用Update方法
Logic->>DAO : 更新账户信息
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
#### 账户删除
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : DELETE /api/apple/account/delete
Controller->>Service : 调用Delete方法
Service->>Logic : 调用Delete方法
Logic->>DAO : 删除账户
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
#### 批量导入账户
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/account/batch-add
Controller->>Service : 调用Add方法
Service->>Logic : 调用Add方法
loop 每个账户
Logic->>DAO : 插入账户
DAO-->>Logic : 返回结果
end
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
**章节来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
### 充值处理分析
充值处理组件负责提交和查询充值订单它还处理来自iTunes的回调请求
#### 充值提交
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/submit
Controller->>Service : 调用AddRechargeOrder方法
Service->>Logic : 调用AddRechargeOrder方法
Logic->>DAO : 插入充值订单
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
#### 充值查询
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/recharge/list
Controller->>Service : 调用List方法
Service->>Logic : 调用List方法
Logic->>DAO : 查询充值订单
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list.go)
#### iTunes回调处理
```mermaid
sequenceDiagram
participant iTunes as "iTunes"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
iTunes->>Controller : POST /api/apple/recharge/itunes-callback
Controller->>Service : 调用UpdateActualAmountAndHistoryAndWallet方法
Service->>Logic : 调用UpdateActualAmountAndHistoryAndWallet方法
Logic->>DAO : 更新充值订单和账户余额
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>iTunes : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
**章节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
### 配置管理分析
配置管理组件允许用户获取和设置系统配置
#### 获取配置
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/config/get
Controller->>Service : 调用GetConfig方法
Service->>Logic : 调用GetConfig方法
Logic->>DAO : 查询配置
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
#### 设置配置
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/config/set
Controller->>Service : 调用SetConfig方法
Service->>Logic : 调用SetConfig方法
Logic->>DAO : 更新配置
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
**章节来源**
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
### 偷卡规则分析
偷卡规则组件允许用户管理偷卡规则包括添加更新删除和查询规则
#### 添加偷卡规则
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/steal-rule/add
Controller->>Service : 调用AddStealRule方法
Service->>Logic : 调用AddStealRule方法
Logic->>DAO : 插入偷卡规则
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_steal_rule_add.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_add.go)
#### 查询偷卡规则
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/recharge/steal-rule/list
Controller->>Service : 调用GetStealRuleList方法
Service->>Logic : 调用GetStealRuleList方法
Logic->>DAO : 查询偷卡规则
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_steal_rule_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_list.go)
#### 更新偷卡规则
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : PUT /api/apple/recharge/steal-rule/update
Controller->>Service : 调用UpdateStealRule方法
Service->>Logic : 调用UpdateStealRule方法
Logic->>DAO : 更新偷卡规则
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_steal_rule_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_update.go)
#### 删除偷卡规则
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : DELETE /api/apple/recharge/steal-rule/delete
Controller->>Service : 调用DeleteStealRule方法
Service->>Logic : 调用DeleteStealRule方法
Logic->>DAO : 删除偷卡规则
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_steal_rule_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_delete.go)
**章节来源**
- [card_info_apple_v1_recharge_steal_rule_add.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_add.go)
- [card_info_apple_v1_recharge_steal_rule_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_list.go)
- [card_info_apple_v1_recharge_steal_rule_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_update.go)
- [card_info_apple_v1_recharge_steal_rule_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_delete.go)
- [card_info_apple_v1_recharge_steal_rule_status_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_rule_status_update.go)
- [card_info_apple_v1_recharge_steal_setting.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting.go)
- [card_info_apple_v1_recharge_steal_setting_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_steal_setting_get.go)
### 重复卡密处理分析
重复卡密处理组件负责处理重复提交的卡密
#### 检查重复卡密
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/duplicated-card-pass
Controller->>Service : 调用QueryDuplicatedCardPassV2方法
Service->>Logic : 调用QueryDuplicatedCardPassV2方法
Logic->>DAO : 查询重复卡密
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
**章节来源**
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
### 手动回调订单分析
手动回调订单组件允许用户手动回调订单
#### 手动回调订单
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/call-back-order-manual
Controller->>Service : 调用CallBackOrderToUpstream方法
Service->>Logic : 调用CallBackOrderToUpstream方法
Logic->>DAO : 查询订单并回调
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_call_back_order_manual.go](file://internal/controller/card_info_apple/card_info_apple_v1_call_back_order_manual.go)
**章节来源**
- [card_info_apple_v1_call_back_order_manual.go](file://internal/controller/card_info_apple/card_info_apple_v1_call_back_order_manual.go)
### 充值订单状态修改分析
充值订单状态修改组件允许用户修改充值订单的状态
#### 修改充值订单状态
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/order-modify-actual-amount
Controller->>Service : 调用UpdateActualAmount方法
Service->>Logic : 调用UpdateActualAmount方法
Logic->>DAO : 更新订单状态
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_order_modify_actual_amount.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_modify_actual_amount.go)
**章节来源**
- [card_info_apple_v1_recharge_order_modify_actual_amount.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_modify_actual_amount.go)
### 充值订单状态重置分析
充值订单状态重置组件允许用户重置充值订单的状态
#### 重置充值订单状态
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/order-reset-status
Controller->>Service : 调用ResetDistributionCount方法
Service->>Logic : 调用ResetDistributionCount方法
Logic->>DAO : 重置订单状态
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_order_reset_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_reset_status.go)
**章节来源**
- [card_info_apple_v1_recharge_order_reset_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_order_reset_status.go)
### 账户状态暂停或继续分析
账户状态暂停或继续组件允许用户暂停或继续账户的状态
#### 暂停或继续账户状态
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/account/suspend-or-continue
Controller->>Service : 调用ModifyStatus方法
Service->>Logic : 调用ModifyStatus方法
Logic->>DAO : 更新账户状态
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
**章节来源**
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
### 充值历史查询分析
充值历史查询组件允许用户查询充值历史
#### 查询充值历史
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/recharge/history-list
Controller->>Service : 调用GetRechargeDetails方法
Service->>Logic : 调用GetRechargeDetails方法
Logic->>DAO : 查询充值历史
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
**章节来源**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
### 充值列表下载分析
充值列表下载组件允许用户下载充值列表
#### 下载充值列表
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/recharge/list-download
Controller->>Service : 调用ListWithAccount方法
Service->>Logic : 调用ListWithAccount方法
Logic->>DAO : 查询充值列表
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_list_download.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list_download.go)
**章节来源**
- [card_info_apple_v1_recharge_list_download.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_list_download.go)
### 账户历史信息查询分析
账户历史信息查询组件允许用户查询账户历史信息
#### 查询账户历史信息
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/account/history-info-list
Controller->>Service : 调用GetWalletHistory方法
Service->>Logic : 调用GetWalletHistory方法
Logic->>DAO : 查询账户历史信息
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
**章节来源**
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
### 充值处理分析
充值处理组件负责处理充值请求
#### 处理充值请求
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : POST /api/apple/recharge/handler
Controller->>Service : 调用HandleWaitingList方法
Service->>Logic : 调用HandleWaitingList方法
Logic->>DAO : 处理等待中的充值订单
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
**章节来源**
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
### 充值提交查询分析
充值提交查询组件允许用户查询充值提交的状态
#### 查询充值提交状态
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务"
participant Logic as "逻辑"
participant DAO as "数据访问对象"
Client->>Controller : GET /api/apple/recharge/submit-query
Controller->>Service : 调用GetRechargeStatusByOrderNo方法
Service->>Logic : 调用GetRechargeStatusByOrderNo方法
Logic->>DAO : 查询充值提交状态
DAO-->>Logic : 返回结果
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功或错误
```
**图示来源**
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
**章节来源**
- [card_info_apple_v1_recharge_submit_query.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit_query.go)
## 依赖分析
系统依赖于多个外部组件和库包括GoFrame框架GDB数据库驱动ShopSpring Decimal库等这些依赖项在`go.mod`文件中定义并通过Go模块系统进行管理
```mermaid
graph TD
A[Apple卡密管理API] --> B[GoFrame框架]
A --> C[GDB数据库驱动]
A --> D[ShopSpring Decimal库]
A --> E[Casbin权限库]
A --> F[Redis缓存]
A --> G[MySQL数据库]
```
**图示来源**
- [go.mod](file://go.mod)
- [go.sum](file://go.sum)
**章节来源**
- [go.mod](file://go.mod)
- [go.sum](file://go.sum)
## 性能考虑
为了确保系统的高性能采用了多种优化策略包括使用Redis缓存频繁访问的数据使用数据库索引优化查询性能使用并发处理提高处理速度以及使用连接池管理数据库连接
**章节来源**
- [utility/cache](file://utility/cache)
- [utility/limiter](file://utility/limiter)
- [utility/pool](file://utility/pool)
## 故障排除指南
### 常见问题
1. **账户创建失败**检查请求参数是否正确特别是账户名和密码
2. **充值提交失败**检查卡密是否正确以及账户是否有足够的余额
3. **回调失败**检查回调URL是否正确以及服务器是否能够接收POST请求
4. **配置更新失败**检查配置参数是否在允许范围内
### 错误处理
系统使用统一的错误处理机制所有错误都通过`errHandler`包进行处理错误码和错误信息在`errHandler/code.go`文件中定义
**章节来源**
- [internal/errHandler/code.go](file://internal/errHandler/code.go)
- [internal/errHandler/handler.go](file://internal/errHandler/handler.go)
## 结论
Apple卡密管理API提供了一套完整的解决方案用于管理Apple卡密的账户充值和订单回调通过详细的文档和示例用户可以轻松地集成和使用该API系统设计考虑了性能安全性和可扩展性确保在高负载下仍能稳定运行

View File

@@ -0,0 +1,412 @@
# Apple卡密账户管理
<cite>
**本文档引用的文件**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_apple_account.go](file://internal/model/card_apple_account.go)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [account.go](file://internal/logic/card_apple_account/account.go)
- [card_apple.go](file://internal/consts/card_apple.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心功能](#核心功能)
3. [数据模型](#数据模型)
4. [API端点](#api端点)
5. [账户状态管理](#账户状态管理)
6. [批量操作](#批量操作)
7. [错误处理](#错误处理)
8. [安全考虑](#安全考虑)
9. [客户端实现指南](#客户端实现指南)
10. [性能优化建议](#性能优化建议)
## 简介
本文档详细介绍了Apple卡密账户管理API的功能和使用方法该API提供了一套完整的账户管理解决方案支持账户的创建查询更新删除等基本操作以及账户状态管理批量导入等高级功能系统设计考虑了大规模账户管理的性能需求提供了相应的优化建议
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
## 核心功能
Apple卡密账户管理API提供以下核心功能
- 账户的增删改查操作
- 账户状态的启用/暂停管理
- 批量导入账户信息
- 账户信息的分页查询
- 账户模板下载
这些功能通过RESTful API接口提供支持标准的HTTP方法和JSON数据格式
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
## 数据模型
### 账户信息数据模型
Apple卡密账户的核心数据模型包含以下字段
| 字段名 | 类型 | 必填 | 描述 | 验证规则 |
|-------|------|------|------|---------|
| account | string | | 账户名 | 必须提供 |
| password | string | | 密码 | 必须提供 |
| maxAmountLimit | int | | 最大充值金额 | 必须提供 |
| maxCountLimit | int | | 最大充值次数 | 必须提供 |
| remark | string | | 备注 | |
| balance | float64 | | 余额 | 只读 |
| status | int32 | | 状态 | 0:停用, 1:正常使用, 2:正在充值, 3:已达到单日充值限制 |
**Section sources**
- [card_apple_account.go](file://internal/model/card_apple_account.go)
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
## API端点
### 账户创建
创建新的Apple卡密账户
**请求信息**
- **HTTP方法**: POST
- **URL模式**: `/cardInfo/AppleCard/account/create`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"account": "string",
"password": "string",
"maxAmountLimit": 0,
"maxCountLimit": 0,
"remark": "string"
}
```
**响应**
- **成功**: 200 OK
- **失败**: 400 Bad Request (参数错误), 401 Unauthorized (权限不足), 409 Conflict (账号已存在)
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
### 账户查询
查询Apple卡密账户列表
**请求信息**
- **HTTP方法**: GET
- **URL模式**: `/cardInfo/AppleCard/account/getList`
- **认证机制**: 需要有效的用户会话
**查询参数**
| 参数名 | 类型 | 必填 | 描述 |
|-------|------|------|------|
| account | string | | 账户名支持模糊查询 |
| current | int | | 当前页码默认1 |
| pageSize | int | | 每页数量默认10 |
**响应**
```json
{
"total": 0,
"list": [
{
"id": "string",
"account": "string",
"password": "string",
"maxAmountLimit": 0,
"maxCountLimit": 0,
"remark": "string",
"balance": 0,
"status": 0
}
]
}
```
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_v1_card_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_list.go)
### 账户更新
更新现有Apple卡密账户信息
**请求信息**
- **HTTP方法**: PUT
- **URL模式**: `/cardInfo/AppleCard/account/update`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"id": "string",
"account": "string",
"password": "string",
"maxAmountLimit": 0,
"maxCountLimit": 0,
"remark": "string"
}
```
**响应**
- **成功**: 200 OK
- **失败**: 400 Bad Request, 401 Unauthorized, 404 Not Found
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
### 账户删除
删除指定的Apple卡密账户
**请求信息**
- **HTTP方法**: DELETE
- **URL模式**: `/cardInfo/AppleCard/account/delete`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"id": "string"
}
```
**响应**
- **成功**: 200 OK
- **失败**: 400 Bad Request, 401 Unauthorized, 500 Internal Server Error
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
## 账户状态管理
### 修改账户状态
直接修改账户状态
**请求信息**
- **HTTP方法**: PUT
- **URL模式**: `/cardInfo/AppleCard/account/updateStatus`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"id": "string",
"status": 10
}
```
**状态值**
- 10: 正常
- 20: 停用
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
### 暂停/恢复账户充值
切换账户的暂停/恢复状态
**请求信息**
- **HTTP方法**: PUT
- **URL模式**: `/cardInfo/AppleCard/account/status/continueOrRestart`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"id": "string"
}
```
**逻辑说明**
- 如果账户当前状态为"正常"则将其暂停
- 如果账户当前状态为"停用"则将其恢复为正常状态
- 其他状态返回错误
```mermaid
flowchart TD
Start([开始]) --> CheckStatus["检查账户状态"]
CheckStatus --> StatusDecision{"状态是正常吗?"}
StatusDecision --> |是| SetForbidden["设置为停用状态"]
StatusDecision --> |否| StatusIsForbidden{"状态是停用吗?"}
StatusIsForbidden --> |是| SetNormal["设置为正常状态"]
StatusIsForbidden --> |否| ReturnError["返回错误:状态不正确"]
SetForbidden --> End([结束])
SetNormal --> End
ReturnError --> End
```
**Diagram sources**
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
## 批量操作
### 下载导入模板
下载批量导入账户信息的Excel模板
**请求信息**
- **HTTP方法**: GET
- **URL模式**: `/cardInfo/AppleCard/account/downloadTemplate`
- **认证机制**: 需要有效的用户会话
**响应**
- 返回Excel文件MIME类型为`application/vnd.ms-excel`
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_info_apple_v1_card_info_download_template.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_download_template.go)
### 批量导入账户
从Excel文件批量导入Apple卡密账户
**请求信息**
- **HTTP方法**: POST
- **URL模式**: `/cardInfo/AppleCard/account/batchAdd`
- **认证机制**: 需要有效的用户会话
**请求体**
```json
{
"file": "文件对象"
}
```
**文件格式要求**
- Excel文件格式
- 第一行为标题行账号密码最大充值金额最大充值次数备注
- 支持.csv格式
**处理逻辑**
1. 验证文件格式和内容
2. 检查账户是否已存在
3. 批量创建账户
4. 返回导入结果统计
```mermaid
flowchart TD
Start([开始]) --> ValidateFile["验证文件"]
ValidateFile --> ReadFile["读取Excel数据"]
ReadFile --> CheckData["检查数据有效性"]
CheckData --> ProcessRows["逐行处理"]
ProcessRows --> CheckDuplicate["检查重复"]
CheckDuplicate --> |已存在| SkipRow["跳过该行"]
CheckDuplicate --> |不存在| CreateAccount["创建账户"]
CreateAccount --> UpdateCounters["更新计数器"]
UpdateCounters --> NextRow["处理下一行"]
NextRow --> MoreRows{"还有更多行吗?"}
MoreRows --> |是| ProcessRows
MoreRows --> |否| GenerateResult["生成结果"]
GenerateResult --> ReturnResult["返回结果"]
SkipRow --> NextRow
ReturnResult --> End([结束])
```
**Diagram sources**
- [card_info_apple_v1_card_info_batch_add_from_xlsx.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_batch_add_from_xlsx.go)
## 错误处理
### 常见错误码
| 错误码 | 描述 | 解决方案 |
|-------|------|---------|
| 400 | 参数错误 | 检查请求参数是否符合要求 |
| 401 | 权限不足 | 确保已正确登录并具有相应权限 |
| 404 | 资源未找到 | 检查ID是否正确 |
| 409 | 账号已存在 | 使用不同的账户名 |
| 500 | 服务器内部错误 | 联系管理员 |
### 验证规则
- 账户名和密码为必填项
- 账户名不能重复
- 最大充值金额和次数不能为空
- 状态值必须在允许范围内
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [card_apple.go](file://internal/consts/card_apple.go)
## 安全考虑
### 认证机制
所有API端点都需要用户认证通过会话令牌验证用户身份
### 数据验证
- 输入参数严格验证
- 防止SQL注入
- 限制文件上传类型和大小
### 敏感信息保护
- 密码在传输过程中加密
- 敏感操作需要二次确认
- 操作日志记录
**Section sources**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
## 客户端实现指南
### 基本使用示例
```javascript
// 创建账户
fetch('/cardInfo/AppleCard/account/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify({
account: 'apple_user',
password: 'secure_password',
maxAmountLimit: 1000,
maxCountLimit: 10
})
});
// 查询账户列表
fetch('/cardInfo/AppleCard/account/getList?account=apple', {
method: 'GET',
headers: {
'Authorization': 'Bearer your-token'
}
});
```
### 批量导入示例
```javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/cardInfo/AppleCard/account/batchAdd', {
method: 'POST',
headers: {
'Authorization': 'Bearer your-token'
},
body: formData
});
```
**Section sources**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
## 性能优化建议
### 大规模账户管理
当管理大量账户时建议采取以下优化措施
1. **批量操作**: 尽可能使用批量导入功能减少API调用次数
2. **分页查询**: 使用分页参数避免一次性获取过多数据
3. **缓存策略**: 对频繁查询的数据进行缓存
4. **异步处理**: 对耗时操作采用异步处理模式
### 数据库优化
- 确保账户名字段有索引
- 定期清理历史数据
- 监控查询性能
### 系统监控
- 监控API响应时间
- 跟踪错误率
- 设置适当的超时机制
**Section sources**
- [account.go](file://internal/logic/card_apple_account/account.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)

View File

@@ -0,0 +1,204 @@
# Apple卡密配置管理
<cite>
**本文档引用的文件**
- [config.go](file://api/card_info_apple/v1/config.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [card_apple.go](file://internal/consts/card_apple.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排查指南](#故障排查指南)
9. [结论](#结论)
10. [附录](#附录)如有必要
## 简介
本文档详细说明了Apple卡密配置管理API的设计与实现涵盖配置获取设置等端点的HTTP方法URL模式请求/响应模式和认证机制文档详细解释了Apple卡密服务的各项可配置参数包括充值超时时间回调重试策略防刷单规则阈值等并提供实际使用示例同时文档还包含最佳实践建议安全考虑和故障排查指南特别关注配置变更对现有服务的影响评估
## 项目结构
Apple卡密配置管理功能主要分布在`api/card_info_apple/v1``internal/controller/card_info_apple`目录下核心配置接口定义在`api/card_info_apple/v1/config.go`控制器实现位于`internal/controller/card_info_apple`目录下配置数据的持久化和业务逻辑处理通过`internal/service/sys_config_dict.go`中的服务接口完成
```mermaid
graph TB
subgraph "API接口层"
config_go[config.go]
end
subgraph "控制器层"
config_get[card_info_apple_v1_config_get.go]
config_set[card_info_apple_v1_config_set.go]
end
subgraph "服务层"
sys_config_dict[sys_config_dict.go]
end
subgraph "常量定义"
card_apple[card_apple.go]
end
config_go --> config_get
config_go --> config_set
config_get --> sys_config_dict
config_set --> sys_config_dict
card_apple -.-> config_go
card_apple -.-> sys_config_dict
```
**图示来源**
- [config.go](file://api/card_info_apple/v1/config.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [card_apple.go](file://internal/consts/card_apple.go)
**本节来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
## 核心组件
Apple卡密配置管理的核心组件包括配置获取和设置两个主要端点`ConfigGetReq``ConfigSetReq`结构体定义了请求参数`ConfigGetRes`定义了响应数据结构这些组件通过`sys_config_dict`服务与底层数据存储进行交互实现了配置的读取和写入功能配置项涵盖了是否允许金额异议充值最小充值金额充值速率等关键业务参数
**本节来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [internal/service/sys_config_dict.go](file://internal/service/sys_config_dict.go)
## 架构概述
Apple卡密配置管理采用典型的分层架构从API接口层到控制器层再到服务层实现了关注点分离API接口层负责定义HTTP端点和数据传输对象DTO控制器层负责处理HTTP请求和响应服务层负责核心业务逻辑和数据持久化这种架构设计使得系统具有良好的可维护性和可扩展性
```mermaid
graph TD
Client[客户端] --> API[API接口层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Database[(数据库)]
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style Database fill:#999,stroke:#333
```
**图示来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [internal/service/sys_config_dict.go](file://internal/service/sys_config_dict.go)
## 详细组件分析
### 配置获取与设置分析
Apple卡密配置管理提供了两个核心API端点获取配置和设置配置获取配置端点使用GET方法URL模式为`/cardInfo/AppleCard/config/get`返回当前的配置状态设置配置端点使用POST方法URL模式为`/cardInfo/AppleCard/config/set`接收新的配置参数并进行更新
#### 配置数据结构
```mermaid
classDiagram
class ConfigGetRes {
+bool isAllowDifferentAmount
+bool isAllowDifferentSucceedCallback
+bool isAllowDifferentFailCallback
+int64 redeemCardMinAmount
+bool isAllowCompensatedCallback
+int redeemCardRate
}
class ConfigSetReq {
+bool isAllowDifferentAmount
+bool isAllowDifferentSucceedCallback
+bool isAllowDifferentFailCallback
+int64 redeemCardMinAmount
+bool isAllowCompensatedCallback
+int redeemCardRate
}
ConfigGetRes <|-- ConfigSetReq : "继承"
```
**图示来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
#### 配置操作流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
Client->>API : GET /cardInfo/AppleCard/config/get
API->>Controller : 调用ConfigGet方法
Controller->>Service : 调用Get配置方法
Service-->>Controller : 返回配置数据
Controller-->>API : 返回配置数据
API-->>Client : 返回JSON响应
Client->>API : POST /cardInfo/AppleCard/config/set
API->>Controller : 调用ConfigSet方法
Controller->>Service : 调用Set配置方法
Service-->>Controller : 返回操作结果
Controller-->>API : 返回操作结果
API-->>Client : 返回JSON响应
```
**图示来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
**本节来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
- [internal/service/sys_config_dict.go](file://internal/service/sys_config_dict.go)
### 概念概述
Apple卡密配置管理是整个卡密系统的核心功能之一它允许管理员动态调整系统的行为和策略通过这个管理接口可以控制是否允许金额异议充值设置最小充值金额调整充值速率等关键参数这些配置直接影响到系统的安全性和用户体验因此需要谨慎设置和管理
## 依赖分析
Apple卡密配置管理功能依赖于多个核心组件`sys_config_dict`服务是配置数据的持久化层提供了配置的读写接口`card_apple`常量文件定义了与Apple卡密相关的常量和枚举值如最小充值金额最大充值金额等这些依赖关系确保了配置管理功能的完整性和一致性
```mermaid
graph TD
ConfigAPI[配置API] --> SysConfigDict[sys_config_dict服务]
ConfigAPI --> CardApple[card_apple常量]
SysConfigDict --> Database[(数据库)]
CardApple -.-> ConfigAPI
```
**图示来源**
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [card_apple.go](file://internal/consts/card_apple.go)
**本节来源**
- [internal/service/sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [internal/consts/card_apple.go](file://internal/consts/card_apple.go)
## 性能考虑
在设计Apple卡密配置管理API时需要考虑性能和可扩展性由于配置数据通常不会频繁变更可以考虑在客户端或中间层进行缓存以减少对后端服务的请求压力同时配置更新操作应该具有原子性确保在并发环境下数据的一致性对于大规模部署可以考虑使用分布式配置中心来管理配置提高系统的可用性和响应速度
## 故障排查指南
在使用Apple卡密配置管理API时可能会遇到各种问题常见的问题包括配置更新不生效获取配置返回错误等对于配置更新不生效的问题首先检查请求参数是否正确然后确认服务层是否成功写入数据库对于获取配置返回错误的问题检查网络连接和API端点是否正确此外还应该查看系统日志寻找可能的错误信息
**本节来源**
- [internal/controller/card_info_apple/card_info_apple_v1_config_get.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_get.go)
- [internal/controller/card_info_apple/card_info_apple_v1_config_set.go](file://internal/controller/card_info_apple/card_info_apple_v1_config_set.go)
## 结论
Apple卡密配置管理API为系统管理员提供了灵活的配置管理能力通过标准化的RESTful接口实现了配置的读取和写入该功能的设计遵循了分层架构原则具有良好的可维护性和可扩展性通过合理设置各项配置参数可以有效控制系统的安全性和性能满足不同业务场景的需求未来可以考虑增加配置版本管理和审计日志功能进一步提升系统的可管理性和安全性
## 附录
### 配置参数说明表
| 参数名称 | 类型 | 描述 | 有效值范围 |
| --- | --- | --- | --- |
| isAllowDifferentAmount | bool | 是否允许金额异议充值 | true/false |
| isAllowDifferentSucceedCallback | bool | 是否允许金额异议回调(充值成功) | true/false |
| isAllowDifferentFailCallback | bool | 是否允许金额异议回调(充值失败) | true/false |
| redeemCardMinAmount | int64 | 充值卡最小充值金额 | 50 |
| isAllowCompensatedCallback | bool | 是否允许补卡自动回调 | true/false |
| redeemCardRate | int | 充值卡充值速率 | 0 |
**本节来源**
- [api/card_info_apple/v1/config.go](file://api/card_info_apple/v1/config.go)
- [internal/consts/card_apple.go](file://internal/consts/card_apple.go)

View File

@@ -0,0 +1,312 @@
# Ctrip卡密管理API
<cite>
**本文档引用的文件**
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [config.go](file://api/card_info_c_trip/v1/config.go)
- [order.go](file://api/card_info_c_trip/v1/order.go)
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go)
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go)
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [sys_auth.go](file://internal/service/sys_auth.go)
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了Ctrip卡密管理API涵盖账户管理订单处理等核心接口文档详细说明了账户创建充值配置订单提交等端点的HTTP方法URL模式请求/响应模式和认证机制提供了实际使用示例包括Ctrip账户Cookie管理充值订单提交订单历史查询等场景解释了Ctrip卡密特有的兑换配置机制和回调处理提供了错误处理策略和安全考虑文档还包含客户端实现指南和性能优化建议特别关注Ctrip平台的API调用频率限制和数据加密要求
## 项目结构
Ctrip卡密管理API的项目结构遵循模块化设计原则将不同功能分离到独立的目录中核心API接口位于`api/card_info_c_trip/v1`目录下控制器实现位于`internal/controller/card_info_c_trip`目录中数据模型定义在`internal/model/entity`目录服务接口在`internal/service`目录中声明
```mermaid
graph TD
subgraph "API接口层"
A[account.go]
B[config.go]
C[order.go]
end
subgraph "控制器层"
D[card_info_c_trip_v1_account_create.go]
E[card_info_c_trip_v1_submit.go]
F[card_info_c_trip_v1_order_callback.go]
G[card_info_c_trip_v1_redeem_config_get.go]
H[card_info_c_trip_v1_account_cookie_check.go]
end
subgraph "服务层"
I[card_redeem_order.go]
J[sys_config_dict.go]
K[sys_auth.go]
end
subgraph "模型层"
L[v_1_card_redeem_account_info.go]
M[v_1_card_redeem_order_info.go]
end
A --> D
B --> G
C --> E
C --> F
D --> I
E --> I
F --> I
G --> J
H --> K
L --> D
M --> E
M --> F
```
**图示来源**
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [config.go](file://api/card_info_c_trip/v1/config.go)
- [order.go](file://api/card_info_c_trip/v1/order.go)
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go)
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go)
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [sys_auth.go](file://internal/service/sys_auth.go)
**本节来源**
- [api/card_info_c_trip](file://api/card_info_c_trip)
- [internal/controller/card_info_c_trip](file://internal/controller/card_info_c_trip)
## 核心组件
Ctrip卡密管理API的核心组件包括账户管理配置管理订单处理三大模块账户管理模块负责Ctrip账户的创建更新删除和状态管理配置管理模块处理Ctrip卡密的兑换配置包括金额异议设置最小充值金额等订单处理模块负责充值订单的提交查询和回调处理
**本节来源**
- [account.go](file://api/card_info_c_trip/v1/account.go#L1-L149)
- [config.go](file://api/card_info_c_trip/v1/config.go#L1-L29)
- [order.go](file://api/card_info_c_trip/v1/order.go#L1-L56)
## 架构概述
Ctrip卡密管理API采用分层架构设计包含API接口层控制器层服务层和数据模型层API接口层定义了HTTP端点和请求/响应结构控制器层处理具体的业务逻辑调用服务层接口服务层封装了核心业务逻辑提供可重用的服务接口数据模型层定义了数据库表结构和实体关系
```mermaid
graph TB
subgraph "客户端"
Client[客户端应用]
end
subgraph "API网关"
API[API接口]
end
subgraph "业务逻辑层"
Controller[控制器]
Service[服务]
end
subgraph "数据访问层"
DAO[数据访问对象]
DB[(数据库)]
end
Client --> API
API --> Controller
Controller --> Service
Service --> DAO
DAO --> DB
```
**图示来源**
- [card_info_c_trip.go](file://internal/controller/card_info_c_trip/card_info_c_trip.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
## 详细组件分析
### 账户管理分析
Ctrip账户管理功能提供了完整的账户生命周期管理包括创建更新删除状态管理和Cookie验证
#### 账户创建流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant ClientInt as "第三方客户端"
Client->>Controller : POST /cardInfo/cTrip/account/create
Controller->>Service : 验证用户登录状态
Service-->>Controller : 返回用户信息
Controller->>ClientInt : 获取Ctrip客户端实例
ClientInt-->>Controller : 返回客户端
Controller->>ClientInt : 查询用户信息(Cookie)
ClientInt-->>Controller : 返回用户信息
Controller->>Service : 检查账户是否已存在
Service-->>Controller : 返回存在状态
Controller->>ClientInt : 查询账户余额
ClientInt-->>Controller : 返回余额信息
Controller->>Service : 添加新账户
Service-->>Controller : 返回结果
Controller-->>Client : 返回响应
```
**图示来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go#L22-L65)
- [account.go](file://api/card_info_c_trip/v1/account.go#L45-L60)
**本节来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go#L1-L66)
- [account.go](file://api/card_info_c_trip/v1/account.go#L1-L149)
### 订单处理分析
Ctrip订单处理模块负责充值订单的提交状态管理和回调处理
#### 订单提交流程
```mermaid
flowchart TD
Start([接收订单请求]) --> ValidateInput["验证输入参数"]
ValidateInput --> InputValid{"参数有效?"}
InputValid --> |否| ReturnError["返回错误响应"]
InputValid --> |是| LogRequest["记录请求日志"]
LogRequest --> AddOrder["添加订单到数据库"]
AddOrder --> TriggerProcess["触发订单处理"]
TriggerProcess --> End([返回响应])
ReturnError --> End
```
**图示来源**
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go#L14-L30)
- [order.go](file://api/card_info_c_trip/v1/order.go#L10-L25)
**本节来源**
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go#L1-L31)
- [order.go](file://api/card_info_c_trip/v1/order.go#L1-L56)
### 配置管理分析
Ctrip兑换配置管理提供了灵活的配置选项允许管理员调整系统行为
#### 配置获取流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "配置服务"
Client->>Controller : GET /cardInfo/cTrip/config/get
Controller->>Service : 获取金额异议设置
Service-->>Controller : 返回设置
Controller->>Service : 获取最小充值金额
Service-->>Controller : 返回金额
Controller->>Service : 获取成功回调设置
Service-->>Controller : 返回设置
Controller->>Service : 获取失败回调设置
Service-->>Controller : 返回设置
Controller->>Service : 获取补卡回调设置
Service-->>Controller : 返回设置
Controller->>Service : 获取充值速率
Service-->>Controller : 返回速率
Controller-->>Client : 返回完整配置
```
**图示来源**
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go#L10-L24)
- [config.go](file://api/card_info_c_trip/v1/config.go#L10-L20)
**本节来源**
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go#L1-L25)
- [config.go](file://api/card_info_c_trip/v1/config.go#L1-L29)
### Cookie验证分析
Ctrip账户Cookie验证功能确保账户的有效性和可用性
#### Cookie验证流程
```mermaid
flowchart TD
Start([开始验证]) --> CheckAuth["验证用户权限"]
CheckAuth --> AuthValid{"权限有效?"}
AuthValid --> |否| ReturnAuthError["返回权限错误"]
AuthValid --> |是| CheckRateLimit["检查速率限制"]
CheckRateLimit --> RateValid{"未超限?"}
RateValid --> |否| ReturnRateError["返回频率错误"]
RateValid --> |是| GetClient["获取Ctrip客户端"]
GetClient --> QueryUserInfo["查询用户信息"]
QueryUserInfo --> UserInfoValid{"信息有效?"}
UserInfoValid --> |否| ReturnInvalid["返回无效"]
UserInfoValid --> |是| QueryBalance["查询账户余额"]
QueryBalance --> BalanceValid{"余额有效?"}
BalanceValid --> |否| ReturnBalanceError["返回余额错误"]
BalanceValid --> |是| CheckExist["检查账户是否存在"]
CheckExist --> SetExistFlag["设置存在标志"]
SetExistFlag --> ReturnSuccess["返回成功结果"]
ReturnAuthError --> End([结束])
ReturnRateError --> End
ReturnInvalid --> End
ReturnBalanceError --> End
ReturnSuccess --> End
```
**图示来源**
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go#L21-L71)
- [account.go](file://api/card_info_c_trip/v1/account.go#L62-L80)
**本节来源**
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go#L1-L72)
- [account.go](file://api/card_info_c_trip/v1/account.go#L1-L149)
## 依赖分析
Ctrip卡密管理API依赖多个内部服务和外部组件形成了复杂的依赖关系网络
```mermaid
graph TD
AccountAPI[账户API] --> AccountController[账户控制器]
ConfigAPI[配置API] --> ConfigController[配置控制器]
OrderAPI[订单API] --> OrderController[订单控制器]
AccountController --> SysAuth[认证服务]
AccountController --> CardRedeemOrder[订单服务]
AccountController --> RedeemClient[Ctrip客户端]
ConfigController --> SysConfigDict[配置字典服务]
OrderController --> SysAuth
OrderController --> CardRedeemOrder
CardRedeemOrder --> Database[(数据库)]
SysConfigDict --> Database
SysAuth --> Database
RedeemClient --> CtripAPI[Ctrip外部API]
```
**图示来源**
- [sys_auth.go](file://internal/service/sys_auth.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
**本节来源**
- [sys_auth.go](file://internal/service/sys_auth.go#L1-L39)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go#L1-L79)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go#L1-L81)
## 性能考虑
Ctrip卡密管理API在设计时考虑了多种性能优化策略系统实现了接口速率限制防止恶意用户频繁调用接口通过缓存机制减少对第三方API的调用频率提高响应速度异步处理订单提交避免阻塞主线程数据库查询优化使用索引提高查询效率批量操作支持减少网络往返次数
## 故障排除指南
### 常见错误及解决方案
- **权限不足错误**: 确保用户已登录且具有相应权限
- **Cookie失效错误**: 检查提供的Cookie是否有效重新获取最新Cookie
- **操作过于频繁错误**: 遵守API调用频率限制等待一段时间后重试
- **订单已回调错误**: 不要重复调用回调接口每个订单只能回调一次
- **金额异议不回调错误**: 检查订单状态金额异议订单不允许回调
**本节来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go#L22-L65)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go#L14-L30)
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go#L16-L53)
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go#L21-L71)
## 结论
Ctrip卡密管理API提供了一套完整的解决方案用于管理Ctrip账户和处理充值订单系统设计合理分层清晰易于维护和扩展通过详细的文档和示例开发者可以快速理解和使用API建议在实际使用中注意API调用频率限制合理使用缓存机制确保系统的稳定性和性能

View File

@@ -0,0 +1,240 @@
# 京东卡密数据汇总
<cite>
**本文档引用文件**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
- [cache.go](file://utility/cache/cache.go)
- [consts.go](file://utility/cache/consts.go)
- [card_info_jd.go](file://api/card_info_jd/v1/order_summary.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了京东卡密数据汇总API的设计与实现涵盖订单汇总账户统计交易分析等接口的HTTP方法URL模式请求/响应模式和认证机制重点描述了数据汇总的计算逻辑时间范围选择和数据精度控制并提供实际使用示例如日/月交易量统计账户余额汇总充值成功率分析等场景同时解释了数据缓存策略查询性能优化和大数据量处理机制确保在高并发查询场景下的响应时间优化
## 项目结构
本项目采用分层架构设计主要分为API层控制器层服务层逻辑层和数据访问层京东卡密相关功能集中在`api/card_info_jd``internal/controller/card_info_jd`目录下订单汇总功能则分布在`api/order``internal/controller/order`目录中缓存机制由`utility/cache`模块统一管理数据库操作通过`internal/dao`实现
```mermaid
graph TB
subgraph "API层"
A[card_info_jd/v1/order_summary.go]
B[order/v1/order_summary.go]
end
subgraph "控制器层"
C[card_info_jd_v1_order_summary_list.go]
D[order_v1_order_summary_get_list.go]
end
subgraph "服务层"
E[merchant_order.go]
end
subgraph "逻辑层"
F[order-summary.go]
end
subgraph "数据访问层"
G[dao/V1OrderInfo.go]
end
subgraph "缓存层"
H[cache.go]
end
A --> C
B --> D
C --> E
D --> E
E --> F
F --> G
F --> H
```
**Diagram sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
## 核心组件
京东卡密数据汇总的核心组件包括订单汇总接口数据计算逻辑和服务注册机制订单汇总接口提供HTTP端点用于获取统计信息数据计算逻辑负责从数据库中提取并聚合数据服务注册机制确保订单汇总服务的正确初始化和调用
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
- [merchant_order.go](file://internal/service/merchant_order.go)
## 架构概述
系统采用典型的分层架构从前端API到后端数据存储形成清晰的数据流用户请求首先到达API层经过控制器层处理后调用服务层提供的接口服务层协调逻辑层完成具体的业务处理包括数据查询聚合计算等逻辑层通过DAO层与数据库交互并利用缓存层提高查询性能
```mermaid
graph LR
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> Logic[逻辑层]
Logic --> Cache[缓存]
Logic --> Database[数据库]
Cache --> Logic
Database --> Logic
```
**Diagram sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
## 详细组件分析
### 订单汇总接口分析
#### 接口定义
```mermaid
classDiagram
class OrderSummaryListReq {
+string RoadUid
+CommonPageReq
}
class OrderSummaryListRes {
+CommonPageRes[OrderSummaryRecord]
}
class OrderSummaryRecord {
+string MerchantUid
+string MerchantName
+int64 SucceedCount
+float64 SucceedShowAmount
+float64 SucceedFactAmount
+int64 TotalCount
+float64 TotalShowAmount
+float64 TotalFactAmount
+float64 Rate
+string Date
+int64 FailedCount
+int64 WaitedCount
}
OrderSummaryListRes --> OrderSummaryRecord : "包含"
```
**Diagram sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
#### 请求处理流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "逻辑层"
participant Database as "数据库"
participant Cache as "缓存"
Client->>API : GET /cardInfo/JDCard/order/summary
API->>Controller : 转发请求
Controller->>Service : 调用OrderSummary()
Service->>Logic : 获取汇总数据
Logic->>Cache : 检查缓存
alt 缓存命中
Cache-->>Logic : 返回缓存数据
else 缓存未命中
Logic->>Database : 查询数据库
Database-->>Logic : 返回原始数据
Logic->>Logic : 聚合计算
Logic->>Cache : 存储计算结果
end
Logic-->>Service : 返回汇总结果
Service-->>Controller : 返回结果
Controller-->>API : 返回响应
API-->>Client : 返回JSON数据
```
**Diagram sources**
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
#### 数据计算逻辑
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> CheckCache["检查缓存是否存在"]
CheckCache --> CacheHit{"缓存命中?"}
CacheHit --> |是| ReturnCache["返回缓存数据"]
CacheHit --> |否| QueryDB["查询数据库"]
QueryDB --> ProcessData["处理原始数据"]
ProcessData --> Aggregate["执行聚合计算"]
Aggregate --> FormatResult["格式化结果"]
FormatResult --> UpdateCache["更新缓存"]
UpdateCache --> ReturnResult["返回结果"]
ReturnCache --> End([结束])
ReturnResult --> End
```
**Diagram sources**
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
## 依赖分析
系统各组件之间存在明确的依赖关系形成了稳定的服务调用链API层依赖控制器层控制器层依赖服务层服务层依赖逻辑层逻辑层依赖数据访问层和缓存层
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[逻辑层]
D --> E[DAO层]
D --> F[缓存层]
E --> G[数据库]
F --> G[数据库]
```
**Diagram sources**
- [merchant_order.go](file://internal/service/merchant_order.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
**Section sources**
- [merchant_order.go](file://internal/service/merchant_order.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
## 性能考虑
为确保系统在高并发场景下的性能表现采用了多项优化措施首先通过Redis缓存频繁访问的数据减少数据库压力其次使用分页查询避免一次性加载大量数据最后对关键路径进行性能监控及时发现和解决瓶颈问题
**Section sources**
- [cache.go](file://utility/cache/cache.go)
- [consts.go](file://utility/cache/consts.go)
## 故障排除指南
当遇到数据汇总接口响应缓慢或返回错误时可按照以下步骤进行排查
1. 检查缓存服务是否正常运行
2. 验证数据库连接是否稳定
3. 查看日志中是否有SQL执行超时记录
4. 确认请求参数是否符合规范
5. 检查是否有大量并发请求导致资源竞争
**Section sources**
- [cache.go](file://utility/cache/cache.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
## 结论
京东卡密数据汇总API通过分层架构设计和缓存优化策略实现了高效的数据统计功能系统能够支持日/月交易量统计账户余额汇总充值成功率分析等多种业务场景满足高并发查询的需求未来可通过引入更精细的缓存策略和数据库索引优化进一步提升性能

View File

@@ -0,0 +1,312 @@
# 京东卡密管理API
<cite>
**本文档引用文件**
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [account.go](file://api/card_info_jd/v1/account.go)
- [order.go](file://api/card_info_jd/v1/order.go)
- [config.go](file://api/card_info_jd/v1/config.go)
- [card_info_jd_v1_jd_account_cookie_batch_add.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_batch_add.go)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_jd.go](file://internal/consts/card_jd.go)
- [utility/redeem/jd.go](file://utility/integration/redeem/jd/jd.go)
- [utility/restriction/jd.go](file://utility/integration/restriction/jd.go)
- [middleware/auth.go](file://internal/middleware/auth.go)
- [model/card_redeem_cookie.go](file://internal/model/card_redeem_cookie.go)
- [dao/v_1_card_redeem_cookie_info.go](file://internal/dao/v_1_card_redeem_cookie_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了京东卡密管理API的设计与实现涵盖账户管理充值处理订单回调等关键接口系统支持京东平台的卡密兑换与账户管理具备完整的Cookie验证机制风控策略和反爬虫应对方案文档重点说明了账户创建批量Cookie导入充值订单提交状态同步等核心功能的实现方式并提供客户端集成指南和性能优化建议
## 项目结构
京东卡密管理模块主要位于`api/card_info_jd``internal/controller/card_info_jd`目录下采用分层架构设计包含API接口层控制器层服务层和数据访问层系统通过`v1`版本化接口提供RESTful服务支持账户管理订单处理和配置操作
```mermaid
graph TB
subgraph "API接口层"
A[account.go]
B[order.go]
C[config.go]
end
subgraph "控制器层"
D[card_info_jd_v1_jd_account_*]
E[card_info_jd_v1_submit.go]
F[card_info_jd_v1_order_callback.go]
end
subgraph "服务层"
G[service/card_redeem_cookie.go]
H[logic/card_redeem_cookie.go]
end
subgraph "数据层"
I[dao/v_1_card_redeem_cookie_info.go]
J[model/card_redeem_cookie.go]
end
A --> D
B --> E
B --> F
D --> G
E --> G
F --> G
G --> H
H --> I
I --> J
```
**图示来源**
- [account.go](file://api/card_info_jd/v1/account.go)
- [order.go](file://api/card_info_jd/v1/order.go)
- [config.go](file://api/card_info_jd/v1/config.go)
- [card_info_jd_v1_jd_account_cookie_batch_add.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_batch_add.go)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
**本节来源**
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [api/card_info_jd/v1](file://api/card_info_jd/v1)
## 核心组件
京东卡密管理系统包含三大核心功能模块账户管理充值处理和订单回调账户管理模块负责京东账户Cookie的批量导入状态检测和有效性验证充值处理模块实现卡密提交订单创建和状态跟踪订单回调模块提供外部系统状态同步接口系统通过`card_redeem_jd`模块实现与京东平台的直接交互包含专门的风控规避机制和请求频率控制
**本节来源**
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_jd.go](file://internal/consts/card_jd.go)
## 架构概览
系统采用典型的分层架构前端通过HTTP API与后端交互后端各层职责分明API层定义接口规范控制器层处理业务逻辑服务层封装核心功能数据访问层负责持久化操作整个流程通过中间件进行认证和错误处理确保系统安全性和稳定性
```mermaid
graph LR
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(数据库)]
subgraph "安全层"
Auth[认证中间件]
Limit[限流组件]
end
Controller --> Auth
Controller --> Limit
subgraph "外部集成"
JD[京东平台]
Restriction[风控系统]
end
Service --> JD
Service --> Restriction
```
**图示来源**
- [middleware/auth.go](file://internal/middleware/auth.go)
- [utility/limiter/rate.go](file://utility/limiter/rate.go)
- [utility/integration/redeem/jd/jd.go](file://utility/integration/redeem/jd/jd.go)
- [utility/integration/restriction/jd.go](file://utility/integration/restriction/jd.go)
## 详细组件分析
### 账户管理分析
账户管理模块提供完整的京东账户生命周期管理功能包括创建更新删除和状态刷新系统支持通过批量文件导入Cookie自动进行有效性验证和分类存储
#### 账户管理类图
```mermaid
classDiagram
class JDAccountController {
+createAccount(req) Response
+updateAccount(id, req) Response
+deleteAccount(id) Response
+refreshStatus(id) Response
+batchAddCookie(file) Response
+batchCheckCookie() Response
}
class JDAccountService {
-cookieValidator : CookieValidator
-accountRepository : AccountRepository
+addAccount(account) error
+updateAccount(id, account) error
+removeAccount(id) error
+validateCookie(cookie) ValidationResult
+syncAccountStatus(id) StatusResult
}
class CookieValidator {
+validateFormat(cookie) bool
+testConnectivity(cookie) bool
+checkRestriction(cookie) RestrictionResult
-simulateLogin(cookie) LoginResult
}
class AccountRepository {
+save(account) error
+findById(id) Account
+findAll() []Account
+updateStatus(id, status) error
}
class Account {
+string accountId
+string cookie
+string nickname
+float balance
+string status
+datetime createdAt
+datetime updatedAt
+getStatus() string
+getBalance() float
}
JDAccountController --> JDAccountService : "调用"
JDAccountService --> CookieValidator : "使用"
JDAccountService --> AccountRepository : "依赖"
JDAccountService --> Account : "操作"
```
**图示来源**
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_info_jd_v1_jd_account_update.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_update.go)
- [card_info_jd_v1_jd_account_delete.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_delete.go)
- [card_info_jd_v1_jd_account_refresh_status.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_refresh_status.go)
- [model/card_redeem_cookie.go](file://internal/model/card_redeem_cookie.go)
**本节来源**
- [account.go](file://api/card_info_jd/v1/account.go)
- [internal/controller/card_info_jd/card_info_jd_v1_jd_account_*.go](file://internal/controller/card_info_jd/)
### 充值处理分析
充值处理模块负责卡密兑换的核心业务流程从订单提交到结果回调的完整生命周期管理系统实现智能路由选择失败重试机制和状态同步功能
#### 充值处理序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API网关"
participant Controller as "充值控制器"
participant Service as "充值服务"
participant JD as "京东平台"
participant DB as "数据库"
Client->>API : POST /api/jd/submit
API->>Controller : 转发请求
Controller->>Service : submitOrder(order)
Service->>Service : validateOrder(order)
Service->>Service : selectRoad(order)
Service->>JD : redeemCard(cookie, cardNo)
alt 兑换成功
JD-->>Service : 返回成功结果
Service->>DB : 更新订单状态
Service-->>Controller : 返回成功响应
Controller-->>API : 返回结果
API-->>Client : {status : "success", orderId}
else 兑换失败
JD-->>Service : 返回错误信息
Service->>Service : scheduleRetry(order)
Service-->>Controller : 返回失败响应
Controller-->>API : 返回结果
API-->>Client : {status : "failed", orderId, retryAfter}
end
Note over Client,DB : 订单状态最终一致性保障
```
**图示来源**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [utility/integration/redeem/jd/jd.go](file://utility/integration/redeem/jd/jd.go)
- [internal/model/card_redeem_cookie_order_jd.go](file://internal/model/card_redeem_cookie_order_jd.go)
**本节来源**
- [order.go](file://api/card_info_jd/v1/order.go)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
### 订单回调分析
订单回调模块提供标准化接口用于接收外部系统如京东平台的订单状态更新通知实现双向状态同步
#### 订单回调流程图
```mermaid
flowchart TD
Start([收到回调请求]) --> Validate["验证请求签名"]
Validate --> SignatureValid{"签名有效?"}
SignatureValid --> |否| ReturnError["返回401错误"]
SignatureValid --> |是| Parse["解析回调数据"]
Parse --> Extract["提取订单信息"]
Extract --> FindOrder["查询本地订单"]
FindOrder --> OrderExists{"订单存在?"}
OrderExists --> |否| CreateOrder["创建新订单"]
OrderExists --> |是| UpdateStatus["更新订单状态"]
UpdateStatus --> CheckChange["状态有变化?"]
CheckChange --> |是| Notify["触发通知机制"]
CheckChange --> |否| SkipNotify["跳过通知"]
Notify --> Log["记录操作日志"]
SkipNotify --> Log
Log --> ReturnSuccess["返回200成功"]
ReturnError --> End([响应完成])
ReturnSuccess --> End
```
**图示来源**
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [utility/verify/utils.go](file://utility/verify/utils.go)
- [internal/dao/v_1_card_redeem_cookie_order_jd.go](file://internal/dao/v_1_card_redeem_cookie_order_jd.go)
**本节来源**
- [order.go](file://api/card_info_jd/v1/order.go)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
## 依赖分析
系统依赖多个内部和外部组件形成复杂的依赖网络核心依赖包括认证中间件限流组件京东平台集成和数据库持久化层
```mermaid
graph TD
A[京东卡密API] --> B[认证中间件]
A --> C[限流组件]
A --> D[京东平台集成]
A --> E[数据库访问]
A --> F[风控系统]
B --> G[用户令牌系统]
C --> H[Redis限流]
D --> I[HTTP客户端]
D --> J[Cookie管理]
E --> K[ORM框架]
F --> L[IP限制检查]
F --> M[请求频率监控]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#bbf,stroke:#333
style D fill:#bbf,stroke:#333
style E fill:#bbf,stroke:#333
style F fill:#bbf,stroke:#333
```
**图示来源**
- [middleware/auth.go](file://internal/middleware/auth.go)
- [utility/limiter/redis.go](file://utility/limiter/redis.go)
- [utility/integration/redeem/jd/jd.go](file://utility/integration/redeem/jd/jd.go)
- [internal/dao/internal/v_1_card_redeem_cookie_info.go](file://internal/dao/internal/v_1_card_redeem_cookie_info.go)
- [utility/integration/restriction/jd.go](file://utility/integration/restriction/jd.go)
**本节来源**
- [go.mod](file://go.mod)
- [internal/middleware](file://internal/middleware)
- [utility/integration](file://utility/integration)
## 性能考虑
系统在设计时充分考虑了京东平台的反爬虫机制和请求频率限制通过分布式限流智能重试请求合并等策略确保在高并发场景下的稳定性和效率建议客户端实现指数退避重试机制避免因频繁请求导致IP被封禁系统内部采用连接池和缓存机制减少数据库访问压力提高响应速度
## 故障排除指南
常见问题包括Cookie失效订单状态不同步请求被限流等对于Cookie失效问题应检查京东账户登录状态和安全验证对于状态不同步可手动触发状态刷新或检查回调配置对于限流问题应降低请求频率或联系管理员调整配额系统提供详细的日志记录和监控指标便于问题定位和分析
**本节来源**
- [internal/errHandler/handler.go](file://internal/errHandler/handler.go)
- [utility/monitor/monitor.go](file://utility/monitor/monitor.go)
- [internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_check.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_check.go)
## 结论
京东卡密管理API提供了一套完整的解决方案涵盖账户管理充值处理和状态同步等核心功能系统设计充分考虑了京东平台的特殊要求和限制通过合理的架构设计和优化策略确保了系统的稳定性安全性和可扩展性建议用户遵循最佳实践合理使用API避免触发平台的反爬虫机制

View File

@@ -0,0 +1,244 @@
# 京东卡密订单处理
<cite>
**本文档引用文件**
- [order.go](file://api/card_info_jd/v1/order.go)
- [account.go](file://api/card_info_jd/v1/account.go)
- [config.go](file://api/card_info_jd/v1/config.go)
- [order_summary.go](file://api/card_info_jd/v1/order_summary.go)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [v_1_card_redeem_order_info.go](file://internal/dao/v_1_card_redeem_order_info.go)
- [v_1_card_redeem_account_info.go](file://internal/dao/v_1_card_redeem_account_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了京东卡密订单处理API的设计与实现涵盖订单提交状态回调历史查询等核心功能重点描述了订单创建支付处理状态同步等流程并提供客户端实现指南错误处理策略和性能优化建议特别关注订单状态一致性保障机制
## 项目结构
京东卡密订单处理系统采用模块化设计主要分为API接口层控制器层服务层和数据访问层系统通过清晰的分层架构实现了高内聚低耦合的设计原则
```mermaid
graph TB
subgraph "API层"
OrderAPI["/cardInfo/JDCard/order/submit"]
AccountAPI["/cardInfo/JDCard/account/*"]
ConfigAPI["/cardInfo/JDCard/config/*"]
end
subgraph "控制器层"
OrderController["card_info_jd_v1_submit.go"]
CallbackController["card_info_jd_v1_order_callback.go"]
end
subgraph "服务层"
OrderService["CardRedeemOrder服务"]
AuthService["SysAuth服务"]
end
subgraph "数据层"
OrderDAO["v_1_card_redeem_order_info.go"]
AccountDAO["v_1_card_redeem_account_info.go"]
end
OrderAPI --> OrderController
AccountAPI --> OrderController
ConfigAPI --> OrderController
OrderController --> OrderService
OrderController --> AuthService
OrderService --> OrderDAO
OrderService --> AccountDAO
```
**Diagram sources**
- [order.go](file://api/card_info_jd/v1/order.go#L1-L56)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L30)
**Section sources**
- [order.go](file://api/card_info_jd/v1/order.go#L1-L56)
- [account.go](file://api/card_info_jd/v1/account.go#L1-L145)
## 核心组件
京东卡密订单处理系统的核心组件包括订单提交状态回调账户管理和配置管理四大模块订单提交模块负责接收商户充值请求并创建订单状态回调模块实现订单状态通知功能账户管理模块维护京东账户信息配置管理模块提供系统参数设置
**Section sources**
- [order.go](file://api/card_info_jd/v1/order.go#L1-L56)
- [config.go](file://api/card_info_jd/v1/config.go#L1-L33)
## 架构概述
系统采用典型的分层架构设计从前端API到后端数据存储形成完整的处理链条各层之间通过明确定义的接口进行通信确保系统的可维护性和可扩展性
```mermaid
graph TD
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(数据库)]
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style DAO fill:#69f,stroke:#333
style DB fill:#9f9,stroke:#333
```
**Diagram sources**
- [order.go](file://api/card_info_jd/v1/order.go#L1-L56)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L30)
## 详细组件分析
### 订单提交分析
订单提交功能是系统的核心业务流程负责接收商户的充值请求并创建相应的订单记录
#### 订单提交请求模型
```mermaid
classDiagram
class SubmitReq {
+string CardNo
+string GiftCardPwd
+string NotifyUrl
+float64 Amount
+string MerchantId
+string Attach
+g.Meta path : "/cardInfo/JDCard/order/submit" tags : "京东充值卡订单" method : "post" summary : "充值"
}
SubmitReq : +CardNo : 卡号
SubmitReq : +GiftCardPwd : 礼品卡密码
SubmitReq : +NotifyUrl : 回调地址
SubmitReq : +Amount : 充值金额
SubmitReq : +MerchantId : 商户ID
SubmitReq : +Attach : 附加信息
```
**Diagram sources**
- [order.go](file://api/card_info_jd/v1/order.go#L10-L20)
#### 订单提交处理流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "订单服务"
participant DAO as "数据访问层"
Client->>API : POST /cardInfo/JDCard/order/submit
API->>Controller : 转发请求
Controller->>Service : 调用AddOne方法
Service->>DAO : 创建订单记录
DAO-->>Service : 返回订单信息
Service->>Service : 触发验证和消费
Service-->>Controller : 返回结果
Controller-->>Client : 返回响应
```
**Diagram sources**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L30)
### 订单回调分析
订单回调功能用于处理订单状态变更通知确保商户能够及时获取订单处理结果
#### 订单回调处理流程
```mermaid
flowchart TD
Start([开始]) --> AuthCheck["验证用户权限"]
AuthCheck --> OrderQuery["查询订单信息"]
OrderQuery --> StatusCheck["检查订单状态"]
StatusCheck --> |订单不存在| ReturnError["返回错误"]
StatusCheck --> |权限不足| ReturnError
StatusCheck --> |已回调| ReturnError
StatusCheck --> |未结束状态| ReturnError
StatusCheck --> |金额异议| ReturnError
StatusCheck --> |可回调| CallBack["执行回调"]
CallBack --> UpdateStatus["更新通知状态"]
UpdateStatus --> ReturnSuccess["返回成功"]
ReturnError --> End([结束])
ReturnSuccess --> End
```
**Diagram sources**
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go#L1-L54)
### 账户管理分析
账户管理模块负责京东账户的全生命周期管理包括创建查询更新和状态维护
```mermaid
classDiagram
class JDAccountListRecord {
+V1CardRedeemAccountInfo
+UploadUser
}
class UploadUser {
+string Id
+string Username
+string Nickname
}
class JDAccountRecord {
+string Cookie
+string Name
+int MaxAmountLimit
+int MaxCountLimit
+string Remark
+int Status
}
JDAccountListRecord --> UploadUser : "包含"
JDAccountListRecord --> JDAccountRecord : "继承"
```
**Diagram sources**
- [account.go](file://api/card_info_jd/v1/account.go#L50-L100)
## 依赖分析
系统各组件之间的依赖关系清晰明确遵循单向依赖原则避免循环依赖问题
```mermaid
graph LR
API --> Controller
Controller --> Service
Service --> DAO
Service --> Consts[consts常量]
Service --> ErrHandler[errHandler]
Controller --> Context[context]
style API fill:#f96,stroke:#333
style Controller fill:#69f,stroke:#333
style Service fill:#6f9,stroke:#333
style DAO fill:#9f9,stroke:#333
style Consts fill:#ff9,stroke:#333
style ErrHandler fill:#ff9,stroke:#333
style Context fill:#ff9,stroke:#333
```
**Diagram sources**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L30)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go#L1-L54)
**Section sources**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L30)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go#L1-L54)
## 性能考虑
系统在设计时充分考虑了性能因素通过异步处理批量操作和缓存机制来提升整体性能订单提交后立即触发验证和消费流程确保快速响应批量账户检查功能支持高效处理大量账户数据
## 故障排除指南
常见问题包括订单提交失败回调权限不足账户状态异常等建议检查请求参数完整性用户权限配置账户可用性等对于回调失败的情况需确认订单是否已处理完毕且未重复回调
**Section sources**
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go#L20-L40)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L15-L25)
## 结论
京东卡密订单处理系统提供了完整的订单生命周期管理功能通过清晰的API设计和稳健的错误处理机制确保了系统的可靠性和易用性系统架构合理组件职责明确为后续功能扩展奠定了良好基础

View File

@@ -0,0 +1,242 @@
# 京东卡密账户管理
<cite>
**本文档引用文件**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_info_jd_v1_jd_account_update.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_update.go)
- [card_info_jd_v1_jd_account_delete.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_delete.go)
- [card_info_jd_v1_jd_account_cookie_batch_add.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_batch_add.go)
- [card_info_jd_v1_jd_account_cookie_check.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_check.go)
- [card_info_original_jd_v1_original_jd_account_cookie_batch_add.go](file://internal/controller/card_info_original_jd/card_info_original_jd_v1_original_jd_account_cookie_batch_add.go)
- [card_redeem_jd_v1_account_add.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_add.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [originalJd/index.go](file://utility/integration/originalJd/index.go)
- [originalJd/model.go](file://utility/integration/originalJd/model.go)
- [card_redeem_account/schdule.go](file://internal/logic/card_redeem_account/schdule.go)
- [card_apple_account/status.go](file://internal/logic/card_apple_account/status.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了京东卡密账户管理API的设计与实现涵盖账户的创建更新删除和查询接口重点描述了批量添加京东账户Cookie的实现机制包括Cookie验证状态检测和刷新策略文档还提供了实际使用示例如批量导入账户账户状态监控和Cookie有效性验证等场景同时解释了账户与京东平台的交互机制包括登录状态管理反爬虫策略应对和请求频率控制并包含错误处理策略安全考虑和性能优化建议
## 项目结构
京东卡密账户管理功能主要分布在`api/card_redeem_jd``internal/controller/card_info_jd`目录下核心API定义在`api/card_redeem_jd/v1/account.go`控制器实现位于`internal/controller/card_info_jd/`目录下账户相关的业务逻辑由`internal/service/card_redeem_account.go``internal/service/card_redeem_cookie.go`提供服务接口京东平台交互通过`utility/integration/originalJd/`中的客户端实现
```mermaid
graph TB
subgraph "API层"
A[account.go]
end
subgraph "控制器层"
B[card_info_jd_v1_jd_account_create.go]
C[card_info_jd_v1_jd_account_update.go]
D[card_info_jd_v1_jd_account_delete.go]
E[card_info_jd_v1_jd_account_cookie_batch_add.go]
end
subgraph "服务层"
F[card_redeem_account.go]
G[card_redeem_cookie.go]
end
subgraph "集成层"
H[originalJd/index.go]
I[originalJd/model.go]
end
A --> B
B --> F
F --> H
H --> I
```
**Diagram sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [originalJd/index.go](file://utility/integration/originalJd/index.go)
**Section sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
## 核心组件
京东卡密账户管理的核心组件包括账户管理API批量Cookie处理状态验证机制和京东平台集成账户管理API提供标准的CRUD操作支持通过HTTP接口进行账户的创建更新删除和查询批量Cookie处理功能允许用户一次性导入多个京东账户的Cookie信息状态验证机制确保账户的可用性并定期刷新账户状态京东平台集成组件负责与京东API进行通信执行登录验证余额查询等操作
**Section sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 架构概述
系统采用分层架构设计从上到下分为API层控制器层服务层和集成层API层定义了所有对外暴露的HTTP接口使用GoFrame框架的元数据注解来配置路由方法和参数控制器层负责处理HTTP请求进行权限验证和参数校验然后调用相应的服务层方法服务层封装了业务逻辑提供统一的接口供控制器调用集成层包含与京东平台交互的具体实现通过HTTP客户端调用京东API
```mermaid
graph TD
Client[客户端] --> API[API层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Integration[集成层]
Integration --> JD[京东平台]
style Client fill:#f9f,stroke:#333
style JD fill:#bbf,stroke:#333
```
**Diagram sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [originalJd/index.go](file://utility/integration/originalJd/index.go)
## 详细组件分析
### 账户管理API分析
账户管理API提供了完整的CRUD操作接口使用RESTful风格设计所有接口都通过JWT进行认证确保只有授权用户才能访问接口设计遵循统一的响应格式包含状态码消息和数据体
#### 账户创建接口
```mermaid
classDiagram
class AccountAddReq {
+string name
+string cookie
+int status
+string notes
}
class AccountAddRes {
+string message
}
AccountAddReq --> AccountAddRes : "POST /cookieInfo/jd/account/add"
```
**Diagram sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
#### 账户操作序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API网关"
participant Controller as "控制器"
participant Service as "服务层"
participant Database as "数据库"
Client->>API : POST /cookieInfo/jd/account/add
API->>Controller : 转发请求
Controller->>Controller : 权限验证
Controller->>Service : 调用Add方法
Service->>Database : 插入账户记录
Database-->>Service : 返回结果
Service-->>Controller : 返回成功
Controller-->>API : 返回响应
API-->>Client : 200 OK
```
**Diagram sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
**Section sources**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
### 批量Cookie处理分析
批量Cookie处理功能允许用户一次性导入多个京东账户的Cookie信息系统会对每个Cookie进行验证查询用户信息和余额并将有效账户保存到数据库中
#### 批量添加流程图
```mermaid
flowchart TD
Start([开始]) --> ValidateAuth["验证用户权限"]
ValidateAuth --> LoopStart{遍历Cookie列表}
LoopStart --> TrimCookie["清理Cookie空白字符"]
TrimCookie --> GetClient["获取京东客户端"]
GetClient --> QueryUserInfo["查询用户信息"]
QueryUserInfo --> CheckUserValid{"用户信息有效?"}
CheckUserValid --> |否| NextCookie
CheckUserValid --> |是| QueryBalance["查询账户余额"]
QueryBalance --> SaveAccount["保存账户信息"]
SaveAccount --> NextCookie["处理下一个Cookie"]
NextCookie --> LoopEnd{是否还有Cookie?}
LoopEnd --> |是| LoopStart
LoopEnd --> |否| TriggerValidation["触发验证和消费"]
TriggerValidation --> End([结束])
```
**Diagram sources**
- [card_info_jd_v1_jd_account_cookie_batch_add.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_batch_add.go)
- [card_info_original_jd_v1_original_jd_account_cookie_batch_add.go](file://internal/controller/card_info_original_jd/card_info_original_jd_v1_original_jd_account_cookie_batch_add.go)
**Section sources**
- [card_info_jd_v1_jd_account_cookie_batch_add.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_batch_add.go)
- [card_info_original_jd_v1_original_jd_account_cookie_batch_add.go](file://internal/controller/card_info_original_jd/card_info_original_jd_v1_original_jd_account_cookie_batch_add.go)
### 状态检测与刷新分析
系统实现了定期的状态检测机制确保京东账户的可用性通过定时任务扫描所有正常状态的账户调用京东API验证其有效性
#### 状态检测流程
```mermaid
flowchart TD
Start([定时任务启动]) --> GetTotal["获取账户总数"]
GetTotal --> LoopPages{分页处理}
LoopPages --> CreateSpan["创建追踪Span"]
CreateSpan --> QueryPage["查询一页账户"]
QueryPage --> LoopAccounts{遍历账户}
LoopAccounts --> ValidateCookie["验证Cookie有效性"]
ValidateCookie --> UpdateStatus["更新账户状态"]
UpdateStatus --> NextAccount["下一个账户"]
NextAccount --> LoopAccountsEnd{是否还有账户?}
LoopAccountsEnd --> |是| LoopAccounts
LoopAccountsEnd --> |否| NextPage["下一页"]
NextPage --> LoopPagesEnd{是否还有页?}
LoopPagesEnd --> |是| LoopPages
LoopPagesEnd --> |否| End([任务完成])
```
**Diagram sources**
- [card_redeem_account/schdule.go](file://internal/logic/card_redeem_account/schdule.go)
**Section sources**
- [card_redeem_account/schdule.go](file://internal/logic/card_redeem_account/schdule.go)
## 依赖分析
系统依赖于多个内部和外部组件内部依赖包括GoFrame框架数据库访问层和缓存系统外部依赖主要是京东API通过HTTP客户端进行通信系统还依赖于配置管理日志记录和分布式追踪等基础设施
```mermaid
graph LR
A[京东卡密账户管理] --> B[GoFrame框架]
A --> C[MySQL数据库]
A --> D[Redis缓存]
A --> E[京东API]
A --> F[OpenTelemetry]
A --> G[JWT认证]
style A fill:#f96,stroke:#333
```
**Diagram sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [originalJd/index.go](file://utility/integration/originalJd/index.go)
**Section sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [originalJd/index.go](file://utility/integration/originalJd/index.go)
## 性能考虑
系统在设计时考虑了多个性能优化点首先使用了缓存机制来减少对京东API的频繁调用特别是在用户信息和余额查询方面其次批量操作采用分页处理避免一次性加载过多数据导致内存溢出此外系统实现了接口限流防止恶意用户过度请求数据库查询也进行了优化使用了适当的索引和查询条件
## 故障排除指南
常见问题包括Cookie验证失败账户状态异常和接口调用频繁对于Cookie验证失败应检查Cookie格式是否正确是否包含必要的登录信息账户状态异常可能是由于京东安全策略导致建议重新获取Cookie接口调用频繁会触发限流机制用户需要等待一段时间后再试系统日志记录了详细的错误信息可通过日志追踪问题根源
**Section sources**
- [card_info_jd_v1_jd_account_cookie_check.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_cookie_check.go)
- [card_redeem_account/schdule.go](file://internal/logic/card_redeem_account/schdule.go)
## 结论
京东卡密账户管理系统提供了一套完整的解决方案用于管理京东账户的Cookie信息系统设计合理层次分明具有良好的可维护性和扩展性通过批量处理状态检测和性能优化系统能够高效地管理大量京东账户未来可以考虑增加更多的京东API集成如订单查询优惠券管理等功能进一步提升系统的实用价值

View File

@@ -0,0 +1,636 @@
# 卡密信息管理API
<cite>
**本文档引用文件**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [order.go](file://api/card_info_c_trip/v1/order.go)
- [config.go](file://api/card_info_c_trip/v1/config.go)
- [account.go](file://api/card_info_jd/v1/account.go)
- [order.go](file://api/card_info_jd/v1/order.go)
- [config.go](file://api/card_info_jd/v1/config.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
- [config.go](file://api/card_info_walmart/v1/config.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了卡密信息管理API涵盖Apple京东天猫沃尔玛和Ctrip等平台的卡密管理功能文档详细说明了每个平台的账户管理充值处理订单回调等接口的HTTP方法URL模式请求/响应模式和认证机制包括账户创建状态管理充值提交历史查询等端点提供实际使用示例错误处理策略和安全考虑解释了不同平台卡密管理的共性和差异提供客户端实现指南和性能优化建议
## 项目结构
项目结构按平台划分每个平台有独立的API模块包含账户管理和订单处理功能核心功能分布在`api`目录下的各个子模块中`card_info_apple``card_info_c_trip``card_info_jd``card_info_t_mall_game``card_info_walmart`每个模块包含`v1`版本的API定义包括账户订单和配置相关的接口
```mermaid
graph TB
subgraph "API模块"
Apple[card_info_apple]
Ctrip[card_info_c_trip]
JD[card_info_jd]
Tmall[card_info_t_mall_game]
Walmart[card_info_walmart]
end
Apple --> Account["账户管理"]
Apple --> Order["订单管理"]
Apple --> Config["配置管理"]
Ctrip --> Account
Ctrip --> Order
Ctrip --> Config
JD --> Account
JD --> Order
JD --> Config
Tmall --> Account
Tmall --> Order
Tmall --> Callback["回调管理"]
Walmart --> Account
Walmart --> Order
Walmart --> Config
Walmart --> Group["分组管理"]
style Apple fill:#f9f,stroke:#333
style Ctrip fill:#f9f,stroke:#333
style JD fill:#f9f,stroke:#333
style Tmall fill:#f9f,stroke:#333
style Walmart fill:#f9f,stroke:#333
```
**图示来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [account.go](file://api/card_info_jd/v1/account.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
**章节来源**
- [api/card_info_apple](file://api/card_info_apple)
- [api/card_info_c_trip](file://api/card_info_c_trip)
- [api/card_info_jd](file://api/card_info_jd)
- [api/card_info_t_mall_game](file://api/card_info_t_mall_game)
- [api/card_info_walmart](file://api/card_info_walmart)
## 核心组件
核心组件包括各平台的账户管理订单处理和配置管理功能每个平台都有独立的API端点用于账户创建更新删除和状态管理以及订单提交查询和回调处理配置管理功能允许设置各平台的充值规则和限制
**章节来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [account.go](file://api/card_info_jd/v1/account.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [order.go](file://api/card_info_c_trip/v1/order.go)
- [order.go](file://api/card_info_jd/v1/order.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
## 架构概述
系统采用模块化架构每个电商平台有独立的API模块共享通用的认证错误处理和数据访问层API层通过HTTP提供RESTful接口业务逻辑层处理具体业务规则数据访问层与数据库交互
```mermaid
graph TD
Client[客户端] --> API[API层]
API --> Business[业务逻辑层]
Business --> Data[数据访问层]
Data --> DB[(数据库)]
subgraph API层
AppleAPI[Apple API]
CtripAPI[Ctrip API]
JDAPI[JD API]
TmallAPI[Tmall API]
WalmartAPI[Walmart API]
end
subgraph 业务逻辑层
AccountLogic[账户逻辑]
OrderLogic[订单逻辑]
ConfigLogic[配置逻辑]
end
subgraph 数据访问层
AccountDAO[账户DAO]
OrderDAO[订单DAO]
ConfigDAO[配置DAO]
end
API --> AccountLogic
API --> OrderLogic
API --> ConfigLogic
AccountLogic --> AccountDAO
OrderLogic --> OrderDAO
ConfigLogic --> ConfigDAO
AccountDAO --> DB
OrderDAO --> DB
ConfigDAO --> DB
```
**图示来源**
- [controller/card_info_apple](file://internal/controller/card_info_apple)
- [controller/card_info_c_trip](file://internal/controller/card_info_c_trip)
- [controller/card_info_jd](file://internal/controller/card_info_jd)
- [controller/card_info_t_mall_game](file://internal/controller/card_info_t_mall_game)
- [controller/card_info_walmart](file://internal/controller/card_info_walmart)
## 详细组件分析
### Apple平台卡密管理
#### 账户管理
Apple平台提供完整的账户生命周期管理功能包括账户创建更新删除状态修改和批量导入
```mermaid
classDiagram
class AppleAccountRecord {
+string Account
+string Password
+int MaxAmountLimit
+int MaxCountLimit
+string Remark
}
class CardInfoListReq {
+string Account
+CommonPageReq
}
class CardInfoCreateReq {
+AppleAccountRecord
}
class CardInfoUpdateReq {
+CommonStrId
+AppleAccountRecord
}
class CardInfoDeleteReq {
+CommonStrId
}
class CardInfoUpdateStatusReq {
+CommonStrId
+AppleAccountStatus Status
}
CardInfoListReq --> AppleAccountRecord : "返回"
CardInfoCreateReq --> AppleAccountRecord : "包含"
CardInfoUpdateReq --> AppleAccountRecord : "包含"
CardInfoUpdateStatusReq --> AppleAccountRecord : "修改状态"
```
**图示来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go#L10-L86)
**章节来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
#### 订单管理
Apple平台提供礼品卡充值订单查询订单处理和回调功能
```mermaid
sequenceDiagram
participant Client
participant API
participant Business
participant DB
Client->>API : POST /cardInfo/appleCard/submit
API->>Business : 处理充值请求
Business->>DB : 保存订单信息
Business-->>API : 返回订单号
API-->>Client : 返回订单状态
Client->>API : GET /cardInfo/appleCard/query
API->>DB : 查询订单状态
DB-->>API : 返回订单信息
API-->>Client : 返回查询结果
```
**图示来源**
- [order.go](file://api/card_info_apple/v1/order.go#L10-L145)
**章节来源**
- [order.go](file://api/card_info_apple/v1/order.go)
#### 配置管理
Apple平台提供充值规则和限制的配置管理功能
```mermaid
classDiagram
class ConfigGetRes {
+bool IsAllowDifferentAmount
+bool IsAllowDifferentSucceedCallback
+bool IsAllowDifferentFailCallback
+int64 RedeemCardMinAmount
+bool IsAllowCompensatedCallback
+int RedeemCardRate
}
class ConfigSetReq {
+bool IsAllowDifferentAmount
+bool IsAllowDifferentSucceedCallback
+bool IsAllowDifferentFailCallback
+int64 RedeemCardMinAmount
+bool IsAllowCompensatedCallback
+int RedeemCardRate
}
ConfigSetReq --> ConfigGetRes : "设置"
```
**图示来源**
- [config.go](file://api/card_info_apple/v1/config.go#L10-L30)
**章节来源**
- [config.go](file://api/card_info_apple/v1/config.go)
### Ctrip平台卡密管理
#### 账户管理
Ctrip平台提供账户管理功能包括账户创建更新删除和状态管理
```mermaid
classDiagram
class AccountRecord {
+string Cookie
+string Name
+int MaxAmountLimit
+int MaxCountLimit
+int Status
+string Remark
}
class AccountCreateReq {
+AccountRecord
}
class AccountUpdateReq {
+CommonStrId
+AccountRecord
}
class AccountDeleteReq {
+CommonStrId
}
AccountCreateReq --> AccountRecord : "包含"
AccountUpdateReq --> AccountRecord : "包含"
```
**图示来源**
- [account.go](file://api/card_info_c_trip/v1/account.go#L10-L149)
**章节来源**
- [account.go](file://api/card_info_c_trip/v1/account.go)
#### 订单管理
Ctrip平台提供订单提交查询和回调功能
```mermaid
flowchart TD
Start([提交订单]) --> Validate["验证请求参数"]
Validate --> CheckCookie["检查账户Cookie"]
CheckCookie --> CreateOrder["创建订单记录"]
CreateOrder --> ReturnResult["返回订单信息"]
ReturnResult --> End([结束])
```
**图示来源**
- [order.go](file://api/card_info_c_trip/v1/order.go#L10-L56)
**章节来源**
- [order.go](file://api/card_info_c_trip/v1/order.go)
### 京东平台卡密管理
#### 账户管理
京东平台提供账户管理功能包括账户创建更新删除和状态管理
```mermaid
classDiagram
class JDAccountRecord {
+string Cookie
+string Name
+int MaxAmountLimit
+int MaxCountLimit
+string Remark
+int Status
}
class JDAccountCreateReq {
+JDAccountRecord
}
class JDAccountUpdateReq {
+CommonStrId
+JDAccountRecord
}
class JDAccountDeleteReq {
+CommonStrId
}
JDAccountCreateReq --> JDAccountRecord : "包含"
JDAccountUpdateReq --> JDAccountRecord : "包含"
```
**图示来源**
- [account.go](file://api/card_info_jd/v1/account.go#L10-L144)
**章节来源**
- [account.go](file://api/card_info_jd/v1/account.go)
#### 订单管理
京东平台提供订单提交查询和回调功能
```mermaid
sequenceDiagram
participant Client
participant API
participant Business
Client->>API : POST /cardInfo/JDCard/order/submit
API->>Business : 处理订单
Business-->>API : 返回处理结果
API-->>Client : 返回响应
```
**图示来源**
- [order.go](file://api/card_info_jd/v1/order.go#L10-L56)
**章节来源**
- [order.go](file://api/card_info_jd/v1/order.go)
### 天猫游戏平台卡密管理
#### 账户管理
天猫游戏平台提供账户创建查询状态切换和删除功能
```mermaid
classDiagram
class TMallGameAccountRecord {
+int Count
}
class TMallGameAccountCreateReq {
+TMallGameAccountRecord
}
class TMallGameAccountListReq {
+string AccountNumber
+CommonPageReq
}
class TMallGameAccountToggleReq {
+CommonStrId
}
class TMallGameAccountDeleteReq {
+CommonStrId
}
TMallGameAccountCreateReq --> TMallGameAccountRecord : "包含"
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L10-L71)
**章节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
#### 订单管理
天猫游戏平台提供订单提交查询和手动回调功能
```mermaid
classDiagram
class TMallGameOrderRecord {
+string Status
+string AccountNumber
+string OrderNo
+string MerchantOrder
+string ThirdMerchantOrder
+string TMallShopOrder
+*gtime.Time DateRange
+RechargeTMallGameCallBackType CallBackType
}
class TMallGameOrderSubmitReq {
+string AccountNumber
+float64 Amount
+string MerchantOrder
+string ThirdMerchantOrder
+string CallbackUrl
+RechargeTMallGameCallBackType CallbackType
+string Attach
+int TimeStamp
+string Sign
+string ChannelName
}
class TMallGameOrderModifyStatusSucceedReq {
+string TotpCode
+string OrderNo
}
TMallGameOrderSubmitReq --> TMallGameOrderRecord : "提交"
TMallGameOrderModifyStatusSucceedReq --> TMallGameOrderRecord : "修改状态"
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go#L10-L76)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
#### 回调管理
天猫游戏平台提供阿奇索回调和天猫授权回调功能
```mermaid
classDiagram
class TMallGameAgisoCallbackReq {
+string FromPlatform
+int TimeStamp
+AgisoCallbackStatus Aopic
+string Json
+string Sign
}
class TMallGameAccountAuthorizeCallbackReq {
+string Code
+TMallGameThirdPartyChannel Channel
}
class CallBackOrderManualReq {
+string OrderNo
+int64 ID
}
TMallGameAgisoCallbackReq --> TMallGameAgisoCallbackRes : "回调"
TMallGameAccountAuthorizeCallbackReq --> TMallGameAccountAuthorizeCallbackRes : "授权回调"
CallBackOrderManualReq --> CallBackOrderManualRes : "手动回调"
```
**图示来源**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go#L10-L36)
**章节来源**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
### 沃尔玛平台卡密管理
#### 账户管理
沃尔玛平台提供完整的账户管理功能包括账户创建更新删除状态管理分组管理和批量操作
```mermaid
classDiagram
class AccountRecord {
+string Cookie
+string Name
+int GroupId
+int MaxAmountLimit
+int MaxCountLimit
+int Status
+string Remark
}
class AccountCreateReq {
+AccountRecord
}
class AccountUpdateReq {
+CommonStrId
+AccountRecord
}
class AccountDeleteReq {
+CommonStrId
}
class AccountCookieBatchCheckReq {
+*ghttp.UploadFile File
}
AccountCreateReq --> AccountRecord : "包含"
AccountUpdateReq --> AccountRecord : "包含"
AccountCookieBatchCheckReq --> AccountRecord : "批量检查"
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go#L10-L242)
**章节来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
#### 订单管理
沃尔玛平台提供订单提交查询回调和导出功能
```mermaid
sequenceDiagram
participant Client
participant API
participant Business
Client->>API : POST /cardInfo/walmart/order/submit
API->>Business : 处理订单
Business-->>API : 返回处理结果
API-->>Client : 返回响应
Client->>API : GET /cardInfo/walmart/order/export
API->>Business : 生成导出文件
Business-->>API : 返回文件
API-->>Client : 下载文件
```
**图示来源**
- [order.go](file://api/card_info_walmart/v1/order.go#L10-L92)
**章节来源**
- [order.go](file://api/card_info_walmart/v1/order.go)
#### 配置管理
沃尔玛平台提供详细的配置管理功能包括充值规则重复充值设置和调度策略
```mermaid
classDiagram
class RedeemConfigGetRes {
+bool IsAllowDifferentAmount
+bool IsAllowDifferentSucceedCallback
+bool IsAllowDifferentFailCallback
+int64 RedeemCardMinAmount
+bool IsAllowCompensatedCallback
+int RedeemCardRate
+bool IsCardAllowRepeated
+int MaxAccountRedeemCount
+RedeemCardScheduleStrategyType RedeemOrderScheduleStrategy
}
class RedeemConfigSetReq {
+bool IsAllowDifferentAmount
+bool IsAllowDifferentSucceedCallback
+bool IsAllowDifferentFailCallback
+int64 RedeemCardMinAmount
+bool IsAllowCompensatedCallback
+int RedeemCardRate
+bool IsCardAllowRepeated
+int MaxAccountRedeemCount
+RedeemCardScheduleStrategyType RedeemOrderScheduleStrategy
}
RedeemConfigSetReq --> RedeemConfigGetRes : "设置"
```
**图示来源**
- [config.go](file://api/card_info_walmart/v1/config.go#L10-L40)
**章节来源**
- [config.go](file://api/card_info_walmart/v1/config.go)
## 依赖分析
系统各模块之间依赖关系清晰每个平台的API模块独立共享通用的认证错误处理和数据访问组件通过接口隔离不同平台的实现细节确保系统的可扩展性和维护性
```mermaid
graph TD
AppleAPI --> CommonAPI
CtripAPI --> CommonAPI
JDAPI --> CommonAPI
TmallAPI --> CommonAPI
WalmartAPI --> CommonAPI
CommonAPI --> Auth[认证模块]
CommonAPI --> ErrorHandler[错误处理模块]
CommonAPI --> Response[响应处理模块]
AppleAPI --> AppleDAO[Apple数据访问]
CtripAPI --> CtripDAO[Ctrip数据访问]
JDAPI --> JDDAO[JD数据访问]
TmallAPI --> TmallDAO[Tmall数据访问]
WalmartAPI --> WalmartDAO[Walmart数据访问]
AppleDAO --> DB[(数据库)]
CtripDAO --> DB
JDDAO --> DB
TmallDAO --> DB
WalmartDAO --> DB
```
**图示来源**
- [commonApi/common.go](file://api/commonApi/common.go)
- [internal/controller](file://internal/controller)
- [internal/dao](file://internal/dao)
**章节来源**
- [commonApi/common.go](file://api/commonApi/common.go)
- [internal/controller](file://internal/controller)
- [internal/dao](file://internal/dao)
## 性能考虑
系统在设计时考虑了性能优化包括
- 使用分页查询避免大数据量加载
- 提供批量操作接口减少网络往返
- 支持异步处理和回调机制
- 实现缓存机制提高访问速度
- 优化数据库查询和索引
对于高并发场景建议
- 使用连接池管理数据库连接
- 实现请求限流和熔断机制
- 采用消息队列解耦处理流程
- 对热点数据进行缓存
- 监控系统性能指标并及时优化
## 故障排除指南
常见问题及解决方案
1. **账户创建失败**
- 检查Cookie有效性
- 验证必填字段是否完整
- 确认账户数量限制
2. **订单提交失败**
- 检查卡密格式和有效性
- 验证回调地址可访问性
- 确认商户ID正确性
3. **回调不成功**
- 检查网络连接
- 验证签名正确性
- 确认时间戳有效性
4. **性能问题**
- 检查数据库连接池配置
- 监控系统资源使用情况
- 优化慢查询
**章节来源**
- [errHandler/handler.go](file://internal/errHandler/handler.go)
- [middleware/error_handler.go](file://internal/middleware/error_handler.go)
## 结论
卡密信息管理API为多个电商平台提供了统一的卡密管理接口具有良好的扩展性和维护性通过模块化设计各平台功能独立又共享通用组件确保了系统的稳定性和可扩展性API设计遵循RESTful规范提供了完整的账户管理订单处理和配置管理功能满足了卡密管理的各种需求

View File

@@ -0,0 +1,291 @@
# 天猫卡密回调机制
<cite>
**本文档引用文件**
- [asigo.go](file://internal/consts/asigo.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [agiso.go](file://internal/model/agiso.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [utils.go](file://utility/integration/agiso/utils.go)
- [models.go](file://utility/integration/agiso/models.go)
- [api.go](file://utility/integration/tmall/api/api.go)
- [handler.go](file://internal/errHandler/handler.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了天猫卡密系统中的回调机制重点涵盖阿奇索Agiso回调和订单状态回调接口的实现文档全面说明了回调接收验证处理等端点的HTTP方法URL模式请求/响应模式和安全机制通过实际使用示例包括Agiso回调处理订单状态更新错误重试等场景深入解释了天猫平台特有的Agiso回调协议和安全验证机制同时文档提供了错误处理策略安全考虑服务端实现指南和性能优化建议特别关注回调的幂等性处理和安全性验证
## 项目结构
天猫卡密系统的项目结构清晰地划分了API接口内部逻辑数据访问和工具集成等模块核心的天猫游戏卡密功能位于`api/card_info_t_mall_game``internal/controller/card_info_t_mall_game`目录下`v1/callback.go`文件定义了回调接口的请求和响应模型`internal/controller/card_info_t_mall_game`目录下的控制器实现了具体的业务逻辑`internal/service``internal/model`包负责服务层和数据模型的定义`utility/integration`包则封装了与Agiso和天猫平台的第三方集成
```mermaid
graph TD
subgraph "API 接口层"
A[api/card_info_t_mall_game/v1/callback.go]
B[api/card_info_t_mall_game/v1/order.go]
end
subgraph "控制器层"
C[internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go]
end
subgraph "服务与模型层"
D[internal/service/card_t_mall_order.go]
E[internal/model/agiso.go]
F[internal/model/card_t_mall_game_order.go]
end
subgraph "工具与集成层"
G[utility/integration/agiso/utils.go]
H[utility/integration/agiso/models.go]
I[utility/integration/tmall/api/api.go]
end
A --> C
B --> C
C --> D
D --> E
D --> F
C --> G
G --> H
C --> I
```
**Diagram sources**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [agiso.go](file://internal/model/agiso.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [utils.go](file://utility/integration/agiso/utils.go)
- [models.go](file://utility/integration/agiso/models.go)
- [api.go](file://utility/integration/tmall/api/api.go)
**Section sources**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
## 核心组件
天猫卡密回调机制的核心组件包括Agiso回调处理器订单状态服务和安全验证模块`TMallGameAgisoCallback`控制器是整个回调流程的入口负责接收来自Agiso平台的HTTP POST请求`RechargeTMallGameOrder`服务提供了处理订单状态更新关联订单发货和回调第三方等核心业务逻辑`agiso.GenerateCallbackSign`函数实现了关键的安全验证确保回调请求的来源可信这些组件协同工作确保了从买家付款到最终订单完成的自动化流程
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [utils.go](file://utility/integration/agiso/utils.go)
## 架构概述
天猫卡密系统的回调架构是一个典型的事件驱动架构当买家在天猫平台完成支付后Agiso平台会向本系统发起一个HTTP POST回调请求该请求首先由`TMallGameAgisoCallback`端点接收经过签名验证后根据回调类型如买家付款交易成功分发到不同的处理函数处理函数会调用`RechargeTMallGameOrder`服务与天猫API交互获取订单详情并更新本地数据库中的订单状态整个流程通过异步任务池pool进行优化确保高并发下的性能和稳定性
```mermaid
sequenceDiagram
participant Agiso as Agiso平台
participant Gateway as 回调网关
participant Controller as TMallGameAgisoCallback
participant Service as RechargeTMallGameOrder
participant TMallAPI as 天猫API
participant DB as 数据库
Agiso->>Gateway : POST /recharge/tMallGame/agiso/callback
Gateway->>Controller : 转发请求
Controller->>Controller : 验证签名(GenerateCallbackSign)
alt 签名验证失败
Controller-->>Agiso : 返回错误
else 签名验证成功
Controller->>Controller : 根据aopic分发
opt 买家付款(CALLBACK_PAYMENT_SUCCESS)
Controller->>Service : handleCallBackPaymentWithoutJudgementSuccess
Service->>TMallAPI : TBMallTradeGet(获取订单详情)
TMallAPI-->>Service : 订单数据
Service->>DB : 更新订单状态(UpdateOrderStatusByTBOrderNo)
Service->>TMallAPI : VirtualDelivery(虚拟发货)
TMallAPI-->>Service : 发货结果
Service->>DB : 记录发货历史
end
opt 交易成功(CALLBACK_PAYMENT_TRADE_SUCCESS)
Controller->>Service : handleBuyerConfirmWithoutJudgementMessage
Service->>DB : 获取淘宝订单(GetShopOneByTid)
Service->>DB : 关联主订单(AssociateCreatedOrderAndStatus)
Service->>DB : 更新订单状态为待评价或完成
opt 需要回调第三方
Service->>Service : CallBackOrderToUpstream
end
end
Controller-->>Agiso : 返回成功
end
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [api.go](file://utility/integration/tmall/api/api.go)
## 详细组件分析
### Agiso回调处理分析
Agiso回调处理是整个系统的核心它确保了外部平台事件能够被正确接收和处理
#### 回调接口定义
```mermaid
classDiagram
class TMallGameAgisoCallbackReq {
+FromPlatform string
+TimeStamp int
+Aopic AgisoCallbackStatus
+Json string
+Sign string
}
class TMallGameAgisoCallbackRes {
}
class AgisoCallbackStatus {
+CALLBACK_PAYMENT_SUCCESS
+CALLBACK_PAYMENT_TRADE_SUCCESS
+Callback_AUTO_SHIPPING_SUCCESS
+Callback_PAYMENT_REFUND_APPLY
+Callback_REVOKE_REFUND
+Callback_MODIFY_ORDER_REMARK
+Callback_SELLER_SHIPPING
+CALLBACK_EVALUATION_SUCCESS
}
TMallGameAgisoCallbackReq --> AgisoCallbackStatus : "包含"
```
**Diagram sources**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [asigo.go](file://internal/consts/asigo.go)
#### 回调处理流程
```mermaid
flowchart TD
Start([接收回调请求]) --> ValidateSign["验证签名(GenerateCallbackSign)"]
ValidateSign --> SignValid{"签名有效?"}
SignValid --> |否| ReturnError["返回验证失败"]
SignValid --> |是| LockOrder["获取订单锁(防止重复处理)"]
LockOrder --> CheckAopic{"检查Aopic类型"}
CheckAopic --> |CALLBACK_PAYMENT_SUCCESS| HandlePayment["处理买家付款"]
CheckAopic --> |CALLBACK_PAYMENT_TRADE_SUCCESS| HandleTradeSuccess["处理交易成功"]
CheckAopic --> |CALLBACK_EVALUATION_SUCCESS| HandleEvaluation["处理评价成功"]
CheckAopic --> |其他| LogError["记录未知类型错误"]
HandlePayment --> GetOrderDetail["调用TBMallTradeGet获取订单详情"]
GetOrderDetail --> UpdateLocalDB["更新本地订单状态为已支付"]
UpdateLocalDB --> VirtualDelivery["调用VirtualDelivery进行虚拟发货"]
VirtualDelivery --> DeliverySuccess{"发货成功?"}
DeliverySuccess --> |是| UpdateStatus["更新状态为发货成功"]
DeliverySuccess --> |否| Retry["重试(最多3次)"]
Retry --> UpdateStatus
HandleTradeSuccess --> GetShopOrder["根据Tid获取淘宝订单"]
GetShopOrder --> AssociateOrder["关联主订单(AssociateCreatedOrderAndStatus)"]
AssociateOrder --> CheckAmount["检查金额是否匹配"]
CheckAmount --> |不匹配| UpdateStatusWrongAmount["更新为金额不符状态"]
CheckAmount --> |匹配| CheckCallbackType["检查回调类型"]
CheckCallbackType --> |Confirm| UpdateStatusFinished["更新为完成状态并回调第三方"]
CheckAmount --> |Evaluation| UpdateStatusWaitEval["更新为待评价状态"]
ReturnError --> End([结束])
UpdateStatus --> End
UpdateStatusWrongAmount --> End
UpdateStatusFinished --> End
UpdateStatusWaitEval --> End
LogError --> End
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [utils.go](file://utility/integration/agiso/utils.go)
### 订单状态更新分析
订单状态更新是确保系统内部状态与外部平台同步的关键
#### 订单状态模型
```mermaid
erDiagram
V1_RECHARGE_TMALL_ORDER {
string order_no PK
float amount
string status
string callback_url
string callback_type
string attach
string merchant_order
string third_merchant_order
datetime created_at
datetime updated_at
}
V1_RECHARGE_TMALL_SHOP {
int id PK
string order_no FK
string t_mall_order_no
string buyer_nick
string payment
string status
datetime created
datetime pay_time
datetime end_time
string original_data
}
V1_RECHARGE_TMALL_ORDER ||--o{ V1_RECHARGE_TMALL_SHOP : "1:N"
```
**Diagram sources**
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [agiso.go](file://internal/model/agiso.go)
#### 状态转换逻辑
订单状态遵循严格的转换流程从创建支付发货评价到最终完成任何状态的更新都通过`UpdateOrderStatusByTBOrderNo`等服务方法进行确保了数据的一致性和可追溯性
**Section sources**
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
## 依赖分析
系统依赖于多个内部和外部组件内部依赖包括`gogf`框架`lancet`工具库和`sonic`高性能JSON解析器外部依赖主要是Agiso平台和天猫开放API`utility/integration`包封装了这些外部依赖为上层业务逻辑提供了统一的接口降低了耦合度
```mermaid
graph LR
A[TMallGameAgisoCallback] --> B[RechargeTMallGameOrder]
B --> C[TMallAPI]
B --> D[数据库]
A --> E[GenerateCallbackSign]
E --> F[config.GetAgiso]
F --> G[配置文件]
C --> H[InnerClient]
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [api.go](file://utility/integration/tmall/api/api.go)
- [utils.go](file://utility/integration/agiso/utils.go)
**Section sources**
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [api.go](file://utility/integration/tmall/api/api.go)
- [utils.go](file://utility/integration/agiso/utils.go)
## 性能考虑
为了应对高并发的回调请求系统采用了多种性能优化策略首先使用`gmutex`和Redis缓存`cache.TMallGameOrderSign`来实现订单级别的锁防止同一订单被重复处理其次通过`pool.New`创建异步任务池将耗时的网络请求如调用天猫API放入后台执行避免阻塞主线程最后代码中使用了`retry.Retry`机制对关键操作如虚拟发货进行重试提高了系统的容错能力
## 故障排除指南
在处理回调时常见的问题包括签名验证失败订单重复推送金额不匹配和发货失败
- **签名验证失败**检查`config.yaml`中的`AppSecret`是否与Agiso平台配置一致
- **订单重复推送**系统通过缓存锁机制防止重复处理若出现此问题检查Redis连接是否正常
- **金额不匹配**买家支付的金额与系统订单金额不一致系统会自动将订单状态更新为`RechargeTMallGameOrderStatusFinishedWithWrongAmount`
- **发货失败**系统会尝试最多3次发货若均失败则更新状态为`RechargeTMallGameOrderStatusDeliveryFailed`并记录错误日志
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [handler.go](file://internal/errHandler/handler.go)
## 结论
本文档详细阐述了天猫卡密系统的回调机制涵盖了从接口定义安全验证到业务处理的完整流程该系统设计合理通过幂等性处理和异步任务池等机制确保了在高并发场景下的稳定性和可靠性开发者在实现类似功能时应重点关注安全性签名验证幂等性防止重复处理和错误处理重试机制这三个方面以构建健壮的回调系统

View File

@@ -0,0 +1,383 @@
# 天猫卡密工作区管理
<cite>
**本文档引用文件**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
</cite>
## 目录
1. [简介](#简介)
2. [工作区管理API概览](#工作区管理api概览)
3. [数据同步接口](#数据同步接口)
4. [状态监控接口](#状态监控接口)
5. [配置管理接口](#配置管理接口)
6. [架构设计与数据隔离](#架构设计与数据隔离)
7. [错误处理与安全考虑](#错误处理与安全考虑)
8. [管理端实现指南](#管理端实现指南)
9. [性能优化建议](#性能优化建议)
10. [实际使用示例](#实际使用示例)
## 简介
本文档详细介绍了天猫卡密工作区管理系统的API接口涵盖数据同步配置管理状态监控等核心功能系统通过RESTful API提供工作区创建数据同步状态查询等端点支持大规模卡密订单的高效处理与监控文档详细说明了各接口的HTTP方法URL模式请求/响应模式和认证机制并提供实际使用场景示例
## 工作区管理API概览
天猫卡密工作区管理API提供了一套完整的接口用于管理工作区的生命周期数据同步和状态监控API基于GoFrame框架构建采用模块化设计主要功能包括工作区数据同步订单统计状态查询等
```mermaid
graph TB
subgraph "API接口层"
A[数据同步接口]
B[状态监控接口]
C[配置管理接口]
end
subgraph "服务层"
D[订单服务]
E[账户服务]
F[店铺服务]
end
subgraph "数据层"
G[订单数据]
H[账户数据]
I[店铺数据]
J[历史数据]
end
A --> D
B --> D
C --> D
D --> G
D --> H
D --> I
D --> J
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
## 数据同步接口
数据同步接口用于实时同步天猫卡密工作区的订单账户店铺等数据确保系统数据的及时性和一致性
### 数据同步端点
- **URL**: `/recharge/tMallGame/data/sync`
- **HTTP方法**: POST
- **功能**: 同步指定渠道在指定时间范围内的所有相关数据
#### 请求参数
| 参数名 | 类型 | 必填 | 描述 |
|--------|------|------|------|
| channelName | string | | 渠道名称 |
| duration | int | | 同步时长 |
#### 响应数据结构
同步接口返回包含以下数据集合的响应
- 订单数据OrderData
- 账户数据AccountData
- 店铺数据ShopData
- 订单历史数据OrderHistory
- 店铺历史数据ShopHistory
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API网关"
participant Controller as "控制器"
participant DAO as "数据访问层"
Client->>API : POST /recharge/tMallGame/data/sync
API->>Controller : 转发请求
Controller->>DAO : 查询订单数据
DAO-->>Controller : 返回订单数据
Controller->>DAO : 查询关联账户数据
DAO-->>Controller : 返回账户数据
Controller->>DAO : 查询关联店铺数据
DAO-->>Controller : 返回店铺数据
Controller->>DAO : 查询订单历史数据
DAO-->>Controller : 返回订单历史数据
Controller->>DAO : 查询店铺历史数据
DAO-->>Controller : 返回店铺历史数据
Controller-->>API : 组装完整响应
API-->>Client : 返回同步数据
```
**图示来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
**本节来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
## 状态监控接口
状态监控接口提供工作区的实时状态和统计信息支持运营监控和数据分析
### 每日订单统计接口
- **URL**: `/recharge/tMallGame/workspace/orderSummary`
- **HTTP方法**: GET
- **功能**: 获取每日订单统计信息
#### 请求参数
| 参数名 | 类型 | 必填 | 描述 |
|--------|------|------|------|
| channelName | string | | 渠道名称 |
| callbackType | RechargeTMallGameCallBackType | | 回调类型 |
#### 响应数据结构
```json
{
"total": 100,
"list": [
{
"count": 20,
"succeedCount": 18,
"succeedAmount": 1800.00,
"amount": 2000.00,
"rate": 0.9,
"date": "2024-01-01"
}
]
}
```
### 基本统计信息接口
- **URL**: `/recharge/tMallGame/workspace/stats`
- **HTTP方法**: GET
- **功能**: 获取工作区基本统计信息
#### 请求参数
| 参数名 | 类型 | 必填 | 描述 |
|--------|------|------|------|
| channelName | string | | 渠道名称 |
#### 响应数据结构
```json
{
"totalCount": 1000,
"totalSucceedCount": 950,
"totalAmount": 95000.00,
"totalSucceedAmount": 90250.00,
"todayCount": 50,
"todaySucceedCount": 48,
"todayAmount": 4800.00,
"todaySucceedAmount": 4560.00,
"totalRate": 0.95,
"todayRate": 0.96
}
```
```mermaid
flowchart TD
Start([获取状态监控数据]) --> ValidateInput["验证输入参数"]
ValidateInput --> InputValid{"参数有效?"}
InputValid --> |否| ReturnError["返回参数错误"]
InputValid --> |是| QueryStats["查询统计信息"]
QueryStats --> StatsResult{"查询成功?"}
StatsResult --> |否| HandleError["处理查询错误"]
StatsResult --> |是| FormatResponse["格式化响应数据"]
FormatResponse --> ReturnResult["返回统计结果"]
HandleError --> ReturnError
ReturnError --> End([结束])
ReturnResult --> End
```
**图示来源**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
**本节来源**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
## 配置管理接口
配置管理接口用于管理工作区的运行参数和业务配置确保系统能够适应不同的业务需求
### 配置获取接口
- **URL**: `/recharge/tMallGame/account/authorize/getKey`
- **HTTP方法**: GET
- **功能**: 获取天猫游戏配置信息
#### 响应数据结构
```json
{
"code": "appKey",
"redirectUri": "https://callback.example.com"
}
```
### 账户状态切换接口
- **URL**: `/recharge/tMallGame/account/toggle`
- **HTTP方法**: POST
- **功能**: 切换账户状态启用/禁用
#### 请求参数
| 参数名 | 类型 | 必填 | 描述 |
|--------|------|------|------|
| id | string | | 账户ID |
| status | int | | 状态1:启用, 0:禁用 |
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_get_key.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_get_key.go)
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go)
## 架构设计与数据隔离
天猫卡密工作区管理系统采用分层架构设计确保系统的可维护性和可扩展性
### 分层架构
系统采用典型的三层架构
1. **API接口层**: 提供RESTful API接口
2. **服务层**: 实现业务逻辑处理
3. **数据层**: 负责数据持久化和访问
### 数据隔离机制
系统通过以下机制实现数据隔离
- **渠道隔离**: 不同渠道的数据通过channelName字段进行隔离
- **时间范围隔离**: 数据同步通过时间戳范围进行隔离
- **关联查询隔离**: 通过外键关联确保数据一致性
```mermaid
erDiagram
ORDER {
string order_no PK
string account_id FK
string channel_name
float amount
int status
datetime created_at
datetime updated_at
}
ACCOUNT {
string id PK
string account_number UK
string channel_name
int status
datetime created_at
datetime updated_at
}
SHOP {
string order_no PK, FK
string t_mall_order_no
datetime end_time
datetime created_at
datetime updated_at
}
ORDER_HISTORY {
int id PK
string order_no FK
int status
datetime created_at
datetime updated_at
}
SHOP_HISTORY {
int id PK
int shop_id FK
string status
datetime created_at
datetime updated_at
}
ORDER ||--o{ ACCOUNT : "belongs to"
ORDER ||--o{ SHOP : "has"
ORDER ||--o{ ORDER_HISTORY : "has"
ORDER_HISTORY ||--o{ SHOP_HISTORY : "has"
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
## 错误处理与安全考虑
系统实现了完善的错误处理和安全机制确保系统的稳定性和安全性
### 错误处理策略
- **统一错误包装**: 使用errHandler.WrapError统一包装错误
- **错误码体系**: 基于gcode.Code体系定义错误码
- **日志记录**: 关键操作和错误信息记录到日志
### 安全考虑
- **参数验证**: 所有输入参数进行严格验证
- **缓存保护**: 使用gmlock确保缓存操作的线程安全
- **敏感信息保护**: 关键配置信息从配置中心获取
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go)
## 管理端实现指南
管理端实现应遵循以下指南确保系统的稳定性和性能
### 实现要点
1. **异步处理**: 大规模数据同步采用异步处理模式
2. **批量操作**: 尽量使用批量查询和更新操作
3. **缓存策略**: 合理使用缓存减少数据库压力
4. **锁机制**: 使用gmlock确保关键操作的线程安全
### 最佳实践
- **分页查询**: 大数据量查询使用分页
- **连接池**: 使用数据库连接池提高性能
- **监控告警**: 关键接口添加监控和告警
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go)
## 性能优化建议
针对大规模数据同步场景提出以下性能优化建议
### 查询优化
- **索引优化**: 在channelNameupdatedAt等常用查询字段上建立索引
- **批量查询**: 使用WhereIn一次性查询关联数据
- **时间范围查询**: 使用时间戳范围限制查询数据量
### 缓存优化
- **热点数据缓存**: 将频繁访问的数据缓存到Redis
- **缓存预热**: 在高峰期前预热常用数据
- **缓存失效策略**: 设置合理的缓存失效时间
### 并发优化
- **并发控制**: 根据系统负载调整并发度
- **连接池配置**: 优化数据库连接池大小
- **资源监控**: 实时监控系统资源使用情况
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
## 实际使用示例
以下是天猫卡密工作区管理API的实际使用示例
### 工作区数据同步示例
```bash
curl -X POST \
http://api.example.com/recharge/tMallGame/data/sync \
-H 'Content-Type: application/json' \
-d '{
"channelName": "channel_001",
"duration": 300
}'
```
### 状态监控查询示例
```bash
curl -X GET \
"http://api.example.com/recharge/tMallGame/workspace/stats?channelName=channel_001" \
-H 'Content-Type: application/json'
```
### 配置更新示例
```bash
curl -X POST \
http://api.example.com/recharge/tMallGame/account/toggle \
-H 'Content-Type: application/json' \
-d '{
"id": "account_001",
"status": 1
}'
```
**本节来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go)

View File

@@ -0,0 +1,273 @@
# 天猫卡密店铺管理
<cite>
**本文档引用的文件**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_shop_order_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_shop_order_list.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了天猫卡密店铺管理API涵盖商品查询订单同步库存管理等核心功能系统通过天猫平台与卡密系统的数据同步机制实现店铺商品信息订单状态和库存的实时管理文档详细说明了各接口的HTTP方法URL模式请求/响应模式和认证机制并提供实际使用示例包括店铺商品同步订单获取和库存状态更新等场景
## 项目结构
天猫卡密店铺管理系统的代码结构遵循模块化设计原则主要分为API接口层业务逻辑层数据访问层和模型层系统通过分层架构实现了关注点分离提高了代码的可维护性和可扩展性
```mermaid
graph TB
subgraph "API接口层"
A[account.go]
B[order.go]
C[shop.go]
D[sync.go]
end
subgraph "控制器层"
E[card_info_t_mall_game_v1_t_mall_game_account_list.go]
F[card_info_t_mall_game_v1_t_mall_game_order_query_order.go]
G[card_info_t_mall_game_v1_t_mall_game_shop_order_list.go]
H[card_info_t_mall_game_v1_t_mall_game_data_sync.go]
end
subgraph "服务层"
I[card_t_mall_order.go]
end
subgraph "模型层"
J[card_t_mall_game_account.go]
K[card_t_mall_game_order.go]
end
subgraph "数据访问层"
L[v_1_recharge_t_mall_account.go]
M[v_1_recharge_t_mall_order.go]
end
A --> E
B --> F
C --> G
D --> H
E --> I
F --> I
G --> I
H --> I
I --> J
I --> K
J --> L
K --> M
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_shop_order_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_shop_order_list.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
**本节来源**
- [api/card_info_t_mall_game/v1](file://api/card_info_t_mall_game/v1)
- [internal/controller/card_info_t_mall_game](file://internal/controller/card_info_t_mall_game)
## 核心组件
天猫卡密店铺管理系统的核心组件包括账户管理订单管理店铺管理和数据同步模块这些组件共同协作实现天猫店铺与卡密系统的无缝集成系统通过标准化的API接口提供商品列表获取订单详情查询和库存同步等功能确保数据的一致性和实时性
**本节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
## 架构概述
天猫卡密店铺管理系统采用分层架构设计包括API接口层控制器层服务层模型层和数据访问层这种架构设计实现了业务逻辑与数据访问的分离提高了系统的可维护性和可扩展性系统通过RESTful API提供服务支持商品查询订单同步和库存管理等核心功能
```mermaid
graph TD
Client[客户端] --> API[API接口层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Model[模型层]
Service --> DAO[数据访问层]
DAO --> Database[(数据库)]
API -.->|HTTP请求| Controller
Controller -.->|业务逻辑处理| Service
Service -.->|数据操作| DAO
DAO -.->|数据库操作| Database
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_shop_order_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_shop_order_list.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
## 详细组件分析
### 账户管理分析
账户管理模块负责天猫卡密店铺的账户信息维护和管理系统提供账户创建删除状态切换和授权等功能确保店铺账户的安全性和可用性
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DAO as "数据访问层"
Client->>API : GET /api/v1/tmall/account/list
API->>Controller : 调用账户列表查询
Controller->>Service : 获取账户列表
Service->>DAO : 查询数据库
DAO-->>Service : 返回账户数据
Service-->>Controller : 处理数据
Controller-->>API : 返回结果
API-->>Client : 返回账户列表
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
**本节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
### 订单管理分析
订单管理模块负责天猫卡密店铺的订单查询和状态管理系统提供订单查询状态修改和订单统计等功能确保订单数据的准确性和实时性
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DAO as "数据访问层"
Client->>API : POST /api/v1/tmall/order/query
API->>Controller : 调用订单查询
Controller->>Service : 查询订单信息
Service->>DAO : 查询订单数据
DAO-->>Service : 返回订单数据
Service-->>Controller : 处理订单数据
Controller-->>API : 返回结果
API-->>Client : 返回订单信息
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
**本节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
### 店铺管理分析
店铺管理模块负责天猫卡密店铺的商品信息和订单历史管理系统提供店铺订单查询订单历史获取和天猫订单历史同步等功能确保店铺数据的完整性和一致性
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DAO as "数据访问层"
Client->>API : GET /api/v1/tmall/shop/order/list
API->>Controller : 调用店铺订单列表
Controller->>Service : 获取店铺订单
Service->>DAO : 查询店铺订单数据
DAO-->>Service : 返回店铺订单数据
Service-->>Controller : 处理数据
Controller-->>API : 返回结果
API-->>Client : 返回店铺订单列表
```
**图示来源**
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [card_info_t_mall_game_v1_t_mall_game_shop_order_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_shop_order_list.go)
**本节来源**
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [card_info_t_mall_game_v1_t_mall_game_shop_order_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_shop_order_list.go)
### 数据同步分析
数据同步模块负责天猫卡密店铺的数据同步任务系统提供定时数据同步功能确保天猫平台与卡密系统之间的数据一致性
```mermaid
flowchart TD
Start([开始]) --> CheckSyncTime["检查同步时间"]
CheckSyncTime --> NeedSync{"需要同步?"}
NeedSync --> |是| ExecuteSync["执行数据同步"]
NeedSync --> |否| End([结束])
ExecuteSync --> SyncAccount["同步账户数据"]
SyncAccount --> SyncOrder["同步订单数据"]
SyncOrder --> UpdateStatus["更新同步状态"]
UpdateStatus --> End
```
**图示来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
**本节来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
## 依赖分析
天猫卡密店铺管理系统各组件之间存在明确的依赖关系API接口层依赖于控制器层控制器层依赖于服务层服务层依赖于模型层和数据访问层这种依赖关系确保了系统的模块化和可维护性
```mermaid
graph LR
API[API接口层] --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Model[模型层]
Service --> DAO[数据访问层]
Model --> Database[(数据库)]
DAO --> Database
classDef default fill:#f9f,stroke:#333,stroke-width:1px;
```
**图示来源**
- [card_info_t_mall_game.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go)
**本节来源**
- [internal/controller/card_info_t_mall_game](file://internal/controller/card_info_t_mall_game)
- [internal/service](file://internal/service)
- [internal/model](file://internal/model)
- [internal/dao](file://internal/dao)
## 性能考虑
天猫卡密店铺管理系统在设计时充分考虑了性能因素系统采用缓存机制减少数据库查询次数使用异步处理提高响应速度并通过分页查询优化大数据量处理此外系统还实现了请求限流和错误重试机制确保在高并发场景下的稳定运行
## 故障排除指南
当遇到天猫卡密店铺管理系统的使用问题时建议按照以下步骤进行排查首先检查API请求的认证信息是否正确然后验证请求参数是否符合规范接着查看系统日志获取详细的错误信息最后根据错误代码参考文档中的错误处理策略进行解决对于数据同步问题需要检查同步任务的执行状态和网络连接情况
**本节来源**
- [errHandler](file://internal/dao/errHandler)
- [middleware](file://internal/middleware)
## 结论
天猫卡密店铺管理系统通过完善的API接口和稳健的架构设计实现了天猫店铺与卡密系统的高效集成系统提供了商品查询订单同步和库存管理等核心功能确保了数据的实时性和一致性通过合理的分层架构和依赖管理系统具有良好的可维护性和可扩展性能够满足不断变化的业务需求

View File

@@ -0,0 +1,314 @@
# 天猫卡密管理API
<cite>
**本文档引用文件**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了天猫卡密管理API涵盖账户授权订单处理店铺管理等核心接口重点说明了账户创建OAuth授权订单提交店铺信息同步等端点的HTTP方法URL模式请求/响应模式和认证机制文档还解释了天猫卡密特有的Agiso回调机制和workspace管理提供错误处理策略和安全考虑并包含客户端实现指南和性能优化建议
## 项目结构
天猫卡密管理API的代码结构清晰主要分为API接口层内部逻辑层和服务层API接口定义位于`api/card_info_t_mall_game/v1/`目录下包含账户订单店铺回调和工作空间等模块内部实现位于`internal/`目录包括模型定义常量控制器服务和工具类
```mermaid
graph TD
subgraph "API接口层"
A[account.go]
B[order.go]
C[shop.go]
D[callback.go]
E[workspace.go]
end
subgraph "内部实现层"
F[card_t_mall_game_account.go]
G[card_t_mall_game_order.go]
H[card_t_mall_game_work_space.go]
I[card_recharge_t_mall.go]
end
subgraph "服务层"
J[card_t_mall_account.go]
K[card_t_mall_order.go]
end
subgraph "控制器层"
L[card_info_t_mall_game_v1_*.go]
end
A --> F
B --> G
C --> G
D --> L
E --> H
F --> J
G --> K
H --> K
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
**章节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
## 核心组件
天猫卡密管理API的核心组件包括账户管理订单处理店铺同步回调处理和统计分析账户管理负责天猫游戏账户的创建查询和状态管理订单处理模块处理订单的提交查询和状态更新店铺同步功能实现与天猫店铺订单的关联和信息同步回调处理模块接收来自Agiso和天猫的回调通知统计分析组件提供订单和账户的统计信息
**章节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
## 架构概述
天猫卡密管理API采用分层架构设计包括API接口层业务逻辑层服务层和数据访问层API接口层定义了RESTful端点业务逻辑层处理具体的业务规则服务层提供可重用的服务接口数据访问层负责与数据库交互
```mermaid
graph TD
A[客户端] --> B[API接口层]
B --> C[业务逻辑层]
C --> D[服务层]
D --> E[数据访问层]
E --> F[数据库]
B --> G[认证中间件]
C --> H[错误处理]
D --> I[事务管理]
style A fill:#f9f,stroke:#333
style F fill:#bbf,stroke:#333
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
## 详细组件分析
### 账户管理分析
账户管理组件提供天猫游戏账户的全生命周期管理功能包括创建查询状态切换和删除
#### 账户创建
```mermaid
flowchart TD
Start([创建账户请求]) --> Validate["验证请求参数"]
Validate --> Exists{"账户已存在?"}
Exists --> |是| ReturnError["返回错误"]
Exists --> |否| Create["创建账户记录"]
Create --> Enable["启用账户"]
Enable --> ReturnSuccess["返回成功"]
style Start fill:#4CAF50,stroke:#333
style ReturnSuccess fill:#4CAF50,stroke:#333
style ReturnError fill:#F44336,stroke:#333
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L10-L20)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L15-L25)
#### 账户授权
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API服务"
participant Tmall as "天猫平台"
Client->>API : GET /recharge/tMallGame/account/auth/getAuthorizeKey
API-->>Client : 返回授权码和回调地址
Client->>Tmall : 使用授权码访问天猫
Tmall-->>Client : 授权成功,重定向到回调地址
Client->>API : POST /recharge/tMallGame/account/auth/callback
API->>API : 验证渠道和授权码
API->>Tmall : 调用天猫OAuth2登录
Tmall-->>API : 返回授权结果
API-->>Client : 返回授权结果
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L60-L70)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
**章节来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
### 订单处理分析
订单处理组件管理天猫游戏订单的整个生命周期从提交到完成
#### 订单提交
```mermaid
flowchart TD
Start([提交订单]) --> Validate["验证订单参数"]
Validate --> Account{"账户可用?"}
Account --> |否| ReturnError["返回错误"]
Account --> |是| Create["创建订单记录"]
Create --> SetStatus["设置订单状态为创建"]
SetStatus --> ReturnSuccess["返回订单号"]
style Start fill:#4CAF50,stroke:#333
style ReturnSuccess fill:#4CAF50,stroke:#333
style ReturnError fill:#F44336,stroke:#333
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go#L40-L55)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L35-L45)
#### 订单状态查询
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API服务"
participant DB as "数据库"
Client->>API : GET /recharge/tMallGame/order/list
API->>DB : 查询订单列表
DB-->>API : 返回订单数据
API->>API : 关联账户和店铺信息
API-->>Client : 返回订单列表
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go#L20-L35)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L50-L60)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
### 店铺管理分析
店铺管理组件处理天猫店铺订单的同步和查询
#### 店铺订单同步
```mermaid
flowchart TD
Start([获取店铺订单]) --> Query["查询店铺订单"]
Query --> Exists{"订单存在?"}
Exists --> |否| Create["创建店铺订单记录"]
Exists --> |是| Update["更新订单状态"]
Update --> Sync["同步到本地订单"]
Sync --> Return["返回订单信息"]
style Start fill:#4CAF50,stroke:#333
style Return fill:#4CAF50,stroke:#333
```
**图示来源**
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go#L10-L25)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L70-L80)
**章节来源**
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
## 依赖分析
天猫卡密管理API的组件间存在清晰的依赖关系API接口层依赖于服务层提供的接口服务层依赖于数据访问层各组件通过定义良好的接口进行交互降低了耦合度
```mermaid
classDiagram
class AccountAPI {
+createAccount()
+listAccounts()
+toggleAccount()
+deleteAccount()
}
class OrderAPI {
+submitOrder()
+listOrders()
+modifyOrderStatus()
}
class ShopAPI {
+getShopOrderList()
+getShopOrder()
+getShopHistory()
}
class CallbackAPI {
+agisoCallback()
+authorizeCallback()
+manualCallback()
}
class WorkspaceAPI {
+getOrderSummary()
+getStats()
}
class AccountService {
+Add()
+List()
+Toggle()
+Delete()
}
class OrderService {
+Create()
+List()
+ShopList()
+GetOrderStats()
}
AccountAPI --> AccountService : "使用"
OrderAPI --> OrderService : "使用"
ShopAPI --> OrderService : "使用"
CallbackAPI --> OrderService : "使用"
WorkspaceAPI --> OrderService : "使用"
```
**图示来源**
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
**章节来源**
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
## 性能考虑
天猫卡密管理API在设计时考虑了性能优化通过使用缓存减少数据库查询采用批量操作提高效率实施限流防止系统过载对于高频访问的统计接口建议使用缓存策略订单提交和状态更新操作应使用数据库事务确保数据一致性
## 故障排除指南
### 常见问题
1. **授权失败**检查授权码是否正确回调地址是否匹配网络连接是否正常
2. **订单提交失败**验证账户状态是否正常订单金额是否符合要求签名是否正确
3. **回调接收失败**确认回调URL是否可访问防火墙设置是否允许外部请求
### 错误处理
系统使用统一的错误处理机制所有错误都通过`errHandler`包进行包装和处理错误码遵循标准规范便于客户端识别和处理
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
## 结论
天猫卡密管理API提供了一套完整的解决方案用于管理天猫游戏账户和订单通过清晰的接口设计和分层架构系统实现了高可用性和可维护性文档详细介绍了各个组件的功能和使用方法为开发者提供了全面的参考

View File

@@ -0,0 +1,326 @@
# 天猫卡密订单处理
<cite>
**本文档引用的文件**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
- [v_1_recharge_t_mall_order.go](file://internal/model/entity/v_1_recharge_t_mall_order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
- [v_1_recharge_t_mall_shop.go](file://internal/model/entity/v_1_recharge_t_mall_shop.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_info_t_mall_game_v1_call_back_order_manual.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_call_back_order_manual.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录)如有必要
## 简介
本文档详细介绍了天猫卡密订单处理API的设计与实现涵盖订单提交状态查询历史记录等核心功能系统通过与天猫平台的深度集成实现了卡密订单的自动化处理流程包括订单创建状态同步回调处理等关键环节文档重点阐述了订单状态机幂等性处理安全认证等核心机制为开发者提供了完整的实现指南和最佳实践
## 项目结构
天猫卡密订单处理系统采用分层架构设计主要包含API接口层业务逻辑层数据访问层和常量定义层系统通过模块化设计将不同功能分离确保代码的可维护性和扩展性
```mermaid
graph TD
subgraph "API层"
A[order.go]
B[shop.go]
end
subgraph "控制器层"
C[card_info_t_mall_game_v1_t_mall_game_order_submit.go]
D[card_info_t_mall_game_v1_t_mall_game_agiso_callback.go]
E[card_info_t_mall_game_v1_call_back_order_manual.go]
end
subgraph "服务层"
F[card_t_mall_order.go]
end
subgraph "逻辑层"
G[order.go]
end
subgraph "数据访问层"
H[v_1_recharge_t_mall_order.go]
I[v_1_recharge_t_mall_shop.go]
end
subgraph "常量层"
J[card_recharge_t_mall.go]
end
A --> C
B --> C
C --> F
D --> F
E --> F
F --> G
G --> H
G --> I
J --> F
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
- [v_1_recharge_t_mall_shop.go](file://internal/model/entity/v_1_recharge_t_mall_shop.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [shop.go](file://api/card_info_t_mall_game/v1/shop.go)
## 核心组件
天猫卡密订单处理系统的核心组件包括订单管理状态机处理回调机制和数据同步四大模块订单管理模块负责订单的创建查询和更新状态机处理模块维护订单的生命周期状态回调机制实现与第三方系统的通信数据同步模块确保本地数据与天猫平台数据的一致性
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
## 架构概述
系统采用典型的分层架构从上至下分为API接口层控制器层服务层逻辑层和数据访问层API接口层定义了外部可访问的RESTful端点控制器层处理HTTP请求并调用相应的服务服务层提供业务逻辑的抽象接口逻辑层实现具体的业务规则数据访问层负责与数据库交互
```mermaid
graph TB
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> Logic[逻辑层]
Logic --> DAO[数据访问层]
DAO --> DB[(数据库)]
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style Logic fill:#96f,stroke:#333
style DAO fill:#69f,stroke:#333
style DB fill:#9f6,stroke:#333
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
## 详细组件分析
### 订单提交组件分析
订单提交组件负责处理客户端的订单创建请求验证输入参数创建订单记录并返回订单号该组件实现了幂等性处理确保重复提交不会创建多个订单
#### 订单提交序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "逻辑层"
participant DAO as "数据访问层"
participant DB as "数据库"
Client->>API : POST /recharge/tMallGame/order/submit
API->>Controller : 转发请求
Controller->>Controller : 验证账号可用性
Controller->>Service : 调用Create方法
Service->>Logic : 创建订单
Logic->>DAO : 生成订单号
DAO->>DB : 插入订单记录
DB-->>DAO : 返回结果
DAO-->>Logic : 确认创建
Logic-->>Service : 返回订单号
Service-->>Controller : 返回结果
Controller-->>API : 构造响应
API-->>Client : 返回订单号和状态
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
### 订单状态机分析
订单状态机组件管理订单的整个生命周期从创建到完成的各种状态转换系统定义了丰富的状态类型确保订单处理过程的可追踪性和可靠性
#### 订单状态机图
```mermaid
stateDiagram-v2
[*] --> created
created --> callback : 收到回调
callback --> delivery_failed : 虚拟发货失败
callback --> delivery_succeed : 虚拟发货成功
delivery_succeed --> paid : 已付款
paid --> bind_shop_succeed : 关联淘宝订单成功
bind_shop_succeed --> wait_for_evaluation : 等待用户评价
wait_for_evaluation --> evaluation : 买家评价
evaluation --> callback_succeed : 回调成功
evaluation --> callback_failed : 回调失败
callback_succeed --> finished : 订单结束
callback_succeed --> finished_with_wrong_amount : 金额错误
callback_succeed --> finished_with_wrong_status : 状态错误
callback_succeed --> finished_with_refund_succeed : 退款成功
callback_failed --> refund_failed : 退款失败
delivery_failed --> without_fill_account : 未填写账号
note right of created
订单创建状态
等待处理
end note
note right of delivery_succeed
虚拟商品已发货
等待买家确认
end note
note right of wait_for_evaluation
买家已确认收货
等待评价
end note
note right of finished
订单正常完成
所有流程结束
end note
```
**图示来源**
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
**章节来源**
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
### 回调处理组件分析
回调处理组件负责接收来自天猫平台的异步通知解析回调数据更新订单状态并触发后续业务流程该组件实现了多种回调类型的处理包括支付成功确认收货和用户评价
#### 回调处理流程图
```mermaid
flowchart TD
Start([收到回调请求]) --> ParseData["解析回调数据"]
ParseData --> CheckExist["检查订单是否存在"]
CheckExist --> OrderExists{"订单存在?"}
OrderExists --> |否| CreateOrder["创建新订单"]
OrderExists --> |是| UpdateStatus["更新订单状态"]
CreateOrder --> ProcessPayment["处理支付逻辑"]
UpdateStatus --> ProcessPayment
ProcessPayment --> VirtualDelivery["尝试虚拟发货"]
VirtualDelivery --> DeliverySuccess{"发货成功?"}
DeliverySuccess --> |否| RecordFailure["记录失败状态"]
DeliverySuccess --> |是| RecordSuccess["记录成功状态"]
RecordFailure --> End([结束])
RecordSuccess --> BindOrder["关联淘宝订单"]
BindOrder --> WaitForEvaluation["等待用户评价"]
WaitForEvaluation --> ReceiveEvaluation["收到评价回调"]
ReceiveEvaluation --> CheckEvaluation{"好评?"}
CheckEvaluation --> |是| GiveGoodReview["给予买家好评"]
CheckEvaluation --> |否| RecordBadReview["记录差评"]
GiveGoodReview --> CallbackUpstream["回调上游系统"]
RecordBadReview --> CallbackUpstream
CallbackUpstream --> End
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
## 依赖分析
系统各组件之间的依赖关系清晰明确遵循依赖倒置原则高层模块依赖于抽象接口而非具体实现提高了系统的可测试性和可维护性
```mermaid
classDiagram
class OrderAPI {
+POST /submit
+GET /list
+GET /query
}
class OrderController {
+TMallGameOrderSubmit()
+TMallGameOrderList()
+TMallGameOrderQueryOrder()
}
class OrderService {
+Create()
+List()
+GetById()
+UpdateStatus()
}
class OrderLogic {
+Create()
+List()
+GetById()
+UpdateStatus()
}
class OrderDAO {
+Insert()
+Select()
+Update()
+Delete()
}
class OrderEntity {
+OrderNo
+AccountNumber
+Amount
+Status
+CreatedAt
}
OrderAPI --> OrderController : "调用"
OrderController --> OrderService : "依赖"
OrderService --> OrderLogic : "实现"
OrderLogic --> OrderDAO : "调用"
OrderDAO --> OrderEntity : "映射"
OrderEntity --> DB : "持久化"
class Consts {
+OrderStatusCreated
+OrderStatusCallback
+OrderStatusDeliverySucceed
+OrderStatusFinished
}
OrderService --> Consts : "引用"
OrderLogic --> Consts : "引用"
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
- [v_1_recharge_t_mall_order.go](file://internal/model/entity/v_1_recharge_t_mall_order.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
**章节来源**
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
## 性能考虑
系统在设计时充分考虑了性能优化采用了多种技术手段确保高并发场景下的稳定运行包括数据库连接池缓存机制异步处理等订单查询接口支持分页和条件过滤避免全表扫描订单创建过程采用事务处理确保数据一致性
## 故障排除指南
### 常见问题及解决方案
1. **订单创建失败**检查账号状态是否启用确保账号信息正确无误
2. **回调处理超时**检查网络连接确保回调地址可访问适当增加超时时间
3. **状态同步延迟**检查定时任务是否正常运行确认数据同步频率设置合理
4. **虚拟发货失败**检查天猫API密钥有效性确认商品配置正确
**章节来源**
- [card_info_t_mall_game_v1_call_back_order_manual.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_call_back_order_manual.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
## 结论
天猫卡密订单处理系统通过清晰的架构设计和严谨的状态管理实现了高效可靠的订单处理能力系统具备良好的扩展性和可维护性能够满足不断变化的业务需求通过本文档的指导开发者可以快速理解系统架构进行二次开发和问题排查

View File

@@ -0,0 +1,226 @@
# 天猫卡密账户管理
<cite>
**本文档引用文件**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [account.go](file://internal/logic/card_t_mall_account/account.go)
- [oauth.go](file://utility/integration/tmall/api/oauth.go)
- [tmall.go](file://utility/integration/tmall/utils.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
- [v_1_recharge_t_mall_account.go](file://internal/model/entity/v_1_recharge_t_mall_account.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心接口说明](#核心接口说明)
3. [OAuth授权流程](#oauth授权流程)
4. [账户状态管理](#账户状态管理)
5. [实际使用示例](#实际使用示例)
6. [错误处理与安全考虑](#错误处理与安全考虑)
7. [客户端实现指南](#客户端实现指南)
8. [性能优化建议](#性能优化建议)
## 简介
本文档详细说明天猫卡密账户管理API的使用方法涵盖账户创建OAuth授权状态查询等核心功能系统通过天猫游戏平台对接实现卡密账户的自动化管理支持多渠道授权与订单回调机制
## 核心接口说明
### 账户创建接口
- **HTTP方法**: POST
- **URL模式**: `/recharge/tMallGame/account/create`
- **认证机制**: JWT Token
- **请求体**:
- `count`: 创建账户数量1-100
- **响应**:
- 成功返回空对象批量创建指定数量的随机邮箱账户
### 账户列表查询接口
- **HTTP方法**: GET
- **URL模式**: `/recharge/tMallGame/account/list`
- **参数**:
- `accountNumber`: 账户账号模糊匹配
- `current`: 当前页码
- `pageSize`: 每页数量
- **响应结构**:
- 分页数据包含账户ID账号余额状态创建时间等信息
### 授权回调接口
- **HTTP方法**: POST
- **URL模式**: `/recharge/tMallGame/account/auth/callback`
- **请求体**:
- `code`: 天猫回调授权码
- `channel`: 渠道标识12351:天猫12352:阿奇索
**Section sources**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L10-L71)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go#L18-L36)
## OAuth授权流程
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
participant 天猫平台
用户->>前端 : 发起授权请求
前端->>后端 : GET /recharge/tMallGame/account/auth/getAuthorizeKey
后端-->>前端 : 返回授权码和回调地址
前端->>天猫平台 : 重定向到天猫授权页面
天猫平台->>用户 : 用户登录并授权
天猫平台->>后端 : POST 回调接口携带授权码
后端->>后端 : 调用淘宝API换取access token
后端->>后端 : 缓存OAuth响应信息
后端-->>前端 : 授权完成通知
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go#L1-L30)
- [oauth.go](file://utility/integration/tmall/api/oauth.go#L13-L73)
### 授权状态检查
- **HTTP方法**: GET
- **URL模式**: `/recharge/tMallGame/account/auth/getTMallAuthStatus`
- **响应**:
- `status`: 授权状态true/false
- `expiredAt`: 过期时间
**Section sources**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L60-L71)
- [card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go#L1-L32)
## 账户状态管理
### 状态切换接口
- **HTTP方法**: POST
- **URL模式**: `/recharge/tMallGame/account/toggle`
- **请求体**:
- `id`: 账户ID
- **功能**: 在启用和禁用状态间切换
### 随机获取账户
- **HTTP方法**: GET
- **URL模式**: `/recharge/tMallGame/account/getOneByRandom`
- **参数**:
- `timeStamp`: 时间戳
- `orderNo`: 订单号
- **行为**: 若可用账户不足自动创建新账户
```mermaid
flowchart TD
Start([开始]) --> CheckCount["检查可用账户数量"]
CheckCount --> LowCount{"数量<10?"}
LowCount --> |是| CreateBatch["异步创建100个新账户"]
LowCount --> |否| GetRandom["随机获取一个启用状态账户"]
GetRandom --> HasAccount{"获取到账户?"}
HasAccount --> |是| ReturnAccount["返回账户信息"]
HasAccount --> |否| CreateOne["创建单个新账户"]
CreateOne --> ReturnNew["返回新账户"]
ReturnAccount --> End([结束])
ReturnNew --> End
```
**Diagram sources**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L45-L59)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L130-L180)
**Section sources**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L30-L44)
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L21)
## 实际使用示例
### 天猫游戏账户创建
1. 调用 `/recharge/tMallGame/account/create` 接口
2. 传入 `count=10` 创建10个新账户
3. 系统自动生成随机邮箱格式的账户名
### OAuth2.0授权流程
1. 前端获取授权key和回调地址
2. 重定向用户到天猫授权页面
3. 用户授权后天猫回调后端指定接口
4. 后端使用code换取access token并缓存
### 账户状态检测
定期调用 `/recharge/tMallGame/account/auth/getTMallAuthStatus` 接口检查授权有效性确保API调用的连续性
## 错误处理与安全考虑
### 常见错误码
- `CodeNotAuthorized (401)`: 授权失败access token无效
- `CodeInternalError (500)`: 服务器内部错误
- `CodeNotSupported (400)`: 不支持的渠道类型
### 安全措施
1. 所有敏感接口需JWT认证
2. OAuth回调需验证签名
3. access token缓存设置合理过期时间
4. 数据库操作使用事务保证一致性
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go#L1-L30)
- [errHandler](file://internal/errHandler/handler.go)
## 客户端实现指南
### 授权流程实现
1. 先调用获取授权key接口
2. 构造天猫授权URL
3. 处理回调发送code到后端
4. 定期检查授权状态
### API调用最佳实践
- 使用连接池管理HTTP客户端
- 实现重试机制最多5次
- 缓存access token状态
- 处理速率限制
## 性能优化建议
### 批量操作
- 账户创建建议批量进行减少数据库事务开销
- 查询接口合理使用分页避免大数据量加载
### 缓存策略
- OAuth token信息缓存有效期与token一致
- 频繁查询的账户状态可做短期缓存
### 异步处理
- 账户不足时的自动创建使用异步处理
- 避免阻塞主请求流程
```mermaid
graph TB
subgraph "API层"
A[账户创建]
B[状态查询]
C[授权回调]
end
subgraph "服务层"
D[账户服务]
E[授权服务]
end
subgraph "数据层"
F[MySQL数据库]
G[Redis缓存]
end
A --> D
B --> D
C --> E
D --> F
E --> G
E --> F
```
**Diagram sources**
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L50)
- [account.go](file://internal/logic/card_t_mall_account/account.go)
**Section sources**
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go#L1-L90)
- [v_1_recharge_t_mall_account.go](file://internal/model/entity/v_1_recharge_t_mall_account.go#L1-L21)

View File

@@ -0,0 +1,481 @@
# 沃尔玛卡密分组管理
<cite>
**本文档引用文件**
- [group.go](file://api/card_info_walmart/v1/group.go)
- [stats.go](file://api/card_info_walmart/v1/stats.go)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go)
- [card_info_walmart_v1_group_stat.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_stat.go)
- [card_info_walmart_v1_group_all_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_all_list.go)
- [card_info_walmart_v1_group_delete.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_delete.go)
- [card_info_walmart_v1_group_update.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_update.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心功能概述](#核心功能概述)
3. [分组管理API接口](#分组管理api接口)
4. [统计分析功能](#统计分析功能)
5. [客户端实现指南](#客户端实现指南)
6. [性能优化建议](#性能优化建议)
7. [错误处理与安全](#错误处理与安全)
8. [附录](#附录)
## 简介
本文档详细介绍了沃尔玛卡密分组管理系统的API接口涵盖分组创建列表查询统计分析等核心功能系统为沃尔玛卡密账户提供高效的分组管理能力支持大规模账户的组织查询和性能监控通过本系统用户可以对沃尔玛卡密账户进行分类管理实现精细化运营和数据分析
## 核心功能概述
沃尔玛卡密分组管理系统提供了一套完整的分组管理解决方案主要包括以下核心功能
- **分组创建与管理**支持创建更新删除账户分组实现账户的分类组织
- **分组列表查询**提供分页查询功能支持按用户ID分组名称等条件筛选
- **统计分析**提供分组级别的统计功能包括账户状态分布订单成功率等关键指标
- **数据导出**支持将分组数据导出为Excel格式便于离线分析
系统通过RESTful API提供服务采用标准的HTTP方法和状态码确保接口的易用性和一致性
## 分组管理API接口
### 分组创建接口
**HTTP方法**: POST
**URL模式**: `/cardInfo/walmart/group/add`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginOnlyLogin`验证
创建新的沃尔玛账户分组每个分组必须有唯一的名称系统会检查分组名称是否已存在避免重复创建
**请求参数**:
- `name` (string, 必填): 分组名称
- `notes` (string): 备注信息
**响应**:
- 成功: 返回空对象HTTP状态码200
- 失败: 返回错误信息HTTP状态码400参数错误或500内部错误
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : POST /cardInfo/walmart/group/add
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupAdd方法
服务层->>服务层 : 检查分组名称是否已存在
服务层->>数据库 : 插入新分组记录
数据库-->>服务层 : 返回插入结果
服务层-->>控制器 : 返回操作结果
控制器-->>客户端 : 返回响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L12-L20)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
### 分组更新接口
**HTTP方法**: PUT
**URL模式**: `/cardInfo/walmart/group/update`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginOnlyLogin`验证
更新现有分组的信息包括名称和备注系统会检查新名称是否与其他分组冲突
**请求参数**:
- `id` (int, 必填): 分组ID
- `name` (string, 必填): 新的分组名称
- `notes` (string): 新的备注信息
**响应**:
- 成功: 返回空对象HTTP状态码200
- 失败: 返回错误信息HTTP状态码400参数错误或500内部错误
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : PUT /cardInfo/walmart/group/update
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupUpdate方法
服务层->>服务层 : 检查新名称是否已存在
服务层->>数据库 : 更新分组记录
数据库-->>服务层 : 返回更新结果
服务层-->>控制器 : 返回操作结果
控制器-->>客户端 : 返回响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L22-L29)
- [card_info_walmart_v1_group_update.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_update.go)
### 分组列表查询接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/group/list`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginWithIFrameAndLogin`验证
查询分组列表支持分页按用户ID和分组名称筛选
**请求参数**:
- `page` (int): 页码从1开始
- `limit` (int): 每页数量
- `userId` (string): 用户ID
- `name` (string): 分组名称模糊匹配
**响应**:
- `total` (int): 总记录数
- `list` (array): 分组列表包含分组ID名称备注创建时间等信息
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : GET /cardInfo/walmart/group/list
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupList方法
服务层->>数据库 : 查询分组列表
数据库-->>服务层 : 返回查询结果
服务层-->>控制器 : 返回分组列表和总数
控制器-->>客户端 : 返回分页响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L31-L38)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go)
### 分组删除接口
**HTTP方法**: DELETE
**URL模式**: `/cardInfo/walmart/group/delete`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginOnlyLogin`验证
删除指定的分组删除操作会检查分组是否存在以及用户是否有权限删除
**请求参数**:
- `id` (int, 必填): 分组ID
**响应**:
- 成功: 返回空对象HTTP状态码200
- 失败: 返回错误信息HTTP状态码400参数错误或500内部错误
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : DELETE /cardInfo/walmart/group/delete
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupDelete方法
服务层->>数据库 : 删除分组记录
数据库-->>服务层 : 返回删除结果
服务层-->>控制器 : 返回操作结果
控制器-->>客户端 : 返回响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L40-L46)
- [card_info_walmart_v1_group_delete.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_delete.go)
### 所有分组查询接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/group/allList`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginWithIFrameAndLogin`验证
查询所有分组不进行分页返回完整的分组列表
**请求参数**:
- `userId` (string): 用户ID
**响应**:
- `total` (int): 总记录数
- `list` (array): 所有分组列表
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : GET /cardInfo/walmart/group/allList
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupAllList方法
服务层->>数据库 : 查询所有分组
数据库-->>服务层 : 返回查询结果
服务层-->>控制器 : 返回分组列表和总数
控制器-->>客户端 : 返回响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L48-L54)
- [card_info_walmart_v1_group_all_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_all_list.go)
## 统计分析功能
### 分组统计接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/group/stat`
**认证机制**: 需要有效的用户登录凭证通过中间件`LoginWithIFrameAndLogin`验证
获取分组的统计信息包括订单日期分组ID分组名称订单数量订单金额等
**请求参数**:
- `page` (int): 页码
- `limit` (int): 每页数量
- `name` (string): 分组名称
- `username` (string): 用户名
- `date` (datetime): 日期
- `userId` (string): 用户ID
**响应**:
- `total` (int): 总记录数
- `list` (array): 统计列表包含订单日期分组信息账户状态统计等
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : GET /cardInfo/walmart/group/stat
控制器->>控制器 : 验证用户登录状态
控制器->>服务层 : 调用GroupStat方法
服务层->>数据库 : 查询分组统计信息
数据库-->>服务层 : 返回统计结果
服务层-->>控制器 : 返回统计列表和总数
控制器-->>客户端 : 返回分页响应
```
**接口来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L56-L78)
- [card_info_walmart_v1_group_stat.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_stat.go)
### 统计概览接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/stats/overview`
**认证机制**: 无特殊认证要求
获取沃尔玛卡密的统计概览信息包括账户数量订单金额和订单数量等关键指标
**请求参数**:
- `groupId` (int64): 分组ID
- `dateRange` (array): 日期范围
- `accountId` (string): 账户ID
**响应**:
- `totalActiveAccountCount` (int): 活跃账户总数
- `totalAccountCount` (int): 账户总数
- `totalOrderAmount` (float): 订单总金额
- `totalOrderAmountSuccess` (float): 成功订单金额
- `totalOrderCount` (int): 订单总数
- `totalOrderCountSuccess` (int): 成功订单数
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : GET /cardInfo/walmart/stats/overview
控制器->>服务层 : 调用StatsOverview方法
服务层->>数据库 : 查询统计概览
数据库-->>服务层 : 返回概览数据
服务层-->>控制器 : 返回统计结果
控制器-->>客户端 : 返回响应
```
**接口来源**
- [stats.go](file://api/card_info_walmart/v1/stats.go#L6-L20)
- [card_info_walmart_v1_stats_overview.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_stats_overview.go)
### 统计数据导出接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/stats/overview/download`
**认证机制**: 无特殊认证要求
**响应类型**: application/xlsx
将统计概览数据导出为Excel文件
**请求参数**:
- `groupId` (int64): 分组ID
- `accountId` (string): 账户ID
**响应**:
- Excel文件流
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : GET /cardInfo/walmart/stats/overview/download
控制器->>服务层 : 调用StatsOverviewDownload方法
服务层->>数据库 : 查询统计数据
数据库-->>服务层 : 返回数据
服务层->>服务层 : 生成Excel文件
服务层-->>控制器 : 返回文件流
控制器-->>客户端 : 返回Excel文件
```
**接口来源**
- [stats.go](file://api/card_info_walmart/v1/stats.go#L22-L32)
- [card_info_walmart_v1_stats_overview_download.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_stats_overview_download.go)
## 客户端实现指南
### 认证流程
客户端在调用任何需要认证的API接口前必须先完成用户登录系统通过`LoginOnlyLogin``LoginWithIFrameAndLogin`中间件验证用户身份
**推荐实现**:
1. 用户登录获取会话凭证
2. 在后续请求的Header中携带认证信息
3. 处理401未授权响应引导用户重新登录
### 错误处理
系统使用标准的HTTP状态码和自定义错误码来表示不同的错误情况
**常见错误码**:
- `400`: 参数错误请求参数不符合验证规则
- `401`: 未授权用户未登录或会话过期
- `404`: 资源不存在
- `500`: 服务器内部错误
**建议的错误处理策略**:
- 捕获并解析错误响应
- 根据错误类型提供用户友好的提示
- 对于可恢复的错误如网络超时实现重试机制
### 分页策略
对于列表查询接口系统采用标准的分页模式
```json
{
"total": 100,
"list": [...],
"page": 1,
"limit": 20
}
```
**客户端实现建议**:
- 记录当前页码和每页数量
- 在用户翻页时更新请求参数
- 处理总记录数变化的情况
## 性能优化建议
### 大规模分组查询优化
当处理大量分组数据时建议采用以下优化策略
**分页查询**:
- 使用合理的分页大小建议20-50/
- 避免一次性查询所有数据
- 实现懒加载只在需要时加载数据
**查询条件优化**:
- 尽可能使用精确的查询条件缩小结果集
- 利用索引字段如用户ID分组名称进行筛选
- 避免在大数据集上进行模糊查询
### 统计计算性能优化
统计功能涉及大量数据聚合计算建议采取以下措施
**缓存策略**:
- 对频繁访问的统计结果进行缓存
- 设置合理的缓存过期时间
- 在数据更新时及时清除相关缓存
**异步计算**:
- 对于复杂的统计计算考虑使用异步任务
- 提供计算进度查询接口
- 计算完成后通过回调或消息通知客户端
**数据预聚合**:
- 定期预计算常用的统计指标
- 存储预聚合结果供快速查询
- 平衡实时性和性能需求
## 错误处理与安全
### 常见错误场景
**分组名称重复**:
- 错误码: 400
- 原因: 创建或更新分组时名称已存在
- 解决方案: 使用唯一的分组名称
**权限不足**:
- 错误码: 401
- 原因: 用户未登录或会话过期
- 解决方案: 重新登录获取有效凭证
**参数验证失败**:
- 错误码: 400
- 原因: 请求参数不符合验证规则
- 解决方案: 检查并修正请求参数
### 安全考虑
**认证安全**:
- 所有敏感操作都需要用户认证
- 会话凭证应安全存储和传输
- 实现会话过期机制
**数据安全**:
- 敏感数据如账户信息应加密存储
- API接口应进行输入验证防止SQL注入等攻击
- 限制单个用户的请求频率防止滥用
## 附录
### 数据模型
**分组实体 (V1CardRedeemAccountGroup)**:
- `id`: 分组ID
- `name`: 分组名称
- `notes`: 备注
- `category`: 分组类别
- `createdUserId`: 创建用户ID
- `createdAt`: 创建时间
- `updatedAt`: 更新时间
- `deletedAt`: 删除时间
**账户实体 (V1CardRedeemAccountInfo)**:
- `id`: 账户ID
- `groupId`: 所属分组ID
- `name`: 账户名称
- `username`: 用户名
- `status`: 状态1.正常 0.禁用
- `balance`: 余额
- `effectiveBalance`: 有效充值余额
**统计实体 (V1CardRedeemAccountGroupStatsEntity)**:
- `orderDate`: 订单日期
- `groupId`: 分组ID
- `groupName`: 分组名称
- `count`: 订单数量
- `sum`: 订单金额
- `createdUserId`: 创建用户ID
- `createdUserName`: 创建用户名
### 接口调用示例
**创建分组**:
```http
POST /cardInfo/walmart/group/add
Content-Type: application/json
{
"name": "沃尔玛账户分组1",
"notes": "测试分组"
}
```
**查询分组列表**:
```http
GET /cardInfo/walmart/group/list?page=1&limit=20&name=沃尔玛
```
**获取统计概览**:
```http
GET /cardInfo/walmart/stats/overview?groupId=1&dateRange[]=2024-01-01&dateRange[]=2024-01-31
```

View File

@@ -0,0 +1,400 @@
# 沃尔玛卡密管理API
<cite>
**本文档引用文件**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
- [group.go](file://api/card_info_walmart/v1/group.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
- [stats.go](file://api/card_info_walmart/v1/stats.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_account_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_list.go)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go)
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
沃尔玛卡密管理API提供了一套完整的接口用于管理沃尔玛礼品卡账户订单处理和分组管理该系统支持账户创建状态检测订单提交分组管理等功能专为高效处理沃尔玛卡密兑换而设计API具备批量验证状态重置分组统计等高级功能确保账户状态与沃尔玛平台保持同步并遵守平台的调用限制
## 项目结构
沃尔玛卡密管理模块位于`api/card_info_walmart`目录下采用分层架构设计该模块包含v1版本的API定义和对应的控制器实现分别位于`v1`子目录和`internal/controller/card_info_walmart`目录中数据模型定义在`internal/model/entity`目录下常量定义在`internal/consts`目录中
```mermaid
graph TD
subgraph "API接口层"
A[card_info_walmart.go]
B[account.go]
C[group.go]
D[order.go]
E[stats.go]
end
subgraph "控制器层"
F[card_info_walmart_v1_account_create.go]
G[card_info_walmart_v1_account_list.go]
H[card_info_walmart_v1_group_add.go]
I[card_info_walmart_v1_submit.go]
end
subgraph "模型层"
J[v_1_card_redeem_account_info.go]
K[v_1_card_redeem_order_info.go]
L[v_1_card_redeem_account_group.go]
end
subgraph "常量层"
M[card_redeem.go]
N[card_redeem_cookie.go]
end
A --> F
B --> G
C --> H
D --> I
J --> F
K --> I
M --> F
N --> F
```
**图示来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
**节来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [internal/controller/card_info_walmart](file://internal/controller/card_info_walmart)
## 核心组件
沃尔玛卡密管理API的核心组件包括账户管理分组管理订单处理和统计分析四大模块账户管理模块负责沃尔玛账户的创建更新删除和状态检测分组管理模块提供账户分组的增删改查和统计功能订单处理模块处理卡密兑换请求和订单状态管理统计分析模块提供账户和订单的汇总数据
**节来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
- [group.go](file://api/card_info_walmart/v1/group.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
## 架构概览
沃尔玛卡密管理API采用典型的三层架构API接口层业务逻辑层和数据访问层API接口层定义了所有对外暴露的HTTP端点业务逻辑层控制器处理具体的业务逻辑数据访问层通过实体模型与数据库交互系统通过常量文件定义了各种状态码和枚举值确保代码的一致性和可维护性
```mermaid
graph TB
subgraph "表现层"
API[API接口]
end
subgraph "业务逻辑层"
Controller[控制器]
end
subgraph "数据层"
Service[服务]
Model[数据模型]
Const[常量]
end
API --> Controller
Controller --> Service
Service --> Model
Service --> Const
```
**图示来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
## 详细组件分析
### 账户管理分析
账户管理组件提供了完整的沃尔玛账户生命周期管理功能包括创建更新删除状态检测和批量操作
#### 账户创建与更新
```mermaid
classDiagram
class AccountRecord {
+string Cookie
+string Name
+int GroupId
+int MaxAmountLimit
+int MaxCountLimit
+int Status
+string Remark
}
class AccountCreateReq {
+AccountRecord
}
class AccountUpdateReq {
+string Id
+AccountRecord
}
class AccountListRecord {
+V1CardRedeemAccountInfo
+UploadUser
}
AccountCreateReq --> AccountRecord : "包含"
AccountUpdateReq --> AccountRecord : "包含"
AccountListRecord --> V1CardRedeemAccountInfo : "扩展"
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
#### 账户状态检测流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Walmart as "沃尔玛平台"
Client->>API : GET /cardInfo/walmart/account/statusDetect?id=xxx
API->>Controller : 调用AccountStatusDetect
Controller->>Service : 查询账户信息
Service->>Walmart : 验证Cookie有效性
Walmart-->>Service : 返回账户状态
Service-->>Controller : 返回检测结果
Controller-->>API : 返回响应
API-->>Client : {status : true/false}
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_status_detect.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_status_detect.go)
#### 批量账户验证流程
```mermaid
flowchart TD
Start([开始]) --> Upload["上传Excel文件"]
Upload --> Validate["验证文件格式"]
Validate --> Process["逐行处理账户"]
Process --> CheckCookie["调用沃尔玛API验证Cookie"]
CheckCookie --> IsValid{"Cookie有效?"}
IsValid --> |是| Success["标记为可用"]
IsValid --> |否| Fail["标记为不可用"]
Success --> Next
Fail --> Next
Next["处理下一个账户"] --> Process
Process --> EndLoop{"所有账户处理完毕?"}
EndLoop --> |否| Process
EndLoop --> |是| Generate["生成验证结果"]
Generate --> Return["返回验证结果列表"]
Return --> End([结束])
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_cookie_batch_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_check.go)
**节来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_account_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_list.go)
### 分组管理分析
分组管理组件提供了对沃尔玛账户的分组管理功能支持分组的创建更新删除和统计分析
#### 分组管理类图
```mermaid
classDiagram
class GroupRecord {
+string Name
+string Notes
}
class GroupAddReq {
+GroupRecord
}
class GroupUpdateReq {
+int Id
+GroupRecord
}
class V1CardRedeemAccountGroup {
+int Id
+string Name
+string Notes
+string Category
+string CreatedUserId
+datetime CreatedAt
+datetime UpdatedAt
+datetime DeletedAt
}
GroupAddReq --> GroupRecord : "包含"
GroupUpdateReq --> GroupRecord : "包含"
V1CardRedeemAccountGroup --> GroupRecord : "扩展"
```
**图示来源**
- [group.go](file://api/card_info_walmart/v1/group.go)
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go)
#### 分组统计功能
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DB as "数据库"
Client->>API : GET /cardInfo/walmart/group/stat?date=2023-01-01
API->>Controller : 调用GroupStat
Controller->>Service : 获取分组统计输入
Service->>DB : 查询分组统计数据
DB-->>Service : 返回统计结果
Service-->>Controller : 处理账户状态统计
Controller-->>API : 返回分组统计
API-->>Client : 返回分组统计结果
```
**图示来源**
- [group.go](file://api/card_info_walmart/v1/group.go)
- [card_info_walmart_v1_group_stat.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_stat.go)
**节来源**
- [group.go](file://api/card_info_walmart/v1/group.go)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
- [card_info_walmart_v1_group_stat.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_stat.go)
### 订单处理分析
订单处理组件负责沃尔玛卡密的兑换流程包括订单提交状态查询和回调处理
#### 订单提交流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Walmart as "沃尔玛平台"
Client->>API : POST /cardInfo/walmart/order/submit
API->>Controller : 调用Submit
Controller->>Service : 验证订单参数
Service->>Service : 分配可用账户
Service->>Walmart : 提交卡密兑换
Walmart-->>Service : 返回兑换结果
Service-->>Controller : 处理订单状态
Controller-->>API : 返回响应
API-->>Client : 返回订单结果
```
**图示来源**
- [order.go](file://api/card_info_walmart/v1/order.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
#### 订单状态重置
```mermaid
flowchart TD
Start([开始]) --> GetOrder["获取订单信息"]
GetOrder --> CheckStatus{"订单状态?"}
CheckStatus --> |失败| Reset["重置订单状态"]
CheckStatus --> |成功| End1([结束])
CheckStatus --> |处理中| CheckTimeout{"超时?"}
CheckTimeout --> |是| Reset
CheckTimeout --> |否| End2([结束])
Reset --> UpdateDB["更新数据库状态"]
UpdateDB --> Notify["通知相关系统"]
Notify --> End([结束])
```
**图示来源**
- [order.go](file://api/card_info_walmart/v1/order.go)
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go)
**节来源**
- [order.go](file://api/card_info_walmart/v1/order.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go)
### 统计分析组件
统计分析组件提供沃尔玛卡密系统的整体运营数据帮助管理员了解系统运行状况
#### 统计概览接口
```mermaid
classDiagram
class StatsOverviewReq {
+int64 GroupId
+datetime[] DateRange
+string AccountId
}
class StatsOverviewRes {
+int TotalActiveAccountCount
+int TotalAccountCount
+float TotalOrderAmount
+float TotalOrderAmountSuccess
+int TotalOrderCount
+int TotalOrderCountSuccess
}
class StatsOverviewDownloadReq {
+int64 GroupId
+string AccountId
}
StatsOverviewReq --> StatsOverviewDownloadReq : "继承"
```
**图示来源**
- [stats.go](file://api/card_info_walmart/v1/stats.go)
**节来源**
- [stats.go](file://api/card_info_walmart/v1/stats.go)
- [card_info_walmart_v1_stats_overview.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_stats_overview.go)
## 依赖分析
沃尔玛卡密管理API的依赖关系清晰各组件之间耦合度低便于维护和扩展
```mermaid
graph TD
API[API接口] --> Controller[控制器]
Controller --> Service[服务层]
Service --> Model[数据模型]
Service --> Const[常量]
Model --> DB[(数据库)]
Const --> Controller
Const --> Service
style API fill:#f9f,stroke:#333
style Controller fill:#bbf,stroke:#333
style Service fill:#f96,stroke:#333
style Model fill:#6f9,stroke:#333
style Const fill:#69f,stroke:#333
style DB fill:#9f9,stroke:#333
```
**图示来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [internal/controller/card_info_walmart](file://internal/controller/card_info_walmart)
- [internal/model/entity](file://internal/model/entity)
- [internal/consts](file://internal/consts)
**节来源**
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [internal/consts/card_redeem.go](file://internal/consts/card_redeem.go)
- [internal/model/entity/v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
## 性能考虑
沃尔玛卡密管理API在设计时充分考虑了性能因素批量操作采用流式处理避免内存溢出数据库查询使用索引优化提高查询效率状态检测采用缓存机制减少对沃尔玛平台的频繁调用系统还实现了限流机制防止对沃尔玛API的过度调用
## 故障排除指南
当遇到问题时可按照以下步骤进行排查
1. 检查账户Cookie是否有效可通过状态检测接口验证
2. 确认账户状态是否正常禁用的账户无法处理订单
3. 检查分组配置是否正确确保账户分配到正确的分组
4. 查看订单历史分析失败订单的具体原因
5. 检查系统日志获取详细的错误信息
**节来源**
- [card_info_walmart_v1_account_status_detect.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_status_detect.go)
- [card_info_walmart_v1_order_history.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_history.go)
## 结论
沃尔玛卡密管理API提供了一套完整高效的解决方案用于管理沃尔玛礼品卡的兑换流程系统设计合理功能完善具备良好的可扩展性和可维护性通过合理的账户管理分组策略和状态同步机制确保了系统的稳定运行和高效处理能力

View File

@@ -0,0 +1,249 @@
# 沃尔玛卡密订单处理
<cite>
**本文档引用的文件**
- [order.go](file://api/card_info_walmart/v1/order.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_info_walmart_v1_order_callback.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_callback.go)
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go)
- [order.go](file://internal/logic/card_redeem_order/order.go)
- [callback.go](file://internal/logic/card_redeem_order/callback.go)
- [status.go](file://internal/logic/card_redeem_order/status.go)
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心接口说明](#核心接口说明)
3. [订单状态机与处理流程](#订单状态机与处理流程)
4. [回调处理机制](#回调处理机制)
5. [状态重置安全限制](#状态重置安全限制)
6. [客户端实现指南](#客户端实现指南)
7. [性能优化与限流策略](#性能优化与限流策略)
8. [异常恢复场景](#异常恢复场景)
9. [安全验证机制](#安全验证机制)
10. [总结](#总结)
## 简介
本文档详细说明沃尔玛卡密订单处理系统的API接口涵盖订单提交第三方回调处理和订单状态重置等核心功能系统采用微服务架构通过RESTful API提供服务支持高并发订单处理和安全回调验证文档重点阐述沃尔玛卡密订单特有的处理流程包括订单状态转换规则回调验证机制和状态重置的安全限制为开发者提供完整的集成指南
## 核心接口说明
### 订单提交接口
**HTTP方法**: POST
**URL模式**: `/cardInfo/walmart/order/submit`
**认证机制**: JWT令牌认证
**请求参数**:
- `cardNo`: 卡号 (字符串)
- `giftCardPwd`: 礼品卡密码 (字符串, 必填)
- `notifyUrl`: 回调地址 (字符串, 必填)
- `merchantId`: 商户ID (字符串, 必填)
- `attach`: 附加信息 (字符串)
- `amount`: 充值金额 (浮点数, 必填)
**响应模式**: 空响应体HTTP状态码表示操作结果
**功能说明**: 接收沃尔玛卡密充值请求创建待处理订单并触发核销流程订单创建后立即返回实际处理在后台异步执行
**Section sources**
- [order.go](file://api/card_info_walmart/v1/order.go#L6-L28)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L1-L32)
### 订单回调接口
**HTTP方法**: GET
**URL模式**: `/cardInfo/walmart/order/callback`
**认证机制**: JWT令牌认证
**请求参数**:
- `orderNo`: 订单ID (字符串, 必填)
**响应模式**: 空响应体HTTP状态码表示操作结果
**功能说明**: 手动触发对第三方商户的回调操作仅当订单处于成功或失败状态且未回调时可执行
**Section sources**
- [order.go](file://api/card_info_walmart/v1/order.go#L58-L67)
- [card_info_walmart_v1_order_callback.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_callback.go#L1-L52)
### 订单状态重置接口
**HTTP方法**: PUT
**URL模式**: `/cardInfo/walmart/order/statusReset`
**认证机制**: JWT令牌认证
**请求参数**:
- `id`: 订单ID (字符串, 必填)
**响应模式**: 空响应体HTTP状态码表示操作结果
**功能说明**: 重置订单状态仅允许将状态为"最大限制"的订单重置为待处理状态确保系统安全
**Section sources**
- [order.go](file://api/card_info_walmart/v1/order.go#L69-L77)
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go#L1-L29)
## 订单状态机与处理流程
```mermaid
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中 : 开始处理
处理中 --> 充值成功 : 验证通过
处理中 --> 充值失败 : 验证失败
处理中 --> 账号失效 : 账号问题
处理中 --> 卡密类型错误 : 类型不匹配
处理中 --> 卡片过期 : 过期验证
充值成功 --> 回调成功 : 成功回调
充值失败 --> 回调失败 : 失败回调
回调成功 --> [*]
回调失败 --> [*]
充值成功 --> 订单禁用 : 最大调用次数
订单禁用 --> 待处理 : 手动重置
```
**Diagram sources**
- [card_redeem.go](file://internal/consts/card_redeem.go#L100-L200)
- [status.go](file://internal/logic/card_redeem_order/status.go#L12-L49)
**Section sources**
- [card_redeem.go](file://internal/consts/card_redeem.go#L100-L252)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go#L1-L34)
## 回调处理机制
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 第三方商户
客户端->>控制器 : GET /callback?orderNo=123
控制器->>服务层 : 验证用户权限
服务层-->>控制器 : 权限验证结果
控制器->>服务层 : 查询订单状态
服务层-->>控制器 : 订单信息
控制器->>服务层 : 验证订单状态
服务层-->>控制器 : 状态验证结果
控制器->>服务层 : 触发回调流程
服务层->>服务层 : 生成签名参数
服务层->>第三方商户 : POST notifyUrl
第三方商户-->>服务层 : 响应结果
服务层->>服务层 : 更新回调状态
服务层-->>控制器 : 回调结果
控制器-->>客户端 : HTTP响应
```
**Diagram sources**
- [card_info_walmart_v1_order_callback.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_callback.go#L1-L52)
- [callback.go](file://internal/logic/card_redeem_order/callback.go#L27-L121)
**Section sources**
- [card_info_walmart_v1_order_callback.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_callback.go#L1-L52)
- [callback.go](file://internal/logic/card_redeem_order/callback.go#L27-L150)
## 状态重置安全限制
```mermaid
flowchart TD
开始[状态重置请求] --> 验证[验证订单存在]
验证 --> 查询[查询订单实体]
查询 --> 检查状态[检查当前状态]
检查状态 --> 是否为最大限制{状态是否为<br/>最大限制?}
是否为最大限制 --> |是| 重置状态[重置为待处理]
是否为最大限制 --> |否| 返回错误[返回操作失败]
重置状态 --> 重置原始状态[重置订单原本状态]
重置原始状态 --> 重置回调次数[重置回调次数为0]
重置回调次数 --> 结束[操作成功]
返回错误 --> 结束
```
**Diagram sources**
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go#L1-L29)
- [status.go](file://internal/logic/card_redeem_order/status.go#L12-L49)
**Section sources**
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go#L1-L29)
- [status.go](file://internal/logic/card_redeem_order/status.go#L12-L73)
## 客户端实现指南
### 订单提交流程
1. 准备请求参数确保包含必填字段
2. 使用JWT令牌进行身份认证
3. 发送POST请求到提交接口
4. 处理响应记录订单号用于后续查询
### 第三方回调处理
1. 在商户系统中配置notifyUrl
2. 实现回调接收端点验证签名
3. 根据回调参数更新本地订单状态
4. 返回"success"确认接收
### 错误处理建议
- 对于重复订单错误使用唯一订单号避免重复提交
- 对于账号频繁错误实现指数退避重试策略
- 对于验证失败错误检查卡密格式和有效性
**Section sources**
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L1-L32)
- [callback.go](file://internal/logic/card_redeem_order/callback.go#L122-L150)
## 性能优化与限流策略
```mermaid
flowchart LR
客户端 --> |高并发请求| 限流器
限流器 --> |令牌桶算法| 核销触发器
核销触发器 --> |异步处理| 工作池
工作池 --> |并发消费| 账号分配
账号分配 --> |预扣款| 第三方接口
第三方接口 --> |绑定卡密| 响应处理
响应处理 --> |更新状态| 数据库
数据库 --> |回调通知| 商户系统
```
**Diagram sources**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L244-L357)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go#L1-L80)
**Section sources**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L1-L357)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go#L1-L80)
## 异常恢复场景
### 订单状态异常恢复
当订单因系统故障处于异常状态时可通过状态重置接口恢复处理仅允许重置状态为"订单禁用,最大调用次数"的订单确保不会影响正常处理流程
### 回调失败恢复
系统自动重试回调3次每次间隔递增若全部失败可通过手动回调接口重新触发商户应确保回调端点的高可用性避免丢失通知
### 数据一致性保障
使用数据库事务确保状态变更的原子性在账号分配和预扣款操作中使用事务锁防止并发问题导致的数据不一致
**Section sources**
- [card_info_walmart_v1_order_status_reset.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_status_reset.go#L1-L29)
- [callback.go](file://internal/logic/card_redeem_order/callback.go#L27-L121)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L1-L357)
## 安全验证机制
### 回调签名验证
回调请求包含时间戳和签名参数商户需使用共享密钥验证签名有效性防止伪造请求
### 权限控制
所有接口均需JWT令牌认证确保只有授权用户可访问回调接口额外验证订单归属防止越权操作
### 配置安全
通过系统配置字典控制关键策略如金额异议回调补卡自动回调等提供灵活的安全策略管理
**Section sources**
- [callback.go](file://internal/logic/card_redeem_order/callback.go#L122-L150)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go#L1-L81)
## 总结
沃尔玛卡密订单处理系统提供了完整的订单生命周期管理功能从提交处理到回调和状态重置系统设计注重安全性可靠性和性能通过状态机管理订单流转使用异步处理提高吞吐量并提供灵活的配置选项满足不同商户需求开发者应遵循本文档的实现指南确保正确集成和使用API接口

View File

@@ -0,0 +1,238 @@
# 沃尔玛卡密账户管理
<cite>
**本文档引用文件**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_account_cookie_batch_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_add.go)
- [card_info_walmart_v1_account_cookie_batch_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_check.go)
- [card_info_walmart_v1_account_update.go](file://internal/controller/card_info_walmart/card_info_wallet_v1_account_update.go)
- [card_info_walmart_v1_account_update_status.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_update_status.go)
- [card_info_walmart_v1_account_cookie_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_check.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了沃尔玛卡密账户管理API的功能涵盖账户创建Cookie批量验证状态检测信息更新等关键接口文档详细描述了各端点的HTTP方法URL模式请求/响应结构和认证机制并提供实际使用示例同时解释了沃尔玛卡密特有的账户状态检测机制异常处理流程和负载均衡策略为客户端实现和性能优化提供指导
## 项目结构
沃尔玛卡密账户管理功能主要分布在`api/card_info_walmart/v1/``internal/controller/card_info_walmart/`目录下通过分层架构实现接口定义与业务逻辑分离
```mermaid
graph TB
subgraph "API层"
A[account.go]
B[config.go]
C[group.go]
D[order.go]
end
subgraph "控制器层"
E[card_info_walmart_v1_account_create.go]
F[card_info_walmart_v1_account_cookie_batch_add.go]
G[card_info_walmart_v1_account_cookie_batch_check.go]
H[card_info_walmart_v1_account_update.go]
end
subgraph "服务层"
I[card_redeem_account.go]
end
subgraph "常量定义"
J[card_redeem.go]
end
subgraph "数据模型"
K[v_1_card_redeem_account_info.go]
end
A --> E
A --> F
A --> G
A --> H
E --> I
F --> I
G --> I
H --> I
I --> K
J --> I
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
**本节来源**
- [api/card_info_walmart/v1/account.go](file://api/card_info_walmart/v1/account.go)
- [internal/controller/card_info_walmart/](file://internal/controller/card_info_walmart/)
## 核心组件
沃尔玛卡密账户管理的核心组件包括账户管理API批量操作控制器状态检测服务和账户实体模型系统通过`CardRedeemAccount`服务统一管理账户的增删改查状态更新和余额操作确保数据一致性和业务逻辑的集中管理
**本节来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 架构概览
系统采用典型的分层架构从API接口到服务层再到数据模型各层职责分明API层定义了所有外部可访问的端点控制器层处理具体业务逻辑服务层提供可复用的业务功能数据模型层定义了持久化结构
```mermaid
graph TD
Client[客户端] --> API[API接口层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Model[数据模型层]
Service --> Database[(数据库)]
API -.->|请求/响应| Controller
Controller -.->|业务逻辑调用| Service
Service -.->|数据操作| Model
Model -.->|CRUD操作| Database
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 详细组件分析
### 账户创建与更新分析
账户创建和更新功能通过统一的流程处理包括权限验证Cookie有效性检查余额查询和数据库持久化创建时会验证管理员设置的最大充值次数限制确保系统安全
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant ClientInt as "第三方客户端"
Client->>API : POST /cardInfo/walmart/account/create
API->>Controller : 转发请求
Controller->>Service : LoginOnlyLogin()
Service-->>Controller : 用户信息
Controller->>ClientInt : GetClient(walmart)
ClientInt-->>Controller : 客户端实例
Controller->>ClientInt : QueryUserInfoWithCache()
ClientInt-->>Controller : 用户信息
Controller->>Service : GetNormalOneByCk()
Service-->>Controller : 账户存在检查
Controller->>ClientInt : QueryBalanceWithCache()
ClientInt-->>Controller : 余额信息
Controller->>Service : Add() 创建账户
Service-->>Controller : 成功
Controller-->>Client : 返回结果
```
**图示来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
**本节来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_account_update.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_update.go)
### 批量操作分析
批量操作支持Cookie的批量验证和添加通过Excel文件上传实现高效的数据导入系统采用并发处理机制提高批量操作的执行效率
```mermaid
flowchart TD
Start([开始]) --> Upload["上传Excel文件"]
Upload --> Validate["验证文件完整性"]
Validate --> Read["读取文件数据"]
Read --> Process["并发处理每行数据"]
Process --> CheckExist["检查账户是否已存在"]
CheckExist --> ValidateLimit["验证充值次数限制"]
ValidateLimit --> QueryInfo["查询用户信息和余额"]
QueryInfo --> Collect["收集验证结果"]
Collect --> End["返回批量验证结果"]
```
**图示来源**
- [card_info_walmart_v1_account_cookie_batch_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_check.go)
- [card_info_walmart_v1_account_cookie_batch_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_add.go)
**本节来源**
- [card_info_walmart_v1_account_cookie_batch_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_check.go)
- [card_info_walmart_v1_account_cookie_batch_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_add.go)
### 状态检测机制分析
沃尔玛卡密账户的状态检测机制包括实时检测和定时检测两种模式实时检测通过API接口触发定时检测由系统后台任务定期执行确保账户状态的及时更新
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> RealTimeCheck : "API调用"
Idle --> ScheduledCheck : "定时任务"
RealTimeCheck --> ValidateCookie : "验证Cookie有效性"
ScheduledCheck --> ValidateCookie : "验证所有账户Cookie"
ValidateCookie --> UpdateBalance : "更新账户余额"
UpdateBalance --> CheckLimits : "检查充值限制"
CheckLimits --> UpdateStatus : "更新账户状态"
UpdateStatus --> Idle : "完成"
```
**图示来源**
- [card_info_walmart_v1_account_cookie_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_check.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
**本节来源**
- [card_info_walmart_v1_account_cookie_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_check.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
## 依赖分析
系统依赖关系清晰API层依赖控制器层控制器层依赖服务层和第三方客户端服务层依赖数据模型和配置服务这种分层依赖结构确保了系统的可维护性和可测试性
```mermaid
graph TD
A[account.go] --> B[card_info_walmart_v1_account_create.go]
A --> C[card_info_walmart_v1_account_cookie_batch_add.go]
A --> D[card_info_walmart_v1_account_cookie_check.go]
B --> E[card_redeem_account.go]
C --> E
D --> E
E --> F[v_1_card_redeem_account_info.go]
E --> G[card_redeem.go]
E --> H[SysConfigDict]
B --> I[redeem client]
C --> I
D --> I
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
**本节来源**
- [api/card_info_walmart/v1/account.go](file://api/card_info_walmart/v1/account.go)
- [internal/controller/card_info_walmart/](file://internal/controller/card_info_walmart/)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 性能考虑
在批量操作中系统采用并发处理机制通过`slice.ForEachConcurrent`方法提高处理效率同时接口设置了限流机制防止恶意请求对系统造成压力状态检测采用缓存策略减少对第三方服务的频繁调用
**本节来源**
- [card_info_walmart_v1_account_cookie_batch_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_batch_check.go)
- [card_info_walmart_v1_account_cookie_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_check.go)
## 故障排除指南
常见问题包括Cookie失效账户已存在充值次数超限等系统通过详细的错误码和错误信息帮助定位问题对于批量操作失败建议检查Excel文件格式是否正确Cookie是否有效以及账户是否已存在于系统中
**本节来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_account_cookie_check.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_cookie_check.go)
## 结论
沃尔玛卡密账户管理系统提供了完整的账户生命周期管理功能包括创建更新批量操作和状态检测系统架构清晰依赖关系明确性能优化到位为卡密业务的稳定运行提供了可靠保障

View File

@@ -0,0 +1,432 @@
# 商户管理API
<cite>
**本文档引用的文件**
- [config.go](file://api/merchant/v1/config.go)
- [deploy.go](file://api/merchant/v1/deploy.go)
- [steal.go](file://api/merchant/v1/steal.go)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go)
- [merchant.go](file://internal/service/merchant.go)
- [steal_rule.go](file://internal/service/steal_rule.go)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go)
- [v_1_merchant_info.go](file://internal/model/entity/v_1_merchant_info.go)
- [v_1_merchant_deploy_info.go](file://internal/model/entity/v_1_merchant_deploy_info.go)
- [v_1_merchant_hidden_config.go](file://internal/model/entity/v_1_merchant_hidden_config.go)
- [v_1_merchant_hidden_record.go](file://internal/model/entity/v_1_merchant_hidden_record.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
商户管理API提供了一套完整的商户生命周期管理功能包括商户配置部署管理和盗单处理等核心功能该系统实现了多租户架构支持商户隔离配置继承和权限控制策略API设计遵循RESTful原则通过清晰的端点组织和标准化的请求/响应模式为商户管理提供了高效安全的接口
## 项目结构
商户管理功能主要分布在`api/merchant/v1`目录下包含配置部署和盗单处理三个核心模块每个模块都有对应的请求/响应结构体定义业务逻辑实现在`internal/controller/merchant`目录中服务层位于`internal/service`数据模型定义在`internal/model/entity`目录下这种分层架构确保了代码的可维护性和扩展性
```mermaid
graph TD
subgraph "API层"
A[config.go]
B[deploy.go]
C[steal.go]
end
subgraph "控制器层"
D[merchant_v1_merchant_config_*.go]
E[merchant_v1_merchant_deploy_*.go]
F[merchant_v1_steal_*.go]
end
subgraph "服务层"
G[merchant.go]
H[steal_rule.go]
I[merchant_deploy_info.go]
end
subgraph "数据模型层"
J[v_1_merchant_info.go]
K[v_1_merchant_deploy_info.go]
L[v_1_merchant_hidden_config.go]
M[v_1_merchant_hidden_record.go]
end
A --> D
B --> E
C --> F
D --> G
E --> I
F --> H
G --> J
I --> K
H --> L
H --> M
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go)
- [deploy.go](file://api/merchant/v1/deploy.go)
- [steal.go](file://api/merchant/v1/steal.go)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go)
**章节来源**
- [config.go](file://api/merchant/v1/config.go#L1-L80)
- [deploy.go](file://api/merchant/v1/deploy.go#L1-L56)
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
## 核心组件
商户管理API的核心组件包括商户配置管理部署信息管理和盗单规则管理商户配置管理负责商户的创建更新状态切换和查询部署信息管理处理商户的通道部署配置盗单规则管理实现盗单策略的配置状态管理和记录查询这些组件通过清晰的接口定义和分层架构确保了系统的可维护性和扩展性
**章节来源**
- [config.go](file://api/merchant/v1/config.go#L1-L80)
- [deploy.go](file://api/merchant/v1/deploy.go#L1-L56)
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
## 架构概述
系统采用典型的分层架构包括API层控制器层服务层和数据访问层API层定义了所有外部接口的请求/响应结构控制器层处理HTTP请求并调用相应的服务服务层封装了业务逻辑数据访问层负责与数据库交互这种架构实现了关注点分离提高了代码的可测试性和可维护性
```mermaid
graph TD
A[客户端] --> B[API层]
B --> C[控制器层]
C --> D[服务层]
D --> E[数据访问层]
E --> F[数据库]
subgraph "API层"
B
end
subgraph "控制器层"
C
end
subgraph "服务层"
D
end
subgraph "数据访问层"
E
end
subgraph "数据存储"
F
end
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go)
- [deploy.go](file://api/merchant/v1/deploy.go)
- [steal.go](file://api/merchant/v1/steal.go)
## 详细组件分析
### 商户配置管理分析
商户配置管理组件提供了商户的全生命周期管理功能包括创建查询更新和状态管理系统通过多租户架构实现了商户隔离每个商户都有唯一的商户UID和密钥对确保了数据的安全性和隔离性
#### 对象导向组件
```mermaid
classDiagram
class MerchantConfigListReq {
+string path : /merchant/config/getList
+string tags : 商户信息
+string method : get
+string summary : 获取商户列表信息
}
class MerchantConfigDetailReq {
+string path : /merchant/config/getDetail
+string tags : 商户信息
+string method : get
+string summary : 获取商户详细信息
+string merchantUid : 商户uid
}
class MerchantConfigUpdateReq {
+string path : /merchant/config/updateDetail
+string tags : 商户信息
+string method : post
+string summary : 修改商户信息
}
class MerchantConfigAddReq {
+string path : /merchant/config/add
+string tags : 商户信息
+string method : post
+string summary : 添加商户
}
class MerchantConfigStatusReq {
+string path : /merchant/config/switchStatus
+string tags : 商户信息
+string method : post
+string summary : 切换商户状态
+string merchantUid : 商户uid
+string status : 状态ID
}
MerchantConfigListReq --> MerchantListParamsReq : 包含
MerchantConfigDetailReq --> MerchantUid : 参数
MerchantConfigUpdateReq --> MerchantSimpleInfoRecord : 包含
MerchantConfigAddReq --> MerchantRecord : 包含
MerchantConfigStatusReq --> MerchantUid : 参数
MerchantConfigStatusReq --> Status : 参数
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go#L15-L80)
#### API/服务组件
```mermaid
sequenceDiagram
participant 客户端
participant Controller
participant Service
participant 数据库
客户端->>Controller : POST /merchant/config/add
Controller->>Controller : 创建事务
Controller->>Service : 调用Merchant().Add()
Service->>数据库 : 插入商户信息
数据库-->>Service : 成功
Service->>Service : 调用Account().Add()
Service->>数据库 : 插入账户信息
数据库-->>Service : 成功
Service-->>Controller : 成功
Controller-->>客户端 : 200 OK
```
**图示来源**
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L1-L48)
- [merchant.go](file://internal/service/merchant.go#L17-L25)
**章节来源**
- [config.go](file://api/merchant/v1/config.go#L1-L80)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L1-L48)
- [merchant.go](file://internal/service/merchant.go#L1-L37)
### 部署信息管理分析
部署信息管理组件负责商户的通道部署配置包括单通道和轮询通道的配置管理系统支持灵活的部署策略允许商户根据业务需求配置不同的支付通道和限制策略
#### 对象导向组件
```mermaid
classDiagram
class MerchantDeployListReq {
+string path : /merchant/deploy/getList
+string tags : 商户部署信息
+string method : get
+string summary : 获取商户部署通道信息
+string merchantUid : 商户uid
}
class MerchantDeployDeleteReq {
+string path : /merchant/deploy/delete
+string tags : 商户部署信息
+string method : delete
+string summary : 删除商户部署通道信息
+string merchantUid : 商户uid
+string singleRoadUid : 单通道uid
}
class MerchantDeployAddReq {
+string path : /merchant/deploy/add
+string tags : 商户部署信息
+string method : post
+string summary : 添加商户部署通道信息
}
class MerchantDeployUpdateReq {
+string path : /merchant/deploy/update
+string tags : 商户部署信息
+string method : post
+string summary : 更新商户部署通道信息
}
class MerchantDeployGetDetailReq {
+string path : merchant/deploy/getDetail
+string tags : 商户部署信息
+string method : get
+string summary : 获取商户部署通道详情
}
MerchantDeployListReq --> MerchantUid : 参数
MerchantDeployDeleteReq --> MerchantUid : 参数
MerchantDeployDeleteReq --> SingleRoadUid : 参数
MerchantDeployAddReq --> MerchantDeployRateAdd : 包含
MerchantDeployUpdateReq --> MerchantDeployRateUpdate : 包含
MerchantDeployGetDetailReq --> CommonIntId : 继承
```
**图示来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L1-L56)
#### API/服务组件
```mermaid
sequenceDiagram
participant 客户端
participant Controller
participant Service
participant 数据库
客户端->>Controller : POST /merchant/deploy/add
Controller->>Service : RoadPool().GetDetailByCode()
Service-->>Controller : 通道池信息
Controller->>Service : Road().GetDetailByUid()
Service-->>Controller : 通道信息
Controller->>Service : MerchantDeployInfo().AddOrUpdate()
Service->>数据库 : 插入或更新部署信息
数据库-->>Service : 成功
Service-->>Controller : 成功
Controller-->>客户端 : 200 OK
```
**图示来源**
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L1-L53)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go#L15-L28)
**章节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L1-L56)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L1-L53)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go#L1-L40)
### 盗单规则管理分析
盗单规则管理组件实现了盗单策略的完整管理功能包括规则的创建更新删除和状态管理系统通过严格的验证机制确保规则的正确性并提供详细的记录和统计功能
#### 对象导向组件
```mermaid
classDiagram
class StealStatusSetReq {
+string path : /merchant/config/stealRule/status
+string tags : 偷卡设置
+string method : post
+string summary : 设置偷卡状态
+bool status : 状态ID
}
class StealStatusGetReq {
+string path : /merchant/config/stealRule/status
+string tags : 偷卡设置
+string method : get
+string summary : 获取偷卡状态
}
class StealCreateReq {
+string path : /merchant/config/stealRule/create
+string tags : 偷卡设置
+string method : post
+string summary : 添加一条规则
}
class StealUpdateReq {
+string path : /merchant/config/stealRule/update
+string tags : 偷卡设置
+string method : post
+string summary : 更新一条规则
}
class StealUpdateStatusReq {
+string path : /merchant/config/stealRule/updateStatus
+string tags : 偷卡设置
+string method : post
+string summary : 更新一条规则
+int enable : 启用状态
}
class StealDeleteReq {
+string path : /merchant/config/stealRule/update
+string tags : 偷卡设置
+string method : delete
+string summary : 删除一条规则
}
class StealListReq {
+string path : /merchant/config/stealRule/list
+string tags : 偷卡设置
+string method : get
+string summary : 获取列表
}
class StealRecordListReq {
+string path : /merchant/config/stealRule/record
+string tags : 偷卡设置
+string method : get
+string summary : 获取偷卡记录
}
class StealStatsReq {
+string path : /merchant/config/stealRule/stats
+string tags : 偷卡设置
+string method : get
+string summary : 获取偷卡统计
}
StealCreateReq --> MerchantHiddenConfig : 包含
StealUpdateReq --> CommonIntId : 继承
StealUpdateReq --> MerchantHiddenConfig : 包含
StealUpdateStatusReq --> CommonIntId : 继承
StealDeleteReq --> CommonIntId : 继承
StealListReq --> CommonPageReq : 继承
StealRecordListReq --> CommonPageReq : 继承
StealStatsReq --> CommonPageReq : 继承
```
**图示来源**
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
#### API/服务组件
```mermaid
sequenceDiagram
participant 客户端
participant Controller
participant Service
participant 数据库
客户端->>Controller : POST /merchant/config/stealRule/create
Controller->>Controller : 验证金额规则
alt 金额规则验证失败
Controller-->>客户端 : 400 Bad Request
else 金额规则验证成功
Controller->>Service : StealRule().Create()
Service->>数据库 : 插入盗单规则
数据库-->>Service : 成功
Service-->>Controller : 成功
Controller-->>客户端 : 200 OK
end
```
**图示来源**
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L1-L25)
- [steal_rule.go](file://internal/service/steal_rule.go#L14-L24)
**章节来源**
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L1-L25)
- [steal_rule.go](file://internal/service/steal_rule.go#L1-L36)
## 依赖分析
商户管理API的各个组件之间存在清晰的依赖关系API层依赖于控制器层控制器层依赖于服务层服务层依赖于数据访问层这种分层依赖确保了系统的可维护性和可测试性服务层组件之间相对独立通过接口进行通信降低了耦合度
```mermaid
graph TD
A[config.go] --> B[merchant_v1_merchant_config_*.go]
B --> C[merchant.go]
C --> D[v_1_merchant_info.go]
E[deploy.go] --> F[merchant_v1_merchant_deploy_*.go]
F --> G[merchant_deploy_info.go]
G --> H[v_1_merchant_deploy_info.go]
I[steal.go] --> J[merchant_v1_steal_*.go]
J --> K[steal_rule.go]
K --> L[v_1_merchant_hidden_config.go]
K --> M[v_1_merchant_hidden_record.go]
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go)
- [deploy.go](file://api/merchant/v1/deploy.go)
- [steal.go](file://api/merchant/v1/steal.go)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go)
**章节来源**
- [config.go](file://api/merchant/v1/config.go#L1-L80)
- [deploy.go](file://api/merchant/v1/deploy.go#L1-L56)
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L1-L48)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L1-L53)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L1-L25)
## 性能考虑
商户管理API在设计时考虑了性能优化通过数据库事务确保数据一致性使用缓存减少数据库访问采用分页查询避免大数据量传输对于频繁访问的数据建议客户端实现本地缓存API响应时间应控制在200ms以内对于复杂查询应提供异步处理选项
## 故障排除指南
常见问题包括商户创建失败部署配置无效和盗单规则验证错误对于商户创建失败检查请求参数是否完整特别是必填字段如商户名称和登录密码对于部署配置无效验证通道UID是否存在且状态正常对于盗单规则验证错误确保偷卡金额不大于偷卡面额所有错误都会返回详细的错误信息帮助快速定位问题
**章节来源**
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L1-L48)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L1-L53)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L1-L25)
## 结论
商户管理API提供了一套完整的商户生命周期管理解决方案通过清晰的分层架构和模块化设计实现了商户配置部署管理和盗单处理等核心功能系统采用多租户架构确保了商户数据的隔离性和安全性API设计遵循RESTful原则提供了标准化的接口便于客户端集成和使用

View File

@@ -0,0 +1,226 @@
# 商户部署管理
<cite>
**本文档中引用的文件**
- [deploy.go](file://api/merchant/v1/deploy.go)
- [model.go](file://api/merchant/v1/model.go)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go)
- [v_1_merchant_deploy_info.go](file://internal/dao/v_1_merchant_deploy_info.go)
- [v_1_road.go](file://internal/service/v_1_road.go)
- [v_1_road_pool.go](file://internal/service/v_1_road_pool.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心数据结构](#核心数据结构)
3. [API端点说明](#api端点说明)
4. [部署创建接口](#部署创建接口)
5. [部署列表查询接口](#部署列表查询接口)
6. [部署更新接口](#部署更新接口)
7. [部署删除接口](#部署删除接口)
8. [部署详情获取接口](#部署详情获取接口)
9. [权限与安全](#权限与安全)
10. [错误处理策略](#错误处理策略)
## 简介
商户部署管理API用于配置和管理商户在不同支付通道上的部署信息该系统支持商户在单通道和轮询通道上的灵活配置包括费率设置自动结算自动代付限制策略等关键功能部署信息与商户配置紧密关联确保支付流程的安全性和可控性
**本文档中引用的文件**
- [deploy.go](file://api/merchant/v1/deploy.go)
## 核心数据结构
### 商户部署记录结构
商户部署记录包含商户在特定支付通道上的完整配置信息
```mermaid
classDiagram
class MerchantDeployRecord {
+uint Id
+string Status
+string MerchantUid
+string PayType
+string PayTypeName
+string SingleRoadName
+string RollRoadName
+string RoadSetting
}
class MerchantDeployRateAdd {
+string SingleRoadUid
+[]PlatformRateRecord SingleRoadPlatformRate
+float64 SingleRoadAgentRate
+string RollRoadCode
+float64 RollRoadAgentRate
+float64 RollRoadPlatformRate
+string MerchantUid
+string AutoSettle
+string AutoPayfor
+[]string RestrictArea
+bool IsRestrictAgent
+bool IsRestrictCardPass
+bool IsRestrictDevice
+bool IsRestrictIp
+bool IsRestrictInternalIp
+string SubmitStrategy
}
class PlatformRateRecord {
+float64 FactLabel
+float64 ShowLabel
+string PlatformLabel
+bool IsLinkSingle
+float64 Value
+string LinkID
+int Sort
}
MerchantDeployRecord --> MerchantDeployRateAdd : "包含"
MerchantDeployRateAdd --> PlatformRateRecord : "包含"
```
**图示来源**
- [model.go](file://api/merchant/v1/model.go#L53-L97)
**本节来源**
- [model.go](file://api/merchant/v1/model.go#L53-L97)
## API端点说明
商户部署管理API提供以下核心端点
| 端点 | HTTP方法 | 路径 | 功能 |
|------|--------|------|------|
| 创建部署 | POST | /merchant/deploy/add | 添加商户部署通道信息 |
| 查询部署列表 | GET | /merchant/deploy/getList | 获取商户部署通道信息 |
| 更新部署 | POST | /merchant/deploy/update | 更新商户部署通道信息 |
| 删除部署 | DELETE | /merchant/deploy/delete | 删除商户部署通道信息 |
| 获取部署详情 | GET | /merchant/deploy/getDetail | 获取商户部署通道详情 |
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L8-L50)
## 部署创建接口
### 请求参数
`merchant_v1_merchant_deploy_add` 接口用于创建新的商户部署配置
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "ControllerV1"
participant RoadPool as "RoadPool服务"
participant Road as "Road服务"
participant Service as "MerchantDeployInfo服务"
Client->>Controller : POST /merchant/deploy/add
Controller->>RoadPool : GetDetailByCode(rollRoadCode)
RoadPool-->>Controller : 返回轮询通道信息
Controller->>Road : GetDetailByUid(singleRoadUid)
Road-->>Controller : 返回单通道信息
Controller->>Service : AddOrUpdate(部署信息)
Service-->>Controller : 返回结果
Controller-->>Client : 返回响应
```
**图示来源**
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L15-L50)
- [v_1_road_pool.go](file://internal/service/v_1_road_pool.go#L16)
- [v_1_road.go](file://internal/service/v_1_road.go#L16)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go#L21)
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L29-L32)
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L15-L50)
## 部署列表查询接口
`merchant_v1_merchant_deploy_list` 接口用于查询商户的部署列表
```go
type MerchantDeployListReq struct {
g.Meta `path:"/merchant/deploy/getList" tags:"商户部署信息" method:"get" summary:"获取商户部署通道信息"`
MerchantUid string `json:"merchantUid" description:"商户uid"`
}
```
该接口需要提供商户UID作为查询参数返回该商户在所有支付通道上的部署配置列表
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L8-L11)
## 部署更新接口
`merchant_v1_merchant_deploy_update` 接口用于更新现有的商户部署配置
```go
type MerchantDeployUpdateReq struct {
g.Meta `path:"/merchant/deploy/update" tags:"商户部署信息" method:"post" summary:"更新商户部署通道信息"`
MerchantDeployRateAdd
}
```
更新操作会验证通道信息的有效性并更新数据库中的部署记录系统会自动同步通道名称等关联信息
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L38-L41)
## 部署删除接口
`merchant_v1_merchant_deploy_delete` 接口用于删除指定的商户部署配置
```go
type MerchantDeployDeleteReq struct {
g.Meta `path:"/merchant/deploy/delete" tags:"商户部署信息" method:"delete" summary:"删除商户部署通道信息"`
MerchantUid string `json:"merchantUid" v:"required#商户ID不能为空" description:"商户uid"`
SingleRoadUid string `json:"singleRoadUid" v:"required#单通道uid不能为空" description:"单通道uid"`
}
```
删除操作需要同时提供商户UID和单通道UID来唯一标识要删除的部署配置
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L18-L23)
## 部署详情获取接口
`merchant_v1_merchant_deploy_get_detail` 接口用于获取特定部署配置的详细信息
```go
type MerchantDeployGetDetailReq struct {
g.Meta `path:"merchant/deploy/getDetail" tags:"商户部署信息" method:"get" summary:"获取商户部署通道详情"`
commonApi.CommonIntId
}
```
该接口通过部署记录的ID来查询详细信息返回完整的部署配置数据
**本节来源**
- [deploy.go](file://api/merchant/v1/deploy.go#L47-L50)
## 权限与安全
商户部署管理API实施严格的权限验证机制
1. **身份验证**所有请求必须包含有效的身份令牌
2. **权限检查**操作者必须具有管理商户部署的权限
3. **数据隔离**商户只能访问和修改自己的部署配置
4. **输入验证**所有输入参数都经过严格的格式和业务规则验证
5. **操作审计**关键操作会被记录到审计日志中
系统通过服务间调用验证通道和轮询通道的有效性确保配置的准确性
**本节来源**
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L15-L50)
- [merchant_deploy_info.go](file://internal/service/merchant_deploy_info.go#L21)
## 错误处理策略
API提供详细的错误响应帮助客户端正确处理异常情况
| 错误类型 | HTTP状态码 | 响应码 | 错误信息 |
|---------|-----------|--------|---------|
| 参数验证失败 | 400 | 400 | 缺失必填字段或格式错误 |
| 通道信息无效 | 400 | 400 | 选取通道错误或轮询通道错误 |
| 资源不存在 | 404 | 404 | 指定的部署配置不存在 |
| 服务器内部错误 | 500 | 500 | 系统处理异常 |
常见错误场景包括
- 提供的单通道UID或轮询通道编码无效
- 必填字段缺失或格式不正确
- 商户UID不存在或已被禁用
- 并发修改导致的数据冲突
**本节来源**
- [merchant_v1_merchant_deploy_add.go](file://internal/controller/merchant/merchant_v1_merchant_deploy_add.go#L15-L50)
- [deploy.go](file://api/merchant/v1/deploy.go#L8-L50)

View File

@@ -0,0 +1,415 @@
# 商户配置管理
<cite>
**本文档引用文件**
- [config.go](file://api/merchant/v1/config.go)
- [model.go](file://api/merchant/v1/model.go)
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go)
- [merchant_v1_merchant_config_detail.go](file://internal/controller/merchant/merchant_v1_merchant_config_detail.go)
- [merchant.go](file://internal/service/merchant.go)
- [v_1_merchant_info.go](file://internal/model/do/v_1_merchant_info.go)
- [common.go](file://api/commonApi/common.go)
- [auth.go](file://internal/middleware/auth.go)
</cite>
## 目录
1. [简介](#简介)
2. [API端点概览](#api端点概览)
3. [商户配置数据结构](#商户配置数据结构)
4. [权限控制机制](#权限控制机制)
5. [错误处理策略](#错误处理策略)
6. [使用示例](#使用示例)
## 简介
本文档详细说明了商户配置管理API的使用方法涵盖商户配置的增删改查操作系统提供了完整的商户配置生命周期管理功能包括创建查询更新状态管理和详情获取等核心接口所有接口均遵循RESTful设计原则通过HTTP方法和URL路径实现对商户配置资源的操作
**商户配置管理功能**
商户配置管理是系统核心功能之一支持对商户基本信息支付方式费率策略等关键业务参数的全面管理系统通过结构化的API设计确保商户配置操作的安全性一致性和可追溯性
## API端点概览
商户配置管理API提供以下核心端点
### 商户配置创建
- **HTTP方法**: POST
- **URL路径**: `/api/merchant/config/add`
- **功能描述**: 创建新的商户配置
- **请求参数**: `MerchantConfigAddReq`
- **响应格式**: `MerchantConfigAddRes`
### 商户配置列表查询
- **HTTP方法**: GET
- **URL路径**: `/api/merchant/config/getList`
- **功能描述**: 查询商户配置列表支持分页
- **请求参数**: `MerchantConfigListReq`
- **响应格式**: `MerchantConfigListRes`
### 商户配置更新
- **HTTP方法**: POST
- **URL路径**: `/api/merchant/config/updateDetail`
- **功能描述**: 更新商户配置信息
- **请求参数**: `MerchantConfigUpdateReq`
- **响应格式**: `MerchantConfigUpdateRes`
### 商户配置状态管理
- **HTTP方法**: POST
- **URL路径**: `/api/merchant/config/switchStatus`
- **功能描述**: 切换商户状态启用/禁用
- **请求参数**: `MerchantConfigStatusReq`
- **响应格式**: `MerchantConfigStatusRes`
### 商户配置详情获取
- **HTTP方法**: GET
- **URL路径**: `/api/merchant/config/getDetail`
- **功能描述**: 获取指定商户的详细配置信息
- **请求参数**: `MerchantConfigDetailReq`
- **响应格式**: `MerchantConfigDetailRes`
**API端点关系图**
```mermaid
flowchart TD
A["客户端"] --> B["创建商户配置"]
A --> C["查询商户列表"]
A --> D["获取商户详情"]
A --> E["更新商户配置"]
A --> F["管理商户状态"]
B --> |POST /add| G[商户配置服务]
C --> |GET /getList| G
D --> |GET /getDetail| G
E --> |POST /updateDetail| G
F --> |POST /switchStatus| G
G --> H[数据库]
G --> I[权限验证]
G --> J[事务管理]
style G fill:#4CAF50,stroke:#388E3C,color:white
style H fill:#2196F3,stroke:#1976D2,color:white
style I fill:#FF9800,stroke:#F57C00,color:white
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go#L39-L52)
- [merchant.go](file://internal/service/merchant.go#L15-L25)
## 商户配置数据结构
### 核心数据模型
#### 商户记录MerchantRecord
商户创建时所需的基本信息
| 字段名 | 类型 | 必填 | 描述 | 验证规则 |
|--------|------|------|------|----------|
| status | string | | 商户状态 | 必须提供 |
| merchantName | string | | 商户名称 | 必须提供 |
| loginAccount | string | | 登录账号 | 必须提供 |
| remark | string | | 备注信息 | - |
| loginPassword | string | | 登录密码 | 必须提供 |
**Section sources**
- [model.go](file://api/merchant/v1/model.go#L14-L20)
#### 商户简单信息记录MerchantSimpleInfoRecord
商户基本信息用于更新和详情展示
| 字段名 | 类型 | 必填 | 描述 | 验证规则 |
|--------|------|------|------|----------|
| merchantName | string | | 商户名称 | 必须提供 |
| merchantUid | string | | 商户唯一标识 | 必须提供 |
| loginAccount | string | | 登录账号 | 必须提供 |
| whiteIps | string | | IP白名单配置 | - |
| remark | string | | 备注信息 | - |
**Section sources**
- [model.go](file://api/merchant/v1/model.go#L45-L51)
#### 商户信息记录MerchantInfoRecord
完整的商户配置信息包含所有字段
| 字段名 | 类型 | 描述 |
|--------|------|------|
| status | string | 商户状态 |
| belongAgentUid | string | 所属代理UID |
| belongAgentName | string | 所属代理名称 |
| merchantName | string | 商户名称 |
| merchantUid | string | 商户唯一标识 |
| merchantKey | string | 商户密钥 |
| merchantSecret | string | 商户密钥 |
| loginAccount | string | 登录账号 |
| clearTextPassword | string | 明文密码 |
| autoSettle | string | 是否自动结算 |
| autoPayFor | string | 是否自动代付 |
| whiteIps | string | IP白名单配置 |
| remark | string | 备注信息 |
| singlePayForRoadUid | string | 单代付通道UID |
| singlePayForRoadName | string | 单代付通道名称 |
| rollPayForRoadCode | string | 轮询代付通道编码 |
| rollPayForRoadName | string | 轮询代付通道名称 |
| payforFee | float64 | 代付手续费 |
| updateTime | *gtime.Time | 更新时间 |
| createTime | *gtime.Time | 创建时间 |
**Section sources**
- [model.go](file://api/merchant/v1/model.go#L22-L43)
### 数据库实体映射
商户配置信息在数据库中的存储结构
```mermaid
erDiagram
MERCHANT_INFO {
uint id PK
string status
string belong_agent_uid
string belong_agent_name
string merchant_name
string merchant_uid UK
string merchant_key
string merchant_secret
string login_account UK
string login_password
string auto_settle
string auto_pay_for
string white_ips
string remark
string single_pay_for_road_uid
string single_pay_for_road_name
string roll_pay_for_road_code
string roll_pay_for_road_name
float payfor_fee
timestamp update_time
timestamp create_time
string otp_secret
}
```
**图示来源**
- [v_1_merchant_info.go](file://internal/model/do/v_1_merchant_info.go#L10-L37)
## 权限控制机制
### 认证流程
系统采用多层认证机制确保商户配置操作的安全性
```mermaid
sequenceDiagram
participant Client as 客户端
participant Auth as 认证中间件
participant Service as 商户服务
participant DB as 数据库
Client->>Auth : 发送请求 (含Token)
Auth->>Auth : 检查白名单
alt 在白名单中
Auth-->>Client : 直接放行
else 不在白名单
Auth->>Auth : 验证Token有效性
Auth->>Auth : 检查Redis中Token
Auth->>Auth : 续签Token
Auth-->>Service : 认证通过
Service->>DB : 执行业务逻辑
DB-->>Service : 返回结果
Service-->>Client : 返回响应
end
```
**图示来源**
- [auth.go](file://internal/middleware/auth.go#L50-L154)
- [config.go](file://api/merchant/v1/config.go#L10-L52)
### 权限验证规则
1. **Token验证**: 所有非白名单接口必须提供有效的JWT Token
2. **Token续签**: 每次请求成功后自动续签Token有效期
3. **Redis同步**: Token状态与Redis保持同步确保即时失效
4. **双因素认证**: 敏感操作支持二次验证机制
### 授权策略
- **创建权限**: 仅管理员角色可创建新商户
- **更新权限**: 仅商户所属管理员可修改配置
- **状态管理**: 需要高级管理员权限才能切换商户状态
- **详情查看**: 具有查看权限的用户均可获取商户详情
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L50-L154)
- [merchant.go](file://internal/service/merchant.go#L15-L25)
## 错误处理策略
### 常见错误码
系统定义了统一的错误处理机制返回标准化的错误响应
| 错误码 | HTTP状态码 | 错误信息 | 场景说明 |
|--------|------------|----------|----------|
| 400 | 400 | 参数验证失败 | 请求参数缺失或格式错误 |
| 401 | 401 | 认证失败 | Token无效或过期 |
| 403 | 403 | 权限不足 | 用户无权执行该操作 |
| 404 | 404 | 资源不存在 | 指定商户UID不存在 |
| 409 | 409 | 配置冲突 | 商户名称或账号已存在 |
| 500 | 500 | 服务器内部错误 | 系统异常或数据库错误 |
### 异常处理流程
```mermaid
flowchart TD
A[接收请求] --> B{参数验证}
B --> |失败| C[返回400错误]
B --> |通过| D{权限验证}
D --> |失败| E[返回401/403错误]
D --> |通过| F[执行业务逻辑]
F --> G{操作成功?}
G --> |是| H[返回成功响应]
G --> |否| I{错误类型}
I --> |商户不存在| J[返回404错误]
I --> |配置冲突| K[返回409错误]
I --> |其他错误| L[返回500错误]
style C fill:#F44336,stroke:#D32F2F,color:white
style E fill:#F44336,stroke:#D32F2F,color:white
style J fill:#F44336,stroke:#D32F2F,color:white
style K fill:#F44336,stroke:#D32F2F,color:white
style L fill:#F44336,stroke:#D32F2F,color:white
```
**图示来源**
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L10-L48)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go#L10-L53)
### 具体错误场景
#### 创建商户时的错误处理
- **商户名称重复**: 返回409错误提示"商户名称已存在"
- **登录账号重复**: 返回409错误提示"登录账号已存在"
- **参数缺失**: 返回400错误明确指出缺失的字段
- **数据库异常**: 返回500错误记录详细日志
#### 更新商户时的错误处理
- **商户不存在**: 返回404错误提示"指定商户不存在"
- **权限不足**: 返回403错误提示"无权修改该商户配置"
- **状态冲突**: 返回409错误当尝试对已删除商户进行更新
#### 状态管理时的错误处理
- **状态切换失败**: 返回500错误记录事务回滚原因
- **关联账户异常**: 返回500错误当商户钱包状态更新失败时
**Section sources**
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L10-L48)
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go#L10-L16)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go#L10-L53)
## 使用示例
### 创建商户配置
```json
POST /api/merchant/config/add
Content-Type: application/json
{
"status": "active",
"merchantName": "测试商户",
"loginAccount": "test_merchant",
"loginPassword": "password123",
"remark": "测试商户备注"
}
```
**成功响应**:
```json
{
"code": 0,
"message": "OK",
"data": {}
}
```
### 查询商户配置列表
```json
GET /api/merchant/config/getList?current=1&pageSize=10&merchantName=测试
Authorization: Bearer {{token}}
```
**成功响应**:
```json
{
"code": 0,
"message": "OK",
"data": {
"total": 1,
"list": [
{
"status": "active",
"belongAgentUid": "",
"belongAgentName": "",
"merchantName": "测试商户",
"merchantUid": "8888a1b2c3d4e5f6",
"merchantKey": "kkkkx1y2z3w4v5u6",
"merchantSecret": "ssssm1n2o3p4q5r6",
"loginAccount": "test_merchant",
"autoSettle": "no",
"autoPayFor": "no",
"whiteIps": "",
"remark": "测试商户备注",
"singlePayForRoadUid": "",
"singlePayForRoadName": "",
"rollPayForRoadCode": "",
"rollPayForRoadName": "",
"payforFee": 0,
"updateTime": "2024-01-01T10:00:00+08:00",
"createTime": "2024-01-01T10:00:00+08:00"
}
]
}
}
```
### 更新商户配置
```json
POST /api/merchant/config/updateDetail
Content-Type: application/json
Authorization: Bearer {{token}}
{
"merchantName": "更新后的商户名称",
"merchantUid": "8888a1b2c3d4e5f6",
"loginAccount": "test_merchant",
"whiteIps": "192.168.1.1,192.168.1.2",
"remark": "更新后的备注信息"
}
```
### 获取商户详情
```json
GET /api/merchant/config/getDetail?merchantUid=8888a1b2c3d4e5f6
Authorization: Bearer {{token}}
```
**成功响应**:
```json
{
"code": 0,
"message": "OK",
"data": {
"merchantName": "更新后的商户名称",
"merchantUid": "8888a1b2c3d4e5f6",
"loginAccount": "test_merchant",
"whiteIps": "192.168.1.1,192.168.1.2",
"remark": "更新后的备注信息"
}
}
```
### 切换商户状态
```json
POST /api/merchant/config/switchStatus
Content-Type: application/json
Authorization: Bearer {{token}}
{
"merchantUid": "8888a1b2c3d4e5f6",
"status": "inactive"
}
```
**Section sources**
- [merchant_v1_merchant_config_add.go](file://internal/controller/merchant/merchant_v1_merchant_config_add.go#L10-L48)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go#L10-L34)
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go#L10-L16)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go#L10-L53)
- [merchant_v1_merchant_config_detail.go](file://internal/controller/merchant/merchant_v1_merchant_config_detail.go#L10-L21)

View File

@@ -0,0 +1,144 @@
# 盗单处理管理
<cite>
**本文档中引用的文件**
- [steal.go](file://api/merchant/v1/steal.go)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go)
- [merchant_v1_steal_list.go](file://internal/controller/merchant/merchant_v1_steal_list.go)
- [merchant_v1_steal_update.go](file://internal/controller/merchant/merchant_v1_steal_update.go)
- [merchant_v1_steal_delete.go](file://internal/controller/merchant/merchant_v1_steal_delete.go)
- [merchant_v1_steal_status_get.go](file://internal/controller/merchant/merchant_v1_steal_status_get.go)
- [merchant_v1_steal_status_set.go](file://internal/controller/merchant/merchant_v1_steal_status_set.go)
- [merchant_v1_steal_stats.go](file://internal/controller/merchant/merchant_v1_steal_stats.go)
- [merchant_v1_steal_record_list.go](file://internal/controller/merchant/merchant_v1_steal_record_list.go)
- [steal_rule.go](file://internal/service/steal_rule.go)
- [steal_rule.go](file://internal/model/steal_rule.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心组件](#核心组件)
3. [API端点说明](#api端点说明)
4. [数据结构与匹配逻辑](#数据结构与匹配逻辑)
5. [集成与执行时机](#集成与执行时机)
6. [权限控制机制](#权限控制机制)
7. [错误处理与监控建议](#错误处理与监控建议)
8. [使用示例](#使用示例)
9. [结论](#结论)
## 简介
本文档详细描述了盗单处理管理API的设计与实现涵盖盗单规则的创建查询更新删除状态管理统计和记录查询等核心功能该系统旨在通过灵活的规则配置自动识别并处理潜在的盗单行为保障商户交易安全API设计遵循RESTful规范提供清晰的接口定义和统一的响应格式
## 核心组件
本系统的核心组件包括API定义层控制器层服务层和数据模型层API定义层`steal.go`负责声明所有端点的HTTP方法路径和数据结构控制器层`merchant_v1_steal_create.go`处理请求并调用服务层服务层`steal_rule.go`封装业务逻辑数据模型层`steal_rule.go` in model定义数据传输对象
**核心组件来源**
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L1-L25)
- [steal_rule.go](file://internal/service/steal_rule.go#L1-L41)
- [steal_rule.go](file://internal/model/steal_rule.go#L1-L34)
## API端点说明
以下表格详细列出了盗单处理管理的所有API端点
| 端点名称 | HTTP方法 | URL路径 | 功能描述 |
| :--- | :--- | :--- | :--- |
| merchant_v1_steal_create | POST | /merchant/config/stealRule/create | 创建新的盗单规则 |
| merchant_v1_steal_list | GET | /merchant/config/stealRule/list | 查询盗单规则列表 |
| merchant_v1_steal_update | POST | /merchant/config/stealRule/update | 更新指定的盗单规则 |
| merchant_v1_steal_delete | DELETE | /merchant/config/stealRule/update | 删除指定的盗单规则 |
| merchant_v1_steal_status_get | GET | /merchant/config/stealRule/status | 获取全局盗单功能状态 |
| merchant_v1_steal_status_set | POST | /merchant/config/stealRule/status | 设置全局盗单功能状态 |
| merchant_v1_steal_stats | GET | /merchant/config/stealRule/stats | 获取盗单统计信息 |
| merchant_v1_steal_record_list | GET | /merchant/config/stealRule/record | 查询盗单处理记录 |
**API端点来源**
- [steal.go](file://api/merchant/v1/steal.go#L1-L116)
## 数据结构与匹配逻辑
### 盗单规则数据结构
盗单规则的核心数据结构为`MerchantHiddenConfig`包含以下关键字段
- `name`: 规则名称
- `merchantUid`: 关联的商户ID
- `roadUid`: 通道ID
- `amount`: 偷卡金额间隔
- `faceAmount`: 偷卡面额
- `delayDurationMin` / `delayDurationMax`: 处理延迟时间范围
- `enable`: 启用状态
- `strategy`: 处理策略
- `amountRule`: 金额规则数组
### 匹配与处理逻辑
系统通过比较订单金额与`amountRule`中的规则进行匹配`merchant_v1_steal_create.go`创建规则时会校验`amountRule`中的每个值是否不大于`faceAmount`确保规则的合理性匹配成功后根据配置的策略和延迟时间执行相应的处理动作
```mermaid
flowchart TD
Start([接收到订单]) --> CheckStatus["检查盗单功能全局状态"]
CheckStatus --> |关闭| End1([正常处理])
CheckStatus --> |开启| MatchRule["匹配盗单规则"]
MatchRule --> RuleMatched{"规则匹配?"}
RuleMatched --> |否| End2([正常处理])
RuleMatched --> |是| ApplyStrategy["应用处理策略"]
ApplyStrategy --> Delay["延迟 delayDurationMin-Max"]
Delay --> Execute["执行盗单处理"]
Execute --> Log["记录处理日志"]
Log --> End3([完成])
```
**数据结构来源**
- [steal.go](file://api/merchant/v1/steal.go#L25-L45)
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L10-L15)
## 集成与执行时机
盗单处理模块深度集成于订单处理流程中当一个新订单进入系统后订单处理服务会首先调用盗单规则服务进行匹配检查此检查发生在订单验证和支付处理之前作为风险控制的第一道防线如果订单被识别为潜在盗单则会根据配置的策略如延迟处理标记拒绝等进行相应操作而不是立即执行正常的订单流程
## 权限控制机制
系统通过基于角色的访问控制RBAC来确保只有授权用户可以修改盗单规则所有对盗单规则的写操作创建更新删除状态设置都需要经过身份验证和权限校验控制器层通过中间件验证用户身份和权限只有具备盗单设置标签tags:"偷卡设置"权限的用户才能访问这些API端点
## 错误处理与监控建议
### 错误处理
系统在`merchant_v1_steal_create.go`中实现了基础的业务逻辑校验例如检查偷卡金额是否超过面额对于无效请求服务会返回带有明确错误信息的响应所有API调用都应进行异常捕获确保不会因内部错误导致服务中断
### 监控建议
1. **日志监控**记录所有盗单规则的变更和处理记录便于审计和追溯
2. **统计分析**定期使用`merchant_v1_steal_stats`端点分析盗单发生频率和金额评估规则有效性
3. **告警机制**当盗单处理量异常激增时触发告警通知管理员
4. **性能监控**监控盗单规则匹配的响应时间避免影响正常订单处理速度
**错误处理来源**
- [merchant_v1_steal_create.go](file://internal/controller/merchant/merchant_v1_steal_create.go#L10-L15)
## 使用示例
### 创建盗单规则
```http
POST /merchant/config/stealRule/create
Content-Type: application/json
{
"name": "高风险订单监控",
"merchantUid": "mch_123",
"roadUid": "road_456",
"amount": 100,
"faceAmount": 500,
"delayDurationMin": 300,
"delayDurationMax": 600,
"enable": 1,
"strategy": 1,
"amountRule": [101, 201, 301, 401]
}
```
### 查询盗单统计
```http
GET /merchant/config/stealRule/stats?current=1&pageSize=10&dateRange[0]=2023-01-01&dateRange[1]=2023-12-31
```
## 结论
本文档全面介绍了盗单处理管理API的各个方面该系统提供了一套完整的工具使商户能够灵活地配置和管理盗单风险通过精确的规则定义严格的权限控制和详尽的监控能力系统能够有效识别和处理潜在的盗单行为保护商户利益建议定期审查和更新盗单规则以应对不断变化的风险模式

View File

@@ -0,0 +1,339 @@
# 权限管理API
<cite>
**本文档中引用的文件**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [tenant.go](file://api/authority/v1/tenant.go)
- [model.go](file://api/authority/v1/model.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_role.go](file://internal/model/sys_role.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
- [sys_role_v1_role_list.go](file://internal/controller/sys_role/sys_role_v1_role_list.go)
- [sys_role_v1_role_delete.go](file://internal/controller/sys_role/sys_role_v1_role_delete.go)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go)
</cite>
## 目录
1. [介绍](#介绍)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 介绍
本文档详细描述了权限管理API的实现涵盖用户角色和租户管理功能重点介绍基于RBAC基于角色的访问控制模型的权限系统包括菜单管理角色管理租户管理等核心接口文档详细说明了各端点的HTTP方法URL模式请求/响应结构和认证机制并解释了权限规则角色继承和访问控制策略的实现细节
## 项目结构
```mermaid
graph TD
subgraph "API 接口层"
A[api/authority/v1/menu.go]
B[api/authority/v1/role.go]
C[api/authority/v1/tenant.go]
D[api/sys_auth_rule/v1/sys_auth_rule.go]
E[api/sys_role/v1/sys_role.go]
end
subgraph "内部逻辑层"
F[internal/model/sys_role.go]
G[internal/model/sys_auth_rule.go]
H[internal/service/Menu.go]
end
subgraph "控制器层"
I[internal/controller/authority/authority_v1_menu_create.go]
J[internal/controller/authority/authority_v1_menu_list.go]
K[internal/controller/authority/authority_v1_menu_update.go]
L[internal/controller/sys_role/sys_role_v1_role_add.go]
M[internal/controller/sys_role/sys_role_v1_role_list.go]
N[internal/controller/sys_role/sys_role_v1_role_delete.go]
O[internal/controller/sys_role/sys_role_v1_role_edit.go]
end
subgraph "权限模型"
P[resource/casbin/rbac_model.conf]
end
A --> I
B --> L
B --> M
B --> N
B --> O
D --> G
E --> F
I --> H
J --> H
K --> H
P --> H
```
**图示来源**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
- [sys_role_v1_role_list.go](file://internal/controller/sys_role/sys_role_v1_role_list.go)
- [sys_role_v1_role_delete.go](file://internal/controller/sys_role/sys_role_v1_role_delete.go)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
**节来源**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [tenant.go](file://api/authority/v1/tenant.go)
- [model.go](file://api/authority/v1/model.go)
## 核心组件
权限管理API的核心组件包括菜单管理角色管理和租户管理菜单管理负责系统功能菜单的增删改查角色管理实现角色的创建编辑删除和查询租户管理支持多租户环境下的权限隔离这些组件共同构成了基于RBAC模型的权限控制系统
**节来源**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [tenant.go](file://api/authority/v1/tenant.go)
## 架构概述
```mermaid
graph TD
Client[客户端] --> API[权限管理API]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> Model[模型层]
Service --> Casbin[权限引擎]
Model --> Database[(数据库)]
subgraph "权限引擎"
Casbin --> rbac_model[rbac_model.conf]
end
subgraph "模型层"
Model --> SysAuthRule[SysAuthRule]
Model --> SysRole[SysRole]
end
subgraph "控制器层"
Controller --> MenuController[MenuController]
Controller --> RoleController[RoleController]
end
```
**图示来源**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
## 详细组件分析
### 菜单管理分析
菜单管理组件负责系统功能菜单的维护支持菜单的创建查询更新和删除操作通过树形结构组织菜单项支持多级嵌套
#### 菜单创建流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "MenuController"
participant Service as "MenuService"
participant Model as "SysAuthRule"
Client->>Controller : POST /auth/menu/create
Controller->>Model : 创建SysAuthRuleInput
Controller->>Service : 调用AddMenu
Service->>Service : 验证菜单数据
Service->>Model : 保存菜单信息
Model-->>Service : 返回结果
Service-->>Controller : 返回操作结果
Controller-->>Client : 返回响应
```
**图示来源**
- [menu.go](file://api/authority/v1/menu.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
#### 菜单查询流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "MenuController"
participant Service as "MenuService"
participant Model as "SysAuthRule"
Client->>Controller : GET /auth/menu/getList
Controller->>Service : 调用GetMenuTree
Service->>Model : 查询菜单数据
Model-->>Service : 返回菜单列表
Service-->>Controller : 构建树形结构
Controller-->>Client : 返回菜单树
```
**图示来源**
- [menu.go](file://api/authority/v1/menu.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
### 角色管理分析
角色管理组件提供角色的全生命周期管理功能包括角色的创建查询更新和删除
#### 角色创建流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "RoleController"
participant Service as "RoleService"
participant Model as "SysRole"
Client->>Controller : POST /auth/role/create
Controller->>Model : 创建RoleAddInput
Controller->>Service : 调用AddRole
Service->>Service : 验证角色数据
Service->>Model : 保存角色信息
Model-->>Service : 返回结果
Service-->>Controller : 返回操作结果
Controller-->>Client : 返回响应
```
**图示来源**
- [role.go](file://api/authority/v1/role.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
#### 角色查询流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "RoleController"
participant Service as "RoleService"
participant Model as "SysRole"
Client->>Controller : GET /auth/role/getList
Controller->>Service : 调用GetRoleListSearch
Service->>Model : 查询角色数据
Model-->>Service : 返回角色列表
Service-->>Controller : 处理分页数据
Controller-->>Client : 返回角色列表
```
**图示来源**
- [role.go](file://api/authority/v1/role.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [sys_role_v1_role_list.go](file://internal/controller/sys_role/sys_role_v1_role_list.go)
### RBAC权限模型分析
RBAC基于角色的访问控制模型是本系统权限控制的核心通过Casbin权限引擎实现
```mermaid
classDiagram
class SysAuthRule {
+int Id
+string Name
+string Path
+string Component
+int ParentId
+int Sort
+string Icon
+bool Hidden
+Children []*SysAuthRule
}
class SysRole {
+int Id
+string Name
+string Code
+string Remark
+int Status
+int Sort
}
class CasbinRule {
+string PType
+string V0
+string V1
+string V2
}
class rbac_model.conf {
+[request_definition]
+[policy_definition]
+[role_definition]
+[policy_effect]
+[matchers]
}
SysRole "1" -- "0..*" SysAuthRule : 拥有
CasbinRule --> SysRole : 关联
CasbinRule --> SysAuthRule : 关联
rbac_model.conf --> CasbinRule : 定义规则
```
**图示来源**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
## 依赖分析
```mermaid
graph TD
A[menu.go] --> B[authority_v1_menu_create.go]
A --> C[authority_v1_menu_list.go]
A --> D[authority_v1_menu_update.go]
E[role.go] --> F[sys_role_v1_role_add.go]
E --> G[sys_role_v1_role_list.go]
E --> H[sys_role_v1_role_delete.go]
E --> I[sys_role_v1_role_edit.go]
B --> J[SysAuthRuleInput]
C --> K[SysAuthRule]
D --> L[SysAuthRuleWithIDInput]
F --> M[RoleAddInput]
G --> N[RoleListInput]
H --> O[RoleDeleteReq]
I --> P[RoleEditInput]
J --> Q[sys_auth_rule.go]
M --> R[sys_role.go]
N --> R
O --> R
P --> R
```
**图示来源**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
- [sys_role_v1_role_list.go](file://internal/controller/sys_role/sys_role_v1_role_list.go)
- [sys_role_v1_role_delete.go](file://internal/controller/sys_role/sys_role_v1_role_delete.go)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go)
**节来源**
- [menu.go](file://api/authority/v1/menu.go)
- [role.go](file://api/authority/v1/role.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
## 性能考虑
权限管理API在设计时考虑了性能优化通过缓存机制减少数据库查询使用分页查询避免大数据量传输并在权限验证时采用高效的匹配算法建议在生产环境中配置适当的缓存策略以提高系统响应速度
## 故障排除指南
当遇到权限管理API相关问题时首先检查请求的认证信息是否正确然后验证请求参数是否符合API规范对于菜单和角色操作失败的情况检查相关数据是否存在以及权限是否足够系统提供了详细的错误码和错误信息可根据这些信息进行问题定位
**节来源**
- [errHandler/handler.go](file://internal/dao/errHandler/handler.go)
- [middleware/auth.go](file://internal/middleware/auth.go)
## 结论
权限管理API提供了一套完整的RBAC权限控制系统支持菜单角色和租户的全生命周期管理通过清晰的接口设计和模块化架构系统具有良好的可维护性和扩展性建议在使用时遵循最佳实践合理规划权限结构确保系统的安全性和稳定性

View File

@@ -0,0 +1,259 @@
# 租户管理API
<cite>
**本文档中引用的文件**
- [tenant.go](file://api/authority/v1/tenant.go)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
- [authority_v1_tenant_update.go](file://internal/controller/authority/authority_v1_tenant_update.go)
- [authority_v1_tenant_delete.go](file://internal/controller/authority/authority_v1_tenant_delete.go)
- [authority_v1_tenant_list.go](file://internal/controller/authority/authority_v1_tenant_list.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [v_1_sys_user.go](file://internal/model/entity/v_1_sys_user.go)
- [auth.go](file://internal/middleware/auth.go)
</cite>
## 目录
1. [介绍](#介绍)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 介绍
本文档详细描述了租户管理API的设计与实现涵盖租户的增删改查操作系统采用多租户架构通过统一的权限控制机制实现不同客户或组织之间的资源隔离API设计遵循RESTful原则使用标准HTTP方法进行资源操作并通过统一的认证机制确保安全性尽管当前实现中各操作仍返回"未实现"状态但接口定义和架构设计已完整为后续功能开发提供了清晰的蓝图
## 项目结构
系统采用分层架构设计将API定义业务逻辑和数据访问分离租户管理功能主要分布在API层和控制器层通过清晰的包结构组织相关功能
```mermaid
graph TD
subgraph "API层"
A[api/authority/v1]
A --> B[tenant.go]
A --> C[role.go]
A --> D[menu.go]
end
subgraph "控制器层"
E[internal/controller/authority]
E --> F[authority_v1_tenant_create.go]
E --> G[authority_v1_tenant_update.go]
E --> H[authority_v1_tenant_delete.go]
E --> I[authority_v1_tenant_list.go]
end
subgraph "模型层"
J[internal/model]
J --> K[sys_user.go]
J --> L[entity/v_1_sys_user.go]
end
subgraph "中间件层"
M[internal/middleware]
M --> N[auth.go]
end
B --> F
B --> G
B --> H
B --> I
K --> E
N --> E
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [auth.go](file://internal/middleware/auth.go)
**本节来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
## 核心组件
租户管理API的核心组件包括请求/响应结构体控制器方法和认证中间件这些组件共同构成了租户管理功能的基础框架
**本节来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [sys_user.go](file://internal/model/sys_user.go)
## 架构概述
系统采用典型的MVC架构模式各层职责分明API层定义接口契约控制器层处理业务逻辑模型层管理数据结构中间件层负责横切关注点如认证授权
```mermaid
graph TD
Client[客户端] --> API[API接口]
API --> Auth[认证中间件]
Auth --> Controller[控制器]
Controller --> Service[服务层]
Service --> DAO[数据访问对象]
DAO --> DB[(数据库)]
API -.->|TenantListReq| Controller
API -.->|TenantCreateReq| Controller
API -.->|TenantUpdateReq| Controller
API -.->|TenantDeleteReq| Controller
style API fill:#f9f,stroke:#333
style Auth fill:#ff9,stroke:#333
style Controller fill:#9ff,stroke:#333
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [auth.go](file://internal/middleware/auth.go)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
## 详细组件分析
### 租户管理操作分析
租户管理API提供了完整的CRUD操作接口每个操作都有明确的HTTP方法URL路径和参数结构
#### 租户创建操作
```mermaid
classDiagram
class TenantCreateReq {
+string path : /auth/tenant/create
+string method : post
+string tags : 用户信息
+string summary : 创建用户信息
}
class TenantCreateRes {
+string json : application/json
}
class ControllerV1 {
+TenantCreate(ctx, req) (res, err)
}
TenantCreateReq --> ControllerV1 : "作为参数"
ControllerV1 --> TenantCreateRes : "返回结果"
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go#L17-L19)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
#### 租户更新操作
```mermaid
classDiagram
class TenantUpdateReq {
+string path : /auth/tenant/update
+string method : post
+string tags : 用户信息
+string summary : 修改用户信息
+CommonIntId
}
class TenantUpdateRes {
+string json : application/json
}
class ControllerV1 {
+TenantUpdate(ctx, req) (res, err)
}
TenantUpdateReq --> ControllerV1 : "作为参数"
ControllerV1 --> TenantUpdateRes : "返回结果"
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go#L25-L28)
- [authority_v1_tenant_update.go](file://internal/controller/authority/authority_v1_tenant_update.go)
#### 租户删除操作
```mermaid
classDiagram
class TenantDeleteReq {
+string path : /auth/tenant/delete
+string method : delete
+string tags : 用户信息
+string summary : 删除用户信息
+CommonIntId
}
class TenantDeleteRes {
+string json : application/json
}
class ControllerV1 {
+TenantDelete(ctx, req) (res, err)
}
TenantDeleteReq --> ControllerV1 : "作为参数"
ControllerV1 --> TenantDeleteRes : "返回结果"
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go#L34-L37)
- [authority_v1_tenant_delete.go](file://internal/controller/authority/authority_v1_tenant_delete.go)
#### 租户查询操作
```mermaid
classDiagram
class TenantListReq {
+string path : /auth/tenant/getList
+string method : get
+string tags : 用户信息
+string summary : 获取用户信息
+CommonPageReq
}
class TenantListRes {
+string json : application/json
}
class ControllerV1 {
+TenantList(ctx, req) (res, err)
}
TenantListReq --> ControllerV1 : "作为参数"
ControllerV1 --> TenantListRes : "返回结果"
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go#L8-L11)
- [authority_v1_tenant_list.go](file://internal/controller/authority/authority_v1_tenant_list.go)
**本节来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
- [authority_v1_tenant_update.go](file://internal/controller/authority/authority_v1_tenant_update.go)
- [authority_v1_tenant_delete.go](file://internal/controller/authority/authority_v1_tenant_delete.go)
- [authority_v1_tenant_list.go](file://internal/controller/authority/authority_v1_tenant_list.go)
## 依赖分析
租户管理功能依赖于多个核心组件包括认证中间件用户模型和基础服务接口
```mermaid
graph TD
A[TenantCreateReq] --> B[ControllerV1.TenantCreate]
C[TenantUpdateReq] --> D[ControllerV1.TenantUpdate]
E[TenantDeleteReq] --> F[ControllerV1.TenantDelete]
G[TenantListReq] --> H[ControllerV1.TenantList]
B --> I[认证中间件]
D --> I
F --> I
H --> I
B --> J[ISysUser.Add]
D --> K[ISysUser.Edit]
F --> L[ISysUser.Delete]
H --> M[ISysUser.List]
I --> N[Token验证]
I --> O[白名单检查]
style A fill:#f96,stroke:#333
style C fill:#f96,stroke:#333
style E fill:#f96,stroke:#333
style G fill:#f96,stroke:#333
```
**图示来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [auth.go](file://internal/middleware/auth.go)
- [sys_user.go](file://internal/model/sys_user.go)
**本节来源**
- [tenant.go](file://api/authority/v1/tenant.go)
- [auth.go](file://internal/middleware/auth.go)
- [sys_user.go](file://internal/model/sys_user.go)
## 性能考虑
虽然当前实现尚未完成但架构设计已考虑性能优化因素API层与控制器层的分离有助于缓存策略的实施而统一的认证中间件可以集中管理会话状态分页查询接口的设计也考虑了大数据量场景下的性能表现建议在完整实现时采用连接池查询缓存和异步处理等技术进一步提升系统性能
## 故障排除指南
当前租户管理API的所有操作均返回"未实现"错误这是预期行为表明功能尚未完成开发系统提供了统一的错误处理机制所有错误都通过gerror.NewCode包装并返回标准错误码认证相关的错误会记录详细日志便于排查问题白名单机制确保了关键接口的可访问性即使在认证系统出现问题时也能保证核心业务的正常运行
**本节来源**
- [authority_v1_tenant_create.go](file://internal/controller/authority/authority_v1_tenant_create.go)
- [auth.go](file://internal/middleware/auth.go)
- [errHandler](file://internal/errHandler)
## 结论
租户管理API的架构设计完整且合理为多租户系统的实现奠定了良好基础接口定义清晰层次结构分明具备良好的可扩展性和可维护性下一步开发应聚焦于实现控制器中的业务逻辑完善数据访问层并建立完整的测试体系同时建议补充API文档和使用示例以便于其他开发人员快速理解和使用该功能

View File

@@ -0,0 +1,345 @@
# 菜单管理API
<cite>
**本文档中引用的文件**
- [menu.go](file://api/authority/v1/menu.go)
- [model.go](file://api/authority/v1/model.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
- [authority_v1_menu_delete.go](file://internal/controller/authority/authority_v1_menu_delete.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [common.go](file://api/commonApi/common.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了菜单管理API的设计与实现涵盖菜单的增删改查操作该API基于RBAC基于角色的访问控制模型通过菜单权限控制用户界面访问权限文档详细说明了创建菜单更新菜单删除菜单和获取菜单列表等端点的HTTP方法URL模式请求/响应模式和认证机制并提供实际使用示例同时文档还解释了菜单权限在RBAC模型中的作用以及错误处理策略安全考虑和性能优化建议
## 项目结构
菜单管理API的实现分布在多个目录中主要涉及API定义控制器逻辑和数据模型API端点定义位于`api/authority/v1/`目录下控制器实现位于`internal/controller/authority/`目录中数据模型定义在`internal/model/``internal/model/entity/`目录中服务层接口在`internal/service/`目录中声明而RBAC权限模型配置位于`resource/casbin/`目录下
```mermaid
graph TB
subgraph "API层"
A[menu.go]
B[model.go]
end
subgraph "控制器层"
C[authority_v1_menu_list.go]
D[authority_v1_menu_create.go]
E[authority_v1_menu_update.go]
F[authority_v1_menu_delete.go]
end
subgraph "服务层"
G[sys_auth_rule.go]
end
subgraph "数据模型层"
H[sys_auth_rule.go]
I[v_1_sys_auth_rule.go]
end
subgraph "公共组件"
J[common.go]
end
subgraph "权限配置"
K[rbac_model.conf]
end
A --> C
B --> C
C --> G
G --> H
H --> I
J --> A
K --> G
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go)
- [model.go](file://api/authority/v1/model.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
- [common.go](file://api/commonApi/common.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
**Section sources**
- [menu.go](file://api/authority/v1/menu.go)
- [model.go](file://api/authority/v1/model.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
## 核心组件
菜单管理API的核心组件包括菜单的增删改查操作这些操作通过RESTful端点暴露API使用GoFrame框架构建通过结构体标签定义HTTP路由方法和请求参数菜单数据模型支持树形结构允许创建多级菜单体系权限控制基于Casbin实现的RBAC模型确保只有授权用户才能执行相应操作
**Section sources**
- [menu.go](file://api/authority/v1/menu.go)
- [model.go](file://api/authority/v1/model.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
## 架构概述
菜单管理API采用分层架构设计包括API层控制器层服务层和数据访问层API层定义了HTTP端点和数据传输对象DTO控制器层处理请求并调用服务层服务层包含业务逻辑并协调数据访问数据访问层负责与数据库交互整个系统通过RBAC模型进行权限控制确保操作的安全性
```mermaid
graph TD
Client[客户端] --> API[API层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(数据库)]
Service --> Casbin[RBAC权限控制]
Casbin --> rbac_model[rbac_model.conf]
style Client fill:#f9f,stroke:#333
style DB fill:#ccf,stroke:#333
style rbac_model fill:#cfc,stroke:#333
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
## 详细组件分析
### 菜单创建分析
菜单创建功能允许系统管理员创建新的菜单项该功能通过POST请求实现请求体包含菜单的详细信息如名称标题类型路径等系统验证输入数据的完整性后将其持久化到数据库中
#### API端点定义
```mermaid
classDiagram
class MenuCreateReq {
+string path "/auth/menu/create"
+string method "post"
+string summary "创建菜单信息"
+SysAuthRuleReq SysAuthRuleReq
}
class SysAuthRuleReq {
+string name "规则名称"
+string title "规则名称"
+uint PID "父ID"
+uint MenuType "类型 0目录 1菜单 2按钮"
+int Weigh "权重"
+uint IsHide "显示状态"
+string Path "路由地址"
+int IsAdmin "是否管理员独享 1是2.否"
+string Component "组件路径"
}
MenuCreateReq --> SysAuthRuleReq : "包含"
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go#L15-L22)
- [model.go](file://api/authority/v1/model.go#L14-L35)
**Section sources**
- [menu.go](file://api/authority/v1/menu.go#L15-L22)
- [model.go](file://api/authority/v1/model.go#L14-L35)
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
### 菜单更新分析
菜单更新功能允许修改现有菜单项的属性该功能通过POST请求实现需要提供菜单的ID和要更新的字段系统会验证用户权限确保只有授权用户才能修改菜单
#### API端点定义
```mermaid
classDiagram
class MenuUpdateReq {
+string path "/auth/menu/update"
+string method "post"
+string summary "修改菜单信息"
+SysAuthRuleWithID SysAuthRuleWithID
}
class SysAuthRuleWithID {
+SysAuthRuleReq SysAuthRuleReq
+uint ID "ID"
}
class SysAuthRuleReq {
+string name "规则名称"
+string title "规则名称"
+uint PID "父ID"
+uint MenuType "类型 0目录 1菜单 2按钮"
+int Weigh "权重"
+uint IsHide "显示状态"
+string Path "路由地址"
+int IsAdmin "是否管理员独享 1是2.否"
+string Component "组件路径"
}
MenuUpdateReq --> SysAuthRuleWithID : "包含"
SysAuthRuleWithID --> SysAuthRuleReq : "继承"
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go#L24-L31)
- [model.go](file://api/authority/v1/model.go#L29-L35)
**Section sources**
- [menu.go](file://api/authority/v1/menu.go#L24-L31)
- [model.go](file://api/authority/v1/model.go#L29-L35)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
### 菜单删除分析
菜单删除功能允许移除不再需要的菜单项该功能通过DELETE请求实现需要提供要删除的菜单ID系统会检查菜单是否存在子菜单如果有则一并删除
#### API端点定义
```mermaid
classDiagram
class MenuDeleteReq {
+string path "/auth/menu/delete"
+string method "delete"
+string summary "删除菜单信息"
+uint ID "ID"
}
class CommonIntId {
+uint ID "ID"
}
MenuDeleteReq --> CommonIntId : "继承"
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go#L33-L39)
- [common.go](file://api/commonApi/common.go#L6-L8)
**Section sources**
- [menu.go](file://api/authority/v1/menu.go#L33-L39)
- [common.go](file://api/commonApi/common.go#L6-L8)
- [authority_v1_menu_delete.go](file://internal/controller/authority/authority_v1_menu_delete.go)
### 菜单列表获取分析
菜单列表获取功能返回系统中所有菜单的树形结构该功能通过GET请求实现无需请求体返回包含所有菜单及其层级关系的数据
#### API端点定义
```mermaid
classDiagram
class MenuListReq {
+string path "/auth/menu/getList"
+string method "get"
+string summary "获取菜单信息"
}
class MenuListRes {
+CommonDataRes[*SysAuthRule] List
}
class SysAuthRule {
+uint ID
+string name
+string title
+uint MenuType
+int Weigh
+uint IsHide
+string Path
+int IdAdmin
+string Component
+*SysAuthRule[] Children
}
MenuListRes --> SysAuthRule : "包含"
SysAuthRule --> SysAuthRule : "children"
```
**Diagram sources**
- [menu.go](file://api/authority/v1/menu.go#L3-L13)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L3-L10)
**Section sources**
- [menu.go](file://api/authority/v1/menu.go#L3-L13)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L3-L10)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
### RBAC权限模型分析
RBAC基于角色的访问控制模型定义了用户角色和权限之间的关系菜单权限作为系统权限的一部分通过Casbin引擎进行管理该模型确保用户只能访问其角色所允许的菜单项
#### 权限模型配置
```mermaid
graph TD
subgraph "RBAC模型"
Request[请求定义 r = sub, obj, act]
Policy[策略定义 p = sub, obj, act]
Role[角色定义 g = _, _]
Effect[策略效果 e = some(where (p.eft == allow))]
Matcher[匹配器 m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act]
end
Request --> Matcher
Policy --> Matcher
Role --> Matcher
Effect --> Matcher
style Request fill:#f96,stroke:#333
style Policy fill:#f96,stroke:#333
style Role fill:#f96,stroke:#333
style Effect fill:#f96,stroke:#333
style Matcher fill:#6f9,stroke:#333
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
## 依赖分析
菜单管理API的组件之间存在明确的依赖关系API层依赖于公共组件和数据模型控制器层依赖于API定义和服务层服务层依赖于数据模型和实体定义整个系统通过RBAC模型进行权限控制确保操作的安全性
```mermaid
graph LR
commonApi[commonApi] --> api[api/authority/v1]
model[internal/model] --> api
api --> controller[internal/controller/authority]
controller --> service[internal/service]
service --> entity[internal/model/entity]
service --> casbin[resource/casbin]
style commonApi fill:#cfc,stroke:#333
style model fill:#cfc,stroke:#333
style api fill:#cf9,stroke:#333
style controller fill:#9cf,stroke:#333
style service fill:#9cf,stroke:#333
style entity fill:#cfc,stroke:#333
style casbin fill:#cfc,stroke:#333
```
**Diagram sources**
- [common.go](file://api/commonApi/common.go)
- [model.go](file://api/authority/v1/model.go)
- [menu.go](file://api/authority/v1/menu.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
**Section sources**
- [common.go](file://api/commonApi/common.go)
- [model.go](file://api/authority/v1/model.go)
- [menu.go](file://api/authority/v1/menu.go)
- [authority_v1_menu_list.go](file://internal/controller/authority/authority_v1_menu_list.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
## 性能考虑
菜单管理API的性能主要受数据库查询和树形结构构建的影响获取菜单列表时系统需要从数据库加载所有菜单数据并构建树形结构这可能成为性能瓶颈建议对菜单数据进行适当的缓存以减少数据库查询次数同时对于大型菜单体系可以考虑实现分页或懒加载机制
## 故障排除指南
当菜单管理API出现问题时应首先检查请求参数是否正确特别是ID字段是否有效对于创建和更新操作确保所有必填字段都已提供如果遇到权限错误检查用户角色是否具有执行相应操作的权限在删除菜单时如果系统返回错误可能是由于外键约束或其他业务规则限制
**Section sources**
- [authority_v1_menu_create.go](file://internal/controller/authority/authority_v1_menu_create.go)
- [authority_v1_menu_update.go](file://internal/controller/authority/authority_v1_menu_update.go)
- [authority_v1_menu_delete.go](file://internal/controller/authority/authority_v1_menu_delete.go)
## 结论
菜单管理API提供了一套完整的菜单增删改查功能通过清晰的RESTful端点设计和严格的RBAC权限控制确保了系统的安全性和可用性API的设计考虑了可扩展性和性能为前端界面提供了灵活的菜单配置能力通过遵循本文档中的指导开发者可以有效地使用和维护这套API系统

View File

@@ -0,0 +1,257 @@
# 角色管理API
<cite>
**本文档中引用的文件**
- [model.go](file://api/sys_role/v1/model.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go)
- [sys_role_v1_role_delete.go](file://internal/controller/sys_role/sys_role_v1_role_delete.go)
- [sys_role_v1_role_list.go](file://internal/controller/sys_role/sys_role_v1_role_list.go)
- [sys_role_v1_role_get.go](file://internal/controller/sys_role/sys_role_v1_role_get.go)
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go)
- [sys_role.go](file://internal/service/sys_role.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了角色管理API的设计与实现涵盖角色的增删改查操作重点说明了角色在RBAC权限控制模型中的核心作用以及如何通过角色实现细粒度的访问控制文档详细阐述了创建角色更新角色删除角色和获取角色列表等端点的HTTP方法URL模式请求/响应模式和认证机制并提供实际使用示例
## 项目结构
角色管理功能主要分布在API层和内部服务层采用分层架构设计API定义位于`api/sys_role/v1/`目录下控制器实现位于`internal/controller/sys_role/`目录服务接口定义在`internal/service/sys_role.go`实体模型定义在`internal/model/entity/v_1_sys_role.go`
```mermaid
graph TD
A[API层] --> B[Controller层]
B --> C[Service层]
C --> D[DAO层]
D --> E[数据库]
subgraph "API定义"
A1[sys_role.go]
A2[model.go]
end
subgraph "控制器"
B1[sys_role_v1_role_add.go]
B2[sys_role_v1_role_edit.go]
B3[sys_role_v1_role_delete.go]
B4[sys_role_v1_role_list.go]
B5[sys_role_v1_role_get.go]
end
subgraph "服务层"
C1[sys_role.go]
end
subgraph "数据模型"
D1[v_1_sys_role.go]
end
```
**Diagram sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L1-L70)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
- [sys_role.go](file://internal/service/sys_role.go#L1-L48)
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go#L1-L22)
**Section sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L1-L70)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
## 核心组件
角色管理API的核心组件包括角色实体模型API请求/响应结构控制器实现和服务接口系统基于RBAC基于角色的访问控制模型通过角色与权限规则的关联实现细粒度的访问控制每个角色包含名称状态排序备注等基本信息并通过菜单ID列表与具体权限关联
**Section sources**
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go#L1-L22)
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
## 架构概述
系统采用典型的分层架构从上至下分为API层控制器层服务层和数据访问层API层定义了HTTP端点的路由方法和参数结构控制器层处理请求验证和转发服务层包含核心业务逻辑DAO层负责与数据库交互权限控制基于Casbin实现配置文件位于`resource/casbin/rbac_model.conf`
```mermaid
graph TB
subgraph "表现层"
A[HTTP API]
end
subgraph "应用层"
B[Controller]
end
subgraph "业务逻辑层"
C[Service]
end
subgraph "数据访问层"
D[DAO]
E[Casbin]
end
subgraph "数据层"
F[MySQL]
end
A --> B --> C --> D --> F
C --> E
```
**Diagram sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L1-L70)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 详细组件分析
### 角色管理端点分析
角色管理API提供了完整的CRUD操作包括创建读取更新和删除角色所有端点均通过统一的认证机制保护确保只有授权用户才能执行相应操作
#### API端点定义
```mermaid
flowchart TD
A[角色列表] --> |GET /role/list| B[分页查询角色]
C[获取角色参数] --> |GET /role/getParams| D[获取编辑参数]
E[添加角色] --> |POST /role/add| F[创建新角色]
G[获取角色信息] --> |GET /role/get| H[查询单个角色]
I[修改角色] --> |PUT /role/edit| J[更新角色信息]
K[删除角色] --> |DELETE /role/delete| L[批量删除角色]
```
**Diagram sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L10-L70)
#### 请求/响应模型
```mermaid
classDiagram
class RoleListReq {
+string RoleName
+string Status
+CommonPageReq
}
class RoleListRes {
+CommonPageRes[*V1SysRole]
}
class RoleAddReq {
+string Name
+uint Status
+uint ListOrder
+string Remark
+[]uint MenuIds
}
class RoleAddRes {
}
class RoleEditReq {
+int64 Id
+string Name
+uint Status
+uint ListOrder
+string Remark
+[]uint MenuIds
}
class RoleEditRes {
}
class RoleDeleteReq {
+[]int64 Ids
}
class RoleDeleteRes {
}
class V1SysRole {
+uint Id
+uint Status
+uint ListOrder
+string Name
+string Remark
+uint DataScope
+*gtime.Time CreatedAt
+*gtime.Time UpdatedAt
}
RoleListReq --> RoleListRes : "响应"
RoleAddReq --> RoleAddRes : "响应"
RoleEditReq --> RoleEditRes : "响应"
RoleDeleteReq --> RoleDeleteRes : "响应"
RoleListRes --> V1SysRole : "包含"
```
**Diagram sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L10-L70)
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go#L11-L20)
### RBAC权限模型分析
系统采用标准的RBAC基于角色的访问控制模型通过Casbin实现权限控制角色与权限规则通过多对多关系关联实现灵活的权限分配
```mermaid
erDiagram
ROLE ||--o{ ROLE_MENU : "拥有"
ROLE {
uint id PK
string name
uint status
uint list_order
string remark
uint data_scope
datetime created_at
datetime updated_at
}
MENU ||--o{ ROLE_MENU : "被分配给"
MENU {
uint id PK
string name
string path
string component
uint status
}
ROLE_MENU {
uint role_id FK
uint menu_id FK
}
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go#L11-L20)
**Section sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go#L1-L70)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 依赖分析
角色管理功能依赖于多个核心组件包括认证中间件Casbin权限引擎数据库访问层和通用工具库服务层通过接口定义与具体实现解耦便于测试和维护
```mermaid
graph TD
A[角色管理API] --> B[认证中间件]
A --> C[Casbin权限引擎]
A --> D[MySQL数据库]
A --> E[分页工具]
A --> F[参数验证]
A --> G[错误处理]
B --> H[JWT令牌]
C --> I[rbac_model.conf]
D --> J[DAO层]
F --> K[GoFrame验证器]
G --> L[统一错误码]
```
**Diagram sources**
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
**Section sources**
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 性能考虑
角色管理API在设计时考虑了性能优化包括数据库索引优化查询结果缓存和批量操作支持建议在高并发场景下对角色列表接口启用Redis缓存减少数据库压力对于批量删除操作采用事务处理确保数据一致性
## 故障排除指南
常见问题包括权限不足参数验证失败和数据库连接错误系统采用统一的错误处理机制返回标准化的错误码和消息开发人员应检查请求头中的认证令牌请求参数的格式和必填字段以及服务日志中的详细错误信息
**Section sources**
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go#L1-L15)
## 结论
角色管理API提供了完整的角色生命周期管理功能基于RBAC模型实现了灵活的权限控制系统架构清晰分层合理便于维护和扩展通过标准化的API设计和统一的错误处理确保了接口的易用性和可靠性建议在生产环境中启用适当的缓存策略和监控告警以保障系统的稳定运行

View File

@@ -0,0 +1,259 @@
# 渠道管理API
<cite>
**本文档引用文件**
- [entrance.go](file://api/channel/v2/entrance.go)
- [model.go](file://api/channel/v2/model.go)
- [channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go)
- [channel_v2_entrance_update.go](file://internal/controller/channel/channel_v2_entrance_update.go)
- [channel_v2_entrance_delete.go](file://internal/controller/channel/channel_v2_entrance_delete.go)
- [channel_v2_entrance_list.go](file://internal/controller/channel/channel_v2_entrance_list.go)
- [entrance.go](file://internal/systemV2/logic/channel/entrance.go)
- [entrance.go](file://internal/model/entrance.go)
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了渠道管理API的功能涵盖入口管理和渠道配置等核心功能文档全面说明了各个端点的HTTP方法URL模式请求/响应模式和认证机制重点包括入口创建更新删除和查询等接口提供实际使用示例错误处理策略和安全考虑同时解释了渠道管理的实现细节包括渠道路由流量分配和性能监控机制并提供客户端实现指南和性能优化建议
## 项目结构
渠道管理API的实现分布在多个目录中主要功能集中在`api/channel/v2``internal/controller/channel`目录下API定义文件负责声明端点和数据结构而控制器文件则处理具体的业务逻辑
```mermaid
graph TD
subgraph "API层"
A[entrance.go]
B[model.go]
end
subgraph "控制器层"
C[channel_v2_entrance_create.go]
D[channel_v2_entrance_update.go]
E[channel_v2_entrance_delete.go]
F[channel_v2_entrance_list.go]
end
subgraph "业务逻辑层"
G[entrance.go]
end
A --> C
A --> D
A --> E
A --> F
B --> C
B --> D
B --> E
B --> F
C --> G
D --> G
E --> G
F --> G
```
**图示来源**
- [entrance.go](file://api/channel/v2/entrance.go#L1-L47)
- [model.go](file://api/channel/v2/model.go#L1-L39)
- [channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go#L1-L15)
**本节来源**
- [api/channel/v2/entrance.go](file://api/channel/v2/entrance.go)
- [internal/controller/channel/channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go)
## 核心组件
渠道管理API的核心组件包括入口管理的四个主要操作创建更新删除和查询这些操作通过清晰的请求-响应模式实现确保了API的易用性和一致性每个操作都有明确的认证机制和错误处理策略
**本节来源**
- [api/channel/v2/entrance.go](file://api/channel/v2/entrance.go#L10-L42)
- [internal/systemV2/logic/channel/entrance.go](file://internal/systemV2/logic/channel/entrance.go#L49-L68)
## 架构概述
渠道管理API采用分层架构设计从API层到业务逻辑层形成了清晰的调用链API层定义了端点和数据结构控制器层处理HTTP请求并调用业务逻辑而业务逻辑层则与数据访问层交互完成具体操作
```mermaid
graph TB
subgraph "客户端"
Client[客户端应用]
end
subgraph "API网关"
Auth[认证中间件]
end
subgraph "API层"
API[API定义]
end
subgraph "控制器层"
Controller[控制器]
end
subgraph "业务逻辑层"
Service[服务逻辑]
end
subgraph "数据访问层"
DAO[数据访问对象]
end
Client --> Auth
Auth --> API
API --> Controller
Controller --> Service
Service --> DAO
```
**图示来源**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go#L1-L15)
- [entrance.go](file://internal/systemV2/logic/channel/entrance.go#L1-L96)
## 详细组件分析
### 入口管理分析
入口管理功能提供了完整的CRUD操作每个操作都有明确的请求参数和响应结构API设计遵循RESTful原则使用标准的HTTP方法来表示不同的操作类型
#### 对象导向组件
```mermaid
classDiagram
class EntranceListReq {
+string path "/channel/entrance/getList"
+string tags "通道信息"
+string method "get"
+string summary "获取通道信息"
+EntranceParamsReq EntranceParamsReq
}
class EntranceCreateReq {
+string path "/channel/entrance/create"
+string tags "通道信息"
+string method "post"
+string summary "创建通道信息"
+Entrance Entrance
}
class EntranceUpdateReq {
+string path "/channel/entrance/update"
+string tags "通道信息"
+string method "post"
+string summary "修改通道信息"
+CommonStrId CommonStrId
+Entrance Entrance
}
class EntranceDeleteReq {
+string path "/channel/entrance/delete"
+string tags "通道信息"
+string method "delete"
+string summary "删除通道信息"
+CommonStrId CommonStrId
}
class Entrance {
+string Name
+string PayType
+float64 ServiceFee
+float64 TotalLimit
+string AllowedMm
+int StartHour
+int EndHour
+EntranceParams Params
+string Remark
+uint Status
}
class EntranceParams {
+string AppKey
+string AppSecret
}
EntranceListReq --> EntranceParamsReq : "包含"
EntranceCreateReq --> Entrance : "包含"
EntranceUpdateReq --> Entrance : "包含"
EntranceUpdateReq --> CommonStrId : "包含"
EntranceDeleteReq --> CommonStrId : "包含"
Entrance --> EntranceParams : "包含"
```
**图示来源**
- [entrance.go](file://api/channel/v2/entrance.go#L10-L42)
- [model.go](file://api/channel/v2/model.go#L11-L32)
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API网关"
participant Controller as "控制器"
participant Service as "服务逻辑"
participant DAO as "数据访问层"
Client->>API : GET /channel/entrance/getList
API->>API : 认证检查
API->>Controller : 调用EntranceList
Controller->>Service : 调用List方法
Service->>DAO : 查询V2RoadInfo
DAO-->>Service : 返回查询结果
Service-->>Controller : 返回总数量和数据列表
Controller-->>API : 构造响应
API-->>Client : 返回分页结果
Client->>API : POST /channel/entrance/create
API->>API : 认证检查
API->>Controller : 调用EntranceCreate
Controller->>Service : 调用Add方法
Service->>DAO : 保存新通道
DAO-->>Service : 返回操作结果
Service-->>Controller : 返回错误信息
Controller-->>API : 构造响应
API-->>Client : 返回创建结果
```
**图示来源**
- [channel_v2_entrance_list.go](file://internal/controller/channel/channel_v2_entrance_list.go#L1-L29)
- [channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go#L1-L15)
- [entrance.go](file://internal/systemV2/logic/channel/entrance.go#L1-L96)
**本节来源**
- [api/channel/v2/entrance.go](file://api/channel/v2/entrance.go#L1-L47)
- [internal/controller/channel/channel_v2_entrance_create.go](file://internal/controller/channel/channel_v2_entrance_create.go#L1-L15)
- [internal/systemV2/logic/channel/entrance.go](file://internal/systemV2/logic/channel/entrance.go#L1-L96)
## 依赖分析
渠道管理API的各个组件之间存在清晰的依赖关系API层依赖于模型定义控制器层依赖于API定义和业务逻辑服务而业务逻辑层则依赖于数据访问对象来完成数据库操作
```mermaid
graph TD
A[entrance.go] --> B[EntranceListReq]
A --> C[EntranceCreateReq]
A --> D[EntranceUpdateReq]
A --> E[EntranceDeleteReq]
F[model.go] --> G[Entrance]
F --> H[EntranceParams]
F --> I[EntranceParamsReq]
J[channel_v2_entrance_list.go] --> A
J --> F
K[channel_v2_entrance_create.go] --> A
K --> F
L[channel_v2_entrance_update.go] --> A
L --> F
M[channel_v2_entrance_delete.go] --> A
N[entrance.go] --> O[V2RoadInfo]
```
**图示来源**
- [entrance.go](file://api/channel/v2/entrance.go#L1-L47)
- [model.go](file://api/channel/v2/model.go#L1-L39)
- [channel_v2_entrance_list.go](file://internal/controller/channel/channel_v2_entrance_list.go#L1-L29)
**本节来源**
- [api/channel/v2/entrance.go](file://api/channel/v2/entrance.go)
- [api/channel/v2/model.go](file://api/channel/v2/model.go)
- [internal/controller/channel/channel_v2_entrance_list.go](file://internal/controller/channel/channel_v2_entrance_list.go)
## 性能考虑
渠道管理API在设计时考虑了性能因素列表查询操作实现了分页功能避免了一次性加载过多数据所有数据库操作都使用了上下文(Context)来支持超时和取消功能业务逻辑层使用了Try机制来处理事务确保了数据的一致性
## 故障排除指南
当遇到API调用问题时首先检查认证令牌是否有效可以通过调用认证接口获取新的令牌如果出现权限错误请确认用户角色是否有访问该端点的权限对于创建或更新操作失败的情况检查请求体中的必填字段是否完整特别是通道名称支付类型等关键字段
**本节来源**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [user_token.go](file://utility/token/user_token.go#L1-L134)
## 结论
渠道管理API提供了一套完整的入口管理功能通过清晰的分层架构和规范的API设计实现了高效安全的渠道配置管理API的每个端点都有明确的语义和一致的错误处理机制便于客户端集成和使用建议在实际使用中遵循文档中的示例和最佳实践以确保系统的稳定运行

View File

@@ -0,0 +1,181 @@
# 系统监控API
<cite>
**本文档中引用的文件**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [monitor.go](file://api/monitor/monitor.go)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
- [auth.go](file://internal/middleware/auth.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了系统监控API的功能重点介绍健康检查和系统状态监控等核心功能文档涵盖了API端点的HTTP方法URL模式请求/响应模式和认证机制通过实际使用示例错误处理策略和安全考虑全面解释了系统监控的实现细节包括健康检查指标响应时间监控和故障检测机制同时提供客户端实现指南和性能优化建议确保文档与代码库中的实际实现完全一致
## 项目结构
系统监控API位于`api/monitor`目录下包含v1版本的健康检查接口定义控制器实现位于`internal/controller/monitor`目录中遵循GoFrame框架的MVC架构模式该模块与其他系统组件松耦合提供独立的系统健康状态检测功能
```mermaid
flowchart TD
A["api/monitor"] --> B["v1/heathcheck.go"]
C["internal/controller/monitor"] --> D["monitor_v1_health_check.go"]
B --> E["定义HealthCheckReq/Res"]
D --> F["实现HealthCheck方法"]
E --> G["HTTP GET /monitor/heathcheck"]
F --> G
```
**Diagram sources**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
**Section sources**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
## 核心组件
系统监控API的核心组件包括健康检查请求/响应数据结构定义和对应的控制器实现`HealthCheckReq`结构体通过g.Meta标签定义了API端点的路由HTTP方法和元数据`HealthCheckRes`定义了返回的健康状态信息控制器`ControllerV1`实现了`IMonitorV1`接口中的`HealthCheck`方法提供实际的健康检查逻辑
**Section sources**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go#L1-L12)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go#L8-L12)
## 架构概述
系统监控API采用标准的分层架构API定义层与业务逻辑实现层分离API接口定义位于`api/monitor`包中而具体实现位于`internal/controller/monitor`包中这种设计遵循了关注点分离原则使得接口定义可以独立于具体实现进行演进
```mermaid
graph TB
A["客户端"] --> B["HTTP GET /monitor/heathcheck"]
B --> C["路由分发"]
C --> D["monitor.ControllerV1.HealthCheck"]
D --> E["返回 {ok: true}"]
E --> F["JSON响应"]
F --> A
```
**Diagram sources**
- [monitor.go](file://api/monitor/monitor.go)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
## 详细组件分析
### 健康检查组件分析
健康检查组件提供了一个简单的端点来验证系统的基本可用性该组件的设计旨在快速响应不依赖于任何外部资源或数据库连接确保即使在系统部分故障的情况下也能提供基本的健康状态信息
#### API接口定义
```mermaid
classDiagram
class HealthCheckReq {
+g.Meta path : "/monitor/heathcheck"
+tags : "监控信息"
+method : "get"
+summary : "健康检查"
}
class HealthCheckRes {
+Ok bool
}
HealthCheckReq --> HealthCheckRes : "返回"
```
**Diagram sources**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go#L6-L12)
#### 控制器实现
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Router as "路由器"
participant Controller as "ControllerV1"
Client->>Router : GET /monitor/heathcheck
Router->>Controller : 调用HealthCheck方法
Controller-->>Router : 返回{ok : true}
Router-->>Client : 200 OK + JSON
Note over Controller : 始终返回成功状态<br/>不执行实际检查
```
**Diagram sources**
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go#L8-L12)
**Section sources**
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
### 认证机制分析
虽然健康检查端点通常不需要认证但系统整体的API访问受认证中间件保护`LoginOrIframeAuth`中间件处理不同来源的认证请求支持登录认证和iframe嵌入场景的认证
```mermaid
flowchart TD
A["API请求"] --> B{"路径在白名单?"}
B --> |是| C["直接通过"]
B --> |否| D["检查tokenFrom头"]
D --> E{"tokenFrom=login?"}
E --> |是| F["执行loginAuth"]
E --> |否| G{"tokenFrom=iframe?"}
G --> |是| H["执行iFrameAuth"]
G --> |否| I["返回错误"]
F --> J{"认证成功?"}
H --> K{"认证成功?"}
J --> |是| L["继续处理"]
K --> |是| L
J --> |否| M["返回认证错误"]
K --> |否| M
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
**Section sources**
- [auth.go](file://internal/middleware/auth.go)
## 依赖分析
系统监控模块具有较低的外部依赖性主要依赖于GoFrame框架的基础组件通过接口定义与实现分离的设计该模块可以轻松地被替换或扩展而不会影响系统的其他部分
```mermaid
graph LR
A["monitor模块"] --> B["github.com/gogf/gf/v2"]
A --> C["kami/api/monitor/v1"]
A --> D["context"]
B --> E["g.Meta"]
B --> F["ghttp"]
C --> G["HealthCheckReq/Res"]
```
**Diagram sources**
- [monitor.go](file://api/monitor/monitor.go)
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
**Section sources**
- [monitor.go](file://api/monitor/monitor.go)
- [heathcheck.go](file://api/monitor/v1/heathcheck.go)
## 性能考虑
健康检查端点设计为轻量级操作不涉及数据库查询或外部服务调用确保极低的响应延迟由于其简单性该端点可以承受高频率的调用适合作为负载均衡器和容器编排系统的健康探针
## 故障排除指南
当健康检查API返回非200状态码时可能的原因包括
- 服务未启动或崩溃
- 网络连接问题
- 反向代理配置错误
建议的排查步骤
1. 检查服务进程是否正在运行
2. 验证网络连接和防火墙设置
3. 查看应用日志以获取错误信息
4. 确认路由配置是否正确
**Section sources**
- [monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
- [auth.go](file://internal/middleware/auth.go)
## 结论
系统监控API提供了简单而有效的健康检查功能通过标准化的RESTful接口返回系统的基本可用性状态该实现遵循了微服务架构的最佳实践具有低耦合高内聚的特点尽管当前实现仅返回静态的健康状态但其设计为未来的扩展留下了空间可以轻松地集成更复杂的系统指标检查

View File

@@ -0,0 +1,167 @@
# 订单日志管理
<cite>
**本文档引用的文件**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
- [v_2_order_notify_log.go](file://internal/systemV2/dao/internal/v_2_order_notify_log.go)
- [common.go](file://api/commonApi/common.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了订单日志管理API的功能重点涵盖订单日志的查询和删除功能文档说明了`GET /api/v1/order/log/getList``DELETE /api/v1/order/log/delete`端点的HTTP方法URL模式请求/响应模式和认证机制同时文档还解释了订单日志在系统审计问题排查和业务分析中的作用以及与其他订单组件的集成方式
## 项目结构
订单日志管理功能主要分布在API层和控制器层相关文件位于`api/order/v1/``internal/controller/order/`目录下数据访问对象DAO定义在`internal/systemV2/dao/internal/`目录中用于与数据库交互
```mermaid
graph TB
subgraph "API层"
A[log.go]
end
subgraph "控制器层"
B[order_v1_order_log_list.go]
C[order_v1_order_log_delete.go]
end
subgraph "数据访问层"
D[v_2_order_notify_log.go]
end
A --> B
A --> C
B --> D
C --> D
```
**图示来源**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
- [v_2_order_notify_log.go](file://internal/systemV2/dao/internal/v_2_order_notify_log.go)
**节来源**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
## 核心组件
订单日志管理的核心组件包括日志查询和删除两个功能模块查询功能通过`OrderLogList`接口实现删除功能通过`OrderLogDelete`接口实现这两个接口目前均返回未实现错误表明功能尚在开发中
**节来源**
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go#L1-L13)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go#L1-L13)
## 架构概述
订单日志管理模块采用典型的三层架构API层定义接口控制器层处理业务逻辑数据访问层负责与数据库交互API层通过GoFrame框架的元数据注解定义了HTTP方法和路径控制器层调用数据访问层的方法来执行具体的数据库操作
```mermaid
graph TD
A[客户端] --> B[API层]
B --> C[控制器层]
C --> D[数据访问层]
D --> E[数据库]
```
**图示来源**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
- [v_2_order_notify_log.go](file://internal/systemV2/dao/internal/v_2_order_notify_log.go)
## 详细组件分析
### 订单日志查询分析
订单日志查询功能通过`GET /api/v1/order/log/getList`端点实现请求参数继承自`CommonPageReq`包含分页信息响应结构为空表明需要进一步实现
#### 请求结构
```mermaid
classDiagram
class OrderLogListReq {
+string path "/order/log/getList"
+string method "get"
+string summary "获取订单流水"
+int Current
+int PageSize
}
class CommonPageReq {
+int Current
+int PageSize
}
OrderLogListReq --> CommonPageReq : "继承"
```
**图示来源**
- [log.go](file://api/order/v1/log.go#L6-L10)
**节来源**
- [log.go](file://api/order/v1/log.go#L6-L10)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go#L1-L13)
### 订单日志删除分析
订单日志删除功能通过`DELETE /api/v1/order/log/delete`端点实现请求参数继承自`CommonIntId`包含要删除的日志ID响应结构为空表明需要进一步实现
#### 请求结构
```mermaid
classDiagram
class OrderLogDeleteReq {
+string path "/order/log/delete"
+string method "delete"
+string summary "删除订单流水"
+uint ID
}
class CommonIntId {
+uint ID
}
OrderLogDeleteReq --> CommonIntId : "继承"
```
**图示来源**
- [log.go](file://api/order/v1/log.go#L16-L20)
**节来源**
- [log.go](file://api/order/v1/log.go#L16-L20)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go#L1-L13)
## 依赖分析
订单日志管理模块依赖于`commonApi`模块中的分页和ID参数定义以及`systemV2`模块中的数据访问对象这些依赖关系通过Go语言的包导入机制实现
```mermaid
graph TD
A[订单日志管理] --> B[commonApi]
A --> C[systemV2]
B --> D[CommonPageReq]
B --> E[CommonIntId]
C --> F[V2OrderNotifyLogDao]
```
**图示来源**
- [log.go](file://api/order/v1/log.go)
- [v_2_order_notify_log.go](file://internal/systemV2/dao/internal/v_2_order_notify_log.go)
**节来源**
- [log.go](file://api/order/v1/log.go)
- [v_2_order_notify_log.go](file://internal/systemV2/dao/internal/v_2_order_notify_log.go)
## 性能考虑
由于订单日志查询功能涉及分页建议合理设置分页大小以避免对数据库造成过大压力同时删除操作应谨慎使用避免误删重要日志数据
## 故障排除指南
当前订单日志管理功能尚未实现调用相关接口将返回未实现错误开发者需要完成控制器层的业务逻辑实现并确保数据访问层的正确性
**节来源**
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go#L12-L13)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go#L12-L13)
## 结论
订单日志管理模块为系统提供了重要的审计和监控能力尽管当前功能尚未实现但其架构设计清晰依赖关系明确后续开发应重点关注查询和删除功能的实现确保日志数据的安全性和可用性

View File

@@ -0,0 +1,198 @@
# 订单汇总统计
<cite>
**本文档中引用的文件**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go)
- [order_info.go](file://internal/model/order_info.go)
- [merchant_order.go](file://internal/service/merchant_order.go)
- [handler.go](file://internal/errHandler/handler.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心组件](#核心组件)
3. [API端点说明](#api端点说明)
4. [数据结构定义](#数据结构定义)
5. [查询条件与统计维度](#查询条件与统计维度)
6. [认证机制](#认证机制)
7. [使用示例](#使用示例)
8. [计算逻辑与数据一致性](#计算逻辑与数据一致性)
9. [性能优化建议](#性能优化建议)
10. [监控与业务分析作用](#监控与业务分析作用)
## 简介
本文档详细描述了订单汇总统计API的功能与使用方法重点涵盖两个核心端点`GET /api/v1/order/summary/get/list` `GET /api/v1/order/summary/daily/get/list`该API用于获取订单的总体统计信息和每日趋势数据支持按商户通道日期等多维度进行聚合分析广泛应用于业务报表生成运营状况监控和财务对账等场景
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
## 核心组件
订单汇总统计功能由控制器服务层和数据模型三层构成控制器负责接收HTTP请求并进行参数校验服务层实现具体的业务逻辑和数据库查询数据模型定义了输入输出的数据结构整个流程通过依赖注入机制解耦确保代码的可维护性和可测试性
```mermaid
graph TD
A[客户端] --> B[ControllerV1.OrderSummaryGetList]
B --> C[service.OrderSummary().GetList]
C --> D[model.OrderSummaryListInput]
C --> E[model.OrderSummaryListOutput]
F[客户端] --> G[ControllerV1.OrderSummaryDailyGetList]
G --> H[service.OrderSummary().GetDailyStats]
H --> I[model.OrderSummaryDailyListInput]
H --> J[model.OrderSummaryDailyListOutput]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#bbf,stroke:#333
style D fill:#9f9,stroke:#333
style E fill:#9f9,stroke:#333
style F fill:#f9f,stroke:#333
style G fill:#bbf,stroke:#333
style H fill:#bbf,stroke:#333
style I fill:#9f9,stroke:#333
style J fill:#9f9,stroke:#333
```
**Diagram sources**
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go#L1-L58)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go#L1-L61)
- [merchant_order.go](file://internal/service/merchant_order.go#L17-L26)
**Section sources**
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go#L1-L58)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go#L1-L61)
## API端点说明
### 总体订单汇总端点
- **HTTP方法**: GET
- **URL模式**: `/api/v1/order/summary/get/list`
- **功能描述**: 获取订单的总体汇总数据按商户维度聚合统计
- **认证要求**: 需要有效的用户会话和权限验证
### 每日订单汇总端点
- **HTTP方法**: GET
- **URL模式**: `/api/v1/order/summary/daily/get/list`
- **功能描述**: 获取订单的每日统计趋势数据支持按日期范围查询
- **认证要求**: 需要有效的用户会话和权限验证
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
## 数据结构定义
### 订单汇总记录OrderSummaryRecord
| 字段名 | 类型 | 描述 |
|--------|------|------|
| merchantUid | string | 商户唯一标识 |
| merchantName | string | 商户名称 |
| succeedCount | int64 | 成功订单数量 |
| totalCount | int64 | 订单总量 |
| failedCount | int64 | 失败订单数量 |
| waitedCount | int64 | 创建但未填写的订单数量 |
| succeedShowAmount | float64 | 成功订单展示金额 |
| totalShowAmount | float64 | 订单总展示金额 |
| succeedFactAmount | float64 | 成功订单实际金额 |
| totalFactAmount | float64 | 订单总实际金额 |
| rate | float64 | 成功率百分比 |
| date | string | 统计日期 |
### 每日订单汇总记录OrderSummaryDailyRecord
在基础汇总记录的基础上增加了通道信息
- **roadUid**: 通道唯一标识
- **roadName**: 通道名称
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
- [order_info.go](file://internal/model/order_info.go#L1-L24)
## 查询条件与统计维度
### 总体汇总查询参数
- **roadUid**: 按指定通道筛选
- **date**: 按指定日期查询
- **分页参数**: 支持标准分页page, limit
### 每日汇总查询参数
- **roadUid[]**: 按多个通道筛选数组
- **dateRange[]**: 按日期范围查询起止时间数组
- **merchantUid[]**: 按多个商户筛选数组
统计维度包括
- 按商户聚合
- 按通道聚合
- 按日趋势分析
- 多维度交叉统计
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
## 认证机制
API采用基于上下文的认证机制通过`service.SysAuth().LoginWithEverything``LoginWithIFrameAndLogin`方法验证用户身份和权限请求必须携带有效的认证令牌系统会自动提取用户ID和登录类型用于数据权限控制未通过认证的请求将返回401状态码
**Section sources**
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go#L1-L58)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go#L1-L61)
## 使用示例
### 获取某商户的总体统计
```http
GET /api/v1/order/summary/get/list?merchantUid=MER123&date=2024-01-15
Authorization: Bearer <token>
```
### 获取多商户多通道的每日趋势
```http
GET /api/v1/order/summary/daily/get/list?roadUid[]=R1&roadUid[]=R2&merchantUid[]=M1&merchantUid[]=M2&dateRange[]=2024-01-01&dateRange[]=2024-01-31
Authorization: Bearer <token>
```
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
## 计算逻辑与数据一致性
汇总数据基于订单状态实时计算成功率通过`成功订单数/总订单数`公式得出金额统计包含展示金额和实际金额两个维度数据更新频率为实时每次查询都会从数据库获取最新状态系统通过事务机制保证数据一致性避免统计过程中的脏读问题错误处理采用统一的包装机制确保异常信息的标准化输出
```mermaid
flowchart TD
Start([开始]) --> Validate["验证请求参数"]
Validate --> Auth["认证用户权限"]
Auth --> Query["查询订单数据"]
Query --> Calc["计算统计指标"]
Calc --> Format["格式化输出结果"]
Format --> End([返回响应])
Query --> |失败| HandleError["处理数据库错误"]
HandleError --> WrapError["包装错误信息"]
WrapError --> End
```
**Diagram sources**
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go#L1-L58)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go#L1-L61)
- [handler.go](file://internal/errHandler/handler.go#L1-L10)
**Section sources**
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go#L1-L58)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go#L1-L61)
## 性能优化建议
1. **合理使用缓存**: 对于频繁查询但变化不频繁的数据建议在客户端或中间层添加缓存
2. **避免高频查询**: 不要以过高频率调用汇总接口建议最小间隔不低于5分钟
3. **精确查询条件**: 尽量指定具体的商户通道和日期范围减少数据扫描量
4. **分页处理**: 对于大量数据使用分页参数避免单次返回过多记录
5. **批量查询**: 当需要多个维度数据时优先使用支持数组参数的接口减少请求数量
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)
## 监控与业务分析作用
该接口在系统监控和业务分析中扮演关键角色
- **健康状况监控**: 通过每日趋势分析及时发现订单量异常波动
- **业务运营分析**: 支持按商户通道多维度分析交易表现
- **财务对账**: 提供准确的订单统计和金额汇总便于财务核对
- **决策支持**: 基于历史数据趋势为业务决策提供数据支持
- **问题排查**: 当出现交易异常时可快速定位受影响的商户或通道
**Section sources**
- [order_summary.go](file://api/order/v1/order_summary.go#L1-L62)

View File

@@ -0,0 +1,269 @@
# 订单管理API
<cite>
**本文档引用的文件**
- [form.go](file://api/order/v1/form.go)
- [log.go](file://api/order/v1/log.go)
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order.go](file://api/order/order.go)
- [order_new.go](file://internal/controller/order/order_new.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_form_update.go](file://internal/controller/order/order_v1_order_form_update.go)
- [order_v1_order_form_delete.go](file://internal/controller/order/order_v1_order_form_delete.go)
- [order_v1_order_form_list.go](file://internal/controller/order/order_v1_order_form_list.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go)
- [order_info.go](file://internal/model/order_info.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
订单管理API提供了一套完整的订单生命周期管理功能包括订单创建查询历史记录和汇总统计等核心功能该API系统支持多商户多渠道的订单处理实现了订单表单管理订单日志记录和订单汇总统计等功能系统采用GoFrame框架构建通过RESTful接口提供服务确保了高可用性和可扩展性API设计遵循清晰的认证机制和错误处理策略为客户端提供了稳定可靠的接口服务
## 项目结构
订单管理API的项目结构遵循分层设计原则将API定义控制器逻辑业务服务和数据访问层分离API接口定义位于`api/order/v1`目录下控制器实现位于`internal/controller/order`目录中业务逻辑处理在`internal/logic/merchant_order`包内数据模型定义在`internal/model`包中这种分层结构确保了代码的可维护性和可测试性同时通过GoFrame框架的代码生成工具保持了接口定义与实现的一致性
```mermaid
graph TB
subgraph "API层"
A[form.go]
B[log.go]
C[order_summary.go]
end
subgraph "控制器层"
D[order_new.go]
E[order_v1_*.go]
end
subgraph "业务逻辑层"
F[order-summary.go]
end
subgraph "数据模型层"
G[order_info.go]
end
A --> D
B --> D
C --> D
D --> F
F --> G
```
**图示来源**
- [form.go](file://api/order/v1/form.go)
- [log.go](file://api/order/v1/log.go)
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order_new.go](file://internal/controller/order/order_new.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
- [order_info.go](file://internal/model/order_info.go)
**本节来源**
- [form.go](file://api/order/v1/form.go)
- [order_new.go](file://internal/controller/order/order_new.go)
## 核心组件
订单管理API的核心组件包括订单表单管理订单日志管理和订单汇总统计三大功能模块订单表单管理提供订单的创建更新删除和查询接口支持实时订单的全生命周期管理订单日志管理记录订单操作历史提供日志查询和删除功能订单汇总统计模块则提供多维度的订单数据分析包括按日期商户和渠道的订单统计所有组件通过统一的认证机制保护确保数据安全
**本节来源**
- [order.go](file://api/order/order.go)
- [form.go](file://api/order/v1/form.go)
- [log.go](file://api/order/v1/log.go)
- [order_summary.go](file://api/order/v1/order_summary.go)
## 架构概述
订单管理API采用典型的分层架构从上到下分为API接口层控制器层业务逻辑层和数据模型层API接口层定义了所有可用的RESTful端点使用GoFrame的元数据注解指定HTTP方法URL路径和请求/响应模式控制器层实现API接口处理请求参数验证和认证检查业务逻辑层包含核心的订单处理逻辑如汇总统计计算数据模型层定义了与数据库交互的数据结构和查询方法各层之间通过清晰的接口契约进行通信确保了系统的模块化和可维护性
```mermaid
graph TD
Client[客户端] --> API[API接口层]
API --> Controller[控制器层]
Controller --> Service[业务逻辑层]
Service --> Model[数据模型层]
Model --> Database[(数据库)]
style Client fill:#f9f,stroke:#333
style Database fill:#ccf,stroke:#333
```
**图示来源**
- [order.go](file://api/order/order.go)
- [order_new.go](file://internal/controller/order/order_new.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
- [order_info.go](file://internal/model/order_info.go)
## 详细组件分析
### 订单表单管理分析
订单表单管理组件提供实时订单的CRUD操作包括创建查询更新和删除功能该组件通过`OrderFormCreate``OrderFormList``OrderFormUpdate``OrderFormDelete`四个主要接口实现所有接口均受认证保护确保只有授权用户才能操作订单数据接口设计遵循RESTful原则使用标准的HTTP方法对应相应的操作类型
#### 对象导向组件
```mermaid
classDiagram
class OrderFormCreateReq {
+string path : "/order/orderForm/create"
+string tags : "实时订单"
+string method : "post"
+string summary : "创建实时订单"
}
class OrderFormListReq {
+string path : "/order/orderForm/getList"
+string tags : "实时订单"
+string method : "get"
+string summary : "获取实时订单"
+CommonPageReq pagination
}
class OrderFormUpdateReq {
+string path : "/order/orderForm/update"
+string tags : "实时订单"
+string method : "post"
+string summary : "修改实时订单"
+int id
}
class OrderFormDeleteReq {
+string path : "/order/orderForm/delete"
+string tags : "实时订单"
+string method : "delete"
+string summary : "删除实时订单"
+int id
}
OrderFormCreateReq : +OrderFormCreateRes execute(Context, Request)
OrderFormListReq : +OrderFormListRes execute(Context, Request)
OrderFormUpdateReq : +OrderFormUpdateRes execute(Context, Request)
OrderFormDeleteReq : +OrderFormDeleteRes execute(Context, Request)
```
**图示来源**
- [form.go](file://api/order/v1/form.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_form_list.go](file://internal/controller/order/order_v1_order_form_list.go)
- [order_v1_order_form_update.go](file://internal/controller/order/order_v1_order_form_update.go)
- [order_v1_order_form_delete.go](file://internal/controller/order/order_v1_order_form_delete.go)
**本节来源**
- [form.go](file://api/order/v1/form.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_form_list.go](file://internal/controller/order/order_v1_order_form_list.go)
### 订单日志管理分析
订单日志管理组件负责记录和查询订单操作历史提供审计和故障排查功能该组件通过`OrderLogList``OrderLogDelete`两个接口实现日志的查询和清理功能日志查询支持分页便于处理大量日志数据所有日志操作均需通过身份验证确保日志数据的安全性
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "OrderController"
participant Service as "OrderService"
participant Model as "OrderModel"
Client->>Controller : GET /order/log/getList
Controller->>Controller : 验证用户权限
Controller->>Service : 调用OrderLogList
Service->>Model : 查询日志数据
Model-->>Service : 返回日志记录
Service-->>Controller : 返回结果
Controller-->>Client : 返回分页日志列表
Client->>Controller : DELETE /order/log/delete
Controller->>Controller : 验证用户权限
Controller->>Service : 调用OrderLogDelete
Service->>Model : 删除指定日志
Model-->>Service : 返回删除结果
Service-->>Controller : 返回响应
Controller-->>Client : 返回删除成功
```
**图示来源**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_log_delete.go](file://internal/controller/order/order_v1_order_log_delete.go)
**本节来源**
- [log.go](file://api/order/v1/log.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
### 订单汇总统计分析
订单汇总统计组件提供多维度的订单数据分析功能支持按日期商户和渠道进行订单统计该组件通过`OrderSummaryGetList``OrderSummaryDailyGetList`两个主要接口提供汇总数据查询服务统计结果包括成功订单数失败订单数等待订单数以及相应的金额统计为业务决策提供数据支持
#### 复杂逻辑组件
```mermaid
flowchart TD
Start([开始]) --> AuthCheck["身份验证"]
AuthCheck --> AuthValid{"验证通过?"}
AuthValid --> |否| ReturnError["返回未授权错误"]
AuthValid --> |是| ParamCheck["参数验证"]
ParamCheck --> SummaryType{"统计类型?"}
SummaryType --> |普通汇总| DailySummary["按日汇总统计"]
SummaryType --> |每日汇总| RangeSummary["按日期范围汇总"]
DailySummary --> QueryBuilder["构建数据库查询"]
RangeSummary --> QueryBuilder
QueryBuilder --> SQLQuery["执行SQL查询"]
SQLQuery --> DataProcess["处理原始数据"]
DataProcess --> RateCalc["计算成功率"]
RateCalc --> AmountRound["金额四舍五入"]
AmountRound --> ReturnResult["返回格式化结果"]
ReturnError --> End([结束])
ReturnResult --> End
```
**图示来源**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
**本节来源**
- [order_summary.go](file://api/order/v1/order_summary.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [order_v1_order_summary_daily_get_list.go](file://internal/controller/order/order_v1_order_summary_daily_get_list.go)
## 依赖分析
订单管理API的组件间依赖关系清晰明确API接口层依赖于`commonApi`包中的通用数据结构如分页参数和响应格式控制器层依赖于`service`包中的业务服务特别是`SysAuth`服务用于认证检查业务逻辑层依赖于`dao`包中的数据访问对象和`config`包中的配置管理所有组件都依赖于GoFrame框架的核心功能如上下文管理错误处理和数据库操作这种依赖关系确保了组件间的松耦合便于单独测试和维护
```mermaid
graph LR
A[order API] --> B[commonApi]
C[OrderController] --> D[SysAuth Service]
C --> E[OrderSummary Service]
F[OrderSummary Logic] --> G[V1OrderInfo DAO]
F --> H[Config]
I[GoFrame Framework] --> C
I --> F
I --> G
style A fill:#f96,stroke:#333
style C fill:#69f,stroke:#333
style F fill:#6f9,stroke:#333
```
**图示来源**
- [order.go](file://api/order/order.go)
- [order_new.go](file://internal/controller/order/order_new.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
- [order_info.go](file://internal/model/order_info.go)
**本节来源**
- [order.go](file://api/order/order.go)
- [order_new.go](file://internal/controller/order/order_new.go)
- [order-summary.go](file://internal/logic/merchant_order/order-summary.go)
## 性能考虑
订单管理API在设计时考虑了性能优化对于订单汇总统计等复杂查询系统使用数据库聚合函数在数据库层面进行计算避免了大量数据传输到应用层处理分页查询支持限制返回结果数量防止一次性加载过多数据导致内存溢出对于高频访问的统计接口建议实现缓存机制将计算结果缓存一段时间减少数据库压力同时所有数据库查询都应确保相关字段有适当的索引特别是`CreateTime``MerchantUid``RoadUid`等常用查询条件字段
## 故障排除指南
当订单管理API出现问题时应首先检查认证信息是否正确确保请求包含有效的身份验证令牌对于返回500错误的情况应查看服务器日志中的详细错误信息特别是数据库操作错误如果查询性能低下应检查相关数据库表的索引是否完整必要时添加复合索引对于汇总统计接口返回空结果的情况应验证查询参数是否正确特别是日期格式是否符合要求所有API调用都应处理可能的错误响应实现适当的重试机制和错误提示
**本节来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [errHandler/handler.go](file://internal/errHandler/handler.go)
## 结论
订单管理API提供了一套完整且安全的订单管理解决方案涵盖了订单创建查询日志和统计等核心功能系统架构清晰分层合理便于维护和扩展通过严格的认证机制和错误处理策略确保了数据的安全性和系统的稳定性建议在生产环境中为高频访问的汇总统计接口添加缓存层并定期优化数据库索引以进一步提升系统性能未来可以考虑增加Webhook通知功能当订单状态发生变化时主动通知商户系统

View File

@@ -0,0 +1,157 @@
# 订单表单管理
<cite>
**本文档中引用的文件**
- [form.go](file://api/order/v1/form.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_form_update.go](file://internal/controller/order/order_v1_order_form_update.go)
- [order_v1_order_form_list.go](file://internal/controller/order/order_v1_order_form_list.go)
- [order_v1_order_form_delete.go](file://internal/controller/order/order_v1_order_form_delete.go)
- [v_1_order_info.go](file://internal/dao/v_1_order_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [API端点说明](#api端点说明)
3. [数据结构定义](#数据结构定义)
4. [业务逻辑与状态约束](#业务逻辑与状态约束)
5. [使用示例](#使用示例)
6. [错误处理策略](#错误处理策略)
7. [安全考虑](#安全考虑)
8. [性能优化建议](#性能优化建议)
9. [与其他模块的关系](#与其他模块的关系)
10. [结论](#结论)
## 简介
本文档详细描述了订单表单管理API的设计与实现涵盖订单表单的创建更新查询和删除等核心操作该功能位于系统订单模块中通过RESTful接口提供服务支持实时订单的全生命周期管理当前实现中各接口已定义但尚未完成具体业务逻辑返回未实现错误
## API端点说明
### 创建订单表单
- **端点**: `POST /api/v1/order/form/create`
- **功能**: 创建新的订单表单
- **认证机制**: 需要有效的用户身份令牌JWT
- **状态**: 接口已定义但逻辑未实现返回 `CodeNotImplemented` 错误
**节来源**
- [form.go](file://api/order/v1/form.go#L14-L17)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go#L11-L13)
### 更新订单表单
- **端点**: `PUT /api/v1/order/form/update`
- **功能**: 修改现有订单表单信息
- **认证机制**: 需要有效的用户身份令牌JWT
- **状态**: 接口已定义但逻辑未实现返回 `CodeNotImplemented` 错误
**节来源**
- [form.go](file://api/order/v1/form.go#L19-L22)
- [order_v1_order_form_update.go](file://internal/controller/order/order_v1_order_form_update.go#L11-L13)
### 查询订单表单列表
- **端点**: `GET /api/v1/order/form/list`
- **功能**: 获取订单表单分页列表
- **参数**: 支持分页参数如页码每页数量
- **认证机制**: 需要有效的用户身份令牌JWT
- **状态**: 接口已定义但逻辑未实现返回 `CodeNotImplemented` 错误
**节来源**
- [form.go](file://api/order/v1/form.go#L3-L8)
- [order_v1_order_form_list.go](file://internal/controller/order/order_v1_order_form_list.go#L11-L13)
### 删除订单表单
- **端点**: `DELETE /api/v1/order/form/delete`
- **功能**: 删除指定ID的订单表单
- **认证机制**: 需要有效的用户身份令牌JWT
- **状态**: 接口已定义但逻辑未实现返回 `CodeNotImplemented` 错误
**节来源**
- [form.go](file://api/order/v1/form.go#L29-L32)
- [order_v1_order_form_delete.go](file://internal/controller/order/order_v1_order_form_delete.go#L11-L13)
## 数据结构定义
### 订单表单请求结构
- `OrderFormCreateReq`: 创建请求无具体字段定义
- `OrderFormUpdateReq`: 更新请求包含通用整型ID`CommonIntId`
- `OrderFormListReq`: 查询请求继承分页参数`CommonPageReq`
- `OrderFormDeleteReq`: 删除请求包含通用整型ID`CommonIntId`
### 响应结构
所有响应结构`OrderFormCreateRes`, `OrderFormUpdateRes`, `OrderFormListRes`, `OrderFormDeleteRes`均为空结构体仅声明JSON内容类型
### 数据库映射
订单信息由 `v_1_order_info.go` 中的DAO对象管理对应数据库表 `order_info`通过GoFrame框架自动生成基础操作接口
**节来源**
- [form.go](file://api/order/v1/form.go#L3-L34)
- [v_1_order_info.go](file://internal/dao/v_1_order_info.go#L1-L27)
## 业务逻辑与状态约束
当前代码中未实现具体的业务逻辑字段验证规则或状态转换机制所有操作均返回未实现错误建议后续开发中补充以下约束
- 字段验证确保必填字段非空数值字段符合范围
- 权限控制验证用户是否有权操作目标订单
- 状态机定义订单表单的有效状态及转换规则草稿 已提交 已完成
- 幂等性确保创建和更新操作的幂等处理
**节来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go#L11-L13)
- [order_v1_order_form_update.go](file://internal/controller/order/order_v1_order_form_update.go#L11-L13)
## 使用示例
由于接口尚未实现以下为预期使用模式
### 成功场景预期
```http
POST /api/v1/order/form/create
Authorization: Bearer <token>
Content-Type: application/json
{
"field1": "value1",
"field2": "value2"
}
```
**预期响应**: `200 OK` + 创建成功的订单信息
### 失败场景
```http
POST /api/v1/order/form/create
Authorization: Bearer <invalid_token>
```
**实际响应**: `500 Internal Server Error` + `CodeNotImplemented`
**节来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go#L11-L13)
## 错误处理策略
当前系统使用GoFrame框架的错误处理机制
- 统一返回 `gerror.NewCode(gcode.CodeNotImplemented)` 表示功能未完成
- 建议后续实现中使用不同错误码区分验证失败权限不足资源不存在等情况
- 所有错误应通过中间件统一捕获并格式化为标准JSON响应
**节来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go#L12-L13)
## 安全考虑
- 所有订单操作需通过身份认证中间件校验JWT令牌
- 建议增加CSRF防护和请求频率限制可通过 `utility/limiter` 模块实现
- 敏感操作应记录审计日志
- 输入参数需进行严格验证防止注入攻击
## 性能优化建议
- 利用GoFrame ORM的缓存机制减少数据库查询
- 对列表查询添加适当索引如按用户ID创建时间
- 考虑使用Redis缓存热点数据
- 批量操作应使用事务确保一致性
## 与其他模块的关系
订单表单作为核心业务实体应与以下模块交互
- **订单日志**每次状态变更应记录到日志模块
- **订单汇总**成功订单应计入日汇总和总览统计
- **支付系统**订单状态可能触发支付流程
- **通知服务**关键状态变更应发送通知
当前代码中尚未建立这些关联
## 结论
订单表单管理API的接口定义已完成但具体实现尚为空建议优先完成核心CRUD逻辑再逐步添加验证权限日志等企业级特性整体架构基于GoFrame框架具有良好的扩展性和一致性

View File

@@ -0,0 +1,262 @@
# 资金流水
<cite>
**本文档中引用的文件**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund_v1_menu_log_list.go](file://internal/controller/fund/fund_v1_menu_log_list.go)
- [fund_v1_menu_log_create.go](file://internal/controller/fund/fund_v1_menu_log_create.go)
- [fund_v1_menu_log_update.go](file://internal/controller/fund/fund_v1_menu_log_update.go)
- [fund_v1_menu_log_delete.go](file://internal/controller/fund/fund_v1_menu_log_delete.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
- [v_1_sys_user_payment_records.go](file://internal/dao/v_1_sys_user_payment_records.go)
- [V1SysUserPaymentRecords.go](file://internal/model/do/v_1_sys_user_payment_records.go)
- [V1SysUserPaymentRecords.go](file://internal/model/entity/v_1_sys_user_payment_records.go)
- [SysUserPaymentRecordInput.go](file://internal/model/sys_user_payment_record.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了资金流水API的实现涵盖资金流水记录的创建查询更新和删除等操作文档详细说明了每个端点的HTTP方法URL模式请求/响应模式和认证机制同时文档还解释了资金流水的实现细节包括流水号生成规则对账机制和数据一致性保障并提供客户端实现指南和性能优化建议
## 项目结构
资金流水功能主要位于`api/fund/v1`目录下相关控制器位于`internal/controller/fund`目录服务逻辑位于`internal/service``internal/logic`目录数据访问对象DAO和模型定义位于`internal/dao``internal/model`目录
```mermaid
graph TB
subgraph "API 层"
A[wallet_log.go]
end
subgraph "控制器层"
B[fund_v1_menu_log_list.go]
C[fund_v1_menu_log_create.go]
D[fund_v1_menu_log_update.go]
E[fund_v1_menu_log_delete.go]
end
subgraph "服务层"
F[sys_user_payment.go]
end
subgraph "逻辑层"
G[record.go]
end
subgraph "数据访问层"
H[v_1_sys_user_payment_records.go]
end
subgraph "模型层"
I[V1SysUserPaymentRecords.go]
J[SysUserPaymentRecordInput.go]
end
A --> B
A --> C
A --> D
A --> E
B --> F
C --> F
D --> F
E --> F
F --> G
G --> H
H --> I
F --> J
```
**图示来源**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund_v1_menu_log_list.go](file://internal/controller/fund/fund_v1_menu_log_list.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
- [v_1_sys_user_payment_records.go](file://internal/dao/v_1_sys_user_payment_records.go)
- [V1SysUserPaymentRecords.go](file://internal/model/do/v_1_sys_user_payment_records.go)
- [SysUserPaymentRecordInput.go](file://internal/model/sys_user_payment_record.go)
**节来源**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund_v1_menu_log_list.go](file://internal/controller/fund/fund_v1_menu_log_list.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
## 核心组件
资金流水功能的核心组件包括API定义服务接口数据访问对象和数据库模型API定义了四个主要操作创建查询更新和删除资金流水记录服务接口`ISysUserPayment`提供了`AddRecord``ListRecords`等方法来处理这些操作
**节来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
## 架构概述
资金流水功能采用典型的分层架构包括API层控制器层服务层逻辑层数据访问层和模型层API层定义了HTTP端点控制器层处理HTTP请求并调用服务层服务层协调业务逻辑逻辑层实现具体业务规则数据访问层负责与数据库交互模型层定义数据结构
```mermaid
graph TB
A[客户端] --> B[API层]
B --> C[控制器层]
C --> D[服务层]
D --> E[逻辑层]
E --> F[数据访问层]
F --> G[数据库]
```
**图示来源**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund_v1_menu_log_list.go](file://internal/controller/fund/fund_v1_menu_log_list.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
- [v_1_sys_user_payment_records.go](file://internal/dao/v_1_sys_user_payment_records.go)
## 详细组件分析
### 资金流水API分析
资金流水API定义了四个主要操作创建查询更新和删除这些操作通过`MenuLogCreateReq``MenuLogListReq``MenuLogUpdateReq``MenuLogDeleteReq`结构体定义
```mermaid
classDiagram
class MenuLogListReq {
+CommonPageReq
}
class MenuLogCreateReq {
}
class MenuLogUpdateReq {
+CommonIntId
}
class MenuLogDeleteReq {
+CommonIntId
}
MenuLogListReq : path : "/auth/menuLog/getList" tags : "钱包流水" method : "get" summary : "获取钱包流水"
MenuLogCreateReq : path : "/auth/menuLog/create" tags : "钱包流水" method : "post" summary : "创建钱包流水"
MenuLogUpdateReq : path : "/auth/menuLog/update" tags : "钱包流水" method : "post" summary : "修改钱包流水"
MenuLogDeleteReq : path : "/auth/menuLog/delete" tags : "钱包流水" method : "delete" summary : "删除钱包流水"
```
**图示来源**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
**节来源**
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
### 服务层分析
服务层通过`ISysUserPayment`接口定义了资金流水操作包括`AddRecord`用于创建流水记录`ListRecords`用于查询流水记录
```mermaid
classDiagram
class ISysUserPayment {
+AddRecord(ctx, input, tx) recordId, err
+ListRecords(ctx, input) total, list, err
+DailySummary(ctx, input) total, record, err
}
class SysUserPaymentRecordInput {
+OrderNo string
+UserId string
+PaymentId int
+Amount decimal.Decimal
+Notes string
+TransactionType UserPaymentTransactionType
+Category CardRedeemAccountCategory
}
ISysUserPayment ..> SysUserPaymentRecordInput : 使用
```
**图示来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [SysUserPaymentRecordInput.go](file://internal/model/sys_user_payment_record.go)
**节来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
### 数据访问分析
数据访问层通过`V1SysUserPaymentRecords` DAO与数据库交互使用`V1SysUserPaymentRecords`模型定义数据库表结构
```mermaid
classDiagram
class V1SysUserPaymentRecords {
+Id uint
+TransactionId string
+PaymentId int
+DeductionId string
+UserId string
+Amount decimal.Decimal
+TransactionType string
+OrderNo string
+Status string
+Category string
+Notes string
+CreatedAt *gtime.Time
+DeletedAt *gtime.Time
+UpdatedAt *gtime.Time
}
class v1SysUserPaymentRecordsDao {
+InsertAndGetId(data) id, err
+Where(column, value) Query
+Page(page, size) Query
+OrderDesc(column) Query
+ScanAndCount(list, total, true) err
}
V1SysUserPaymentRecords ..> v1SysUserPaymentRecordsDao : 使用
```
**图示来源**
- [v_1_sys_user_payment_records.go](file://internal/dao/v_1_sys_user_payment_records.go)
- [V1SysUserPaymentRecords.go](file://internal/model/do/v_1_sys_user_payment_records.go)
- [V1SysUserPaymentRecords.go](file://internal/model/entity/v_1_sys_user_payment_records.go)
**节来源**
- [v_1_sys_user_payment_records.go](file://internal/dao/v_1_sys_user_payment_records.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
## 依赖分析
资金流水功能依赖于多个组件包括认证服务数据库配置通用工具库等这些依赖通过Go的包导入机制实现
```mermaid
graph TD
A[资金流水API] --> B[认证服务]
A --> C[数据库配置]
A --> D[通用工具库]
A --> E[错误处理]
B --> F[用户认证]
C --> G[数据库连接]
D --> H[UUID生成]
D --> I[时间处理]
E --> J[错误码]
```
**图示来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
**节来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [record.go](file://internal/logic/sys_user_payment/record.go)
## 性能考虑
当前资金流水功能的性能考虑主要包括
- 查询操作支持分页和排序避免一次性加载大量数据
- 使用数据库事务确保数据一致性
- 通过索引优化查询性能基于`UserId``TransactionType`字段
- 使用连接池管理数据库连接
然而部分控制器方法仍返回`gcode.CodeNotImplemented`表明功能尚未完全实现需要进一步优化和实现
## 故障排除指南
常见问题及解决方案
1. **API返回501未实现错误**检查控制器方法是否已实现当前`fund_v1_menu_log_*`系列方法均返回未实现错误
2. **查询结果为空**确认`UserId``TransactionType`参数是否正确检查数据库中是否存在相关记录
3. **创建记录失败**检查输入参数是否符合要求特别是金额字段的精度和范围
4. **权限不足错误**确保请求包含有效的认证令牌用户具有相应权限
**节来源**
- [fund_v1_menu_log_list.go](file://internal/controller/fund/fund_v1_menu_log_list.go)
- [fund_v1_menu_log_create.go](file://internal/controller/fund/fund_v1_menu_log_create.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
## 结论
资金流水功能提供了创建查询更新和删除资金流水记录的基本框架但部分功能尚未完全实现建议优先实现控制器层的方法完善错误处理机制并添加单元测试确保功能的正确性和稳定性同时应考虑添加更多的查询条件和过滤选项以满足实际业务需求

View File

@@ -0,0 +1,224 @@
# 资金管理API
<cite>
**本文档中引用的文件**
- [wallet.go](file://api/fund/v1/wallet.go)
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [fund_v1_wallet_update.go](file://internal/controller/fund/fund_v1_wallet_update.go)
- [fund_v1_wallet_delete.go](file://internal/controller/fund/fund_v1_wallet_delete.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本项目旨在为资金管理提供一套完整的API接口涵盖钱包管理资金流水记录等核心功能系统通过模块化设计实现了钱包的创建查询更新和删除操作并支持资金流水的记录与查询API设计遵循RESTful规范采用分层架构确保系统的可维护性和可扩展性通过事务处理机制保障资金操作的数据一致性同时提供完善的错误处理和安全认证机制
## 项目结构
资金管理功能主要集中在`api/fund``internal/controller/fund`目录下形成了清晰的接口定义与实现分离的架构系统通过`v1`版本的API定义了钱包和资金流水的操作接口控制器层实现了具体的业务逻辑数据访问层则负责与数据库交互
```mermaid
graph TB
subgraph "API层"
A[wallet.go]
B[wallet_log.go]
C[fund.go]
end
subgraph "控制器层"
D[fund_v1_wallet_create.go]
E[fund_v1_wallet_list.go]
F[fund_v1_wallet_update.go]
G[fund_v1_wallet_delete.go]
end
subgraph "数据访问层"
H[v_2_user_wallet.go]
I[v_2_user_wallet_log.go]
end
A --> D
B --> G
C --> D
C --> E
C --> F
C --> G
D --> H
E --> H
F --> H
G --> H
G --> I
```
**图示来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [fund_v1_wallet_update.go](file://internal/controller/fund/fund_v1_wallet_update.go)
- [fund_v1_wallet_delete.go](file://internal/controller/fund/fund_v1_wallet_delete.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
**本节来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [wallet_log.go](file://api/fund/v1/wallet_log.go)
- [fund.go](file://api/fund/fund.go)
## 核心组件
资金管理API的核心组件包括钱包管理接口和资金流水记录接口钱包管理接口提供了钱包的全生命周期管理功能包括创建查询更新和删除操作资金流水记录接口则负责记录所有与钱包相关的资金变动确保资金操作的可追溯性系统通过`IFundV1`接口定义了所有可用的操作控制器层实现了这些接口的具体逻辑数据访问层则通过DAO模式与数据库进行交互
**本节来源**
- [fund.go](file://api/fund/fund.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
## 架构概述
系统采用典型的分层架构分为API层控制器层和数据访问层API层定义了所有可用的接口和数据结构控制器层实现了具体的业务逻辑数据访问层负责与数据库的交互这种分层设计确保了系统的高内聚低耦合便于维护和扩展
```mermaid
graph TD
A[客户端] --> B[HTTP请求]
B --> C[API网关]
C --> D[认证中间件]
D --> E[控制器层]
E --> F[业务逻辑]
F --> G[数据访问层]
G --> H[数据库]
H --> G
G --> F
F --> E
E --> C
C --> A
```
**图示来源**
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
## 详细组件分析
### 钱包管理分析
钱包管理功能提供了完整的CRUD操作支持钱包的创建查询更新和删除每个操作都通过独立的控制器方法实现确保了单一职责原则系统通过上下文Context传递请求信息支持分布式追踪和超时控制
#### 钱包创建流程
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : 创建钱包请求
控制器->>控制器 : 验证请求参数
控制器->>服务层 : 调用创建方法
服务层->>数据库 : 插入钱包记录
数据库-->>服务层 : 返回结果
服务层-->>控制器 : 返回创建结果
控制器-->>客户端 : 返回响应
```
**图示来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
#### 钱包查询流程
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据库
客户端->>控制器 : 查询钱包请求
控制器->>控制器 : 验证请求参数
控制器->>服务层 : 调用查询方法
服务层->>数据库 : 查询钱包记录
数据库-->>服务层 : 返回钱包数据
服务层-->>控制器 : 返回查询结果
控制器-->>客户端 : 返回响应
```
**图示来源**
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
**本节来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [fund_v1_wallet_update.go](file://internal/controller/fund/fund_v1_wallet_update.go)
- [fund_v1_wallet_delete.go](file://internal/controller/fund/fund_v1_wallet_delete.go)
### 资金流水分析
资金流水功能记录了所有与钱包相关的资金变动包括充值消费转账等操作每条流水记录都包含了操作类型金额时间戳等关键信息确保了资金操作的可追溯性
#### 资金流水记录流程
```mermaid
flowchart TD
A[开始] --> B[接收资金操作请求]
B --> C[验证操作合法性]
C --> D{验证通过?}
D --> |是| E[开启数据库事务]
E --> F[更新钱包余额]
F --> G[创建资金流水记录]
G --> H[提交事务]
H --> I[返回成功]
D --> |否| J[返回错误]
J --> K[结束]
I --> K
```
**图示来源**
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
**本节来源**
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
## 依赖分析
系统依赖关系清晰各层之间通过接口进行通信降低了耦合度控制器层依赖于API层的接口定义和数据结构同时依赖于数据访问层提供的DAO对象数据访问层则直接依赖于数据库驱动和ORM框架
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[数据访问层]
C --> D[数据库]
B --> E[认证中间件]
B --> F[错误处理]
C --> G[事务管理]
```
**图示来源**
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
**本节来源**
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
## 性能考虑
系统在设计时充分考虑了性能因素通过数据库索引优化查询性能使用连接池管理数据库连接避免频繁创建和销毁连接的开销对于高并发场景系统支持通过配置调整连接池大小和超时设置事务处理机制确保了数据一致性的同时也需要注意事务的粒度控制避免长时间持有锁导致性能下降
## 故障排除指南
当遇到API调用失败时首先检查请求参数是否符合接口定义特别是必填字段和数据类型如果返回500错误可能是服务端内部异常需要查看服务日志获取详细错误信息对于数据库相关错误检查数据库连接是否正常以及是否有足够的权限执行操作在调试过程中可以启用详细的日志记录来追踪请求处理流程
**本节来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
## 结论
资金管理API提供了一套完整且可靠的钱包管理和资金流水记录解决方案通过清晰的分层架构和规范的接口设计系统具有良好的可维护性和可扩展性未来可以考虑增加更多的安全特性如操作审计日志多因素认证等进一步提升系统的安全性

View File

@@ -0,0 +1,249 @@
# 钱包管理
<cite>
**本文档中引用的文件**
- [wallet.go](file://api/fund/v1/wallet.go)
- [fund.go](file://api/fund/fund.go)
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [fund_v1_wallet_update.go](file://internal/controller/fund/fund_v1_wallet_update.go)
- [fund_v1_wallet_delete.go](file://internal/controller/fund/fund_v1_wallet_delete.go)
- [fund_v1_wallet_list.go](file://internal/controller/fund/fund_v1_wallet_list.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [sys_user_payment_record.go](file://internal/model/sys_user_payment_record.go)
- [sys_payment.go](file://api/sys_payment/v1/sys_payment.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了钱包管理API的设计与实现涵盖钱包的创建更新查询和删除等核心操作系统通过RESTful接口提供完整的钱包生命周期管理功能支持余额管理状态控制和权限验证文档深入解析了事务处理机制并发控制策略和安全认证流程为开发者提供全面的技术参考
## 项目结构
钱包管理功能主要分布在`api/fund``internal/service`目录下通过分层架构实现接口定义业务逻辑和数据访问的分离核心功能模块包括钱包操作控制器服务接口和数据模型与系统其他模块通过标准接口进行集成
```mermaid
graph TB
subgraph "API层"
A[wallet.go]
B[fund.go]
end
subgraph "控制层"
C[fund_v1_wallet_create.go]
D[fund_v1_wallet_update.go]
E[fund_v1_wallet_delete.go]
F[fund_v1_wallet_list.go]
end
subgraph "服务层"
G[sys_user_payment.go]
H[sys_user_payment_record.go]
end
subgraph "数据层"
I[v_2_user_wallet.go]
J[v_2_user_wallet_log.go]
end
A --> C
B --> C
C --> G
G --> I
G --> J
```
**图示来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [fund.go](file://api/fund/fund.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
**章节来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [fund.go](file://api/fund/fund.go)
## 核心组件
钱包管理系统的实现基于分层架构包含接口定义业务逻辑和服务集成三个核心部分系统通过GoFrame框架实现RESTful API采用事务机制确保数据一致性并通过权限验证中间件保障接口安全
**章节来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
## 架构概述
系统采用典型的分层架构设计从上至下分为API接口层业务控制层服务逻辑层和数据访问层各层之间通过明确定义的接口进行通信确保系统的可维护性和可扩展性
```mermaid
graph TD
A[客户端] --> B[HTTP请求]
B --> C[API网关]
C --> D[权限验证中间件]
D --> E[钱包控制器]
E --> F[钱包服务]
F --> G[事务管理]
G --> H[数据库操作]
H --> I[用户钱包表]
H --> J[钱包日志表]
I --> K[余额计算]
J --> L[操作审计]
```
**图示来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
## 详细组件分析
### 钱包操作分析
钱包管理组件提供完整的CRUD操作每个操作都经过严格的权限验证和事务控制系统通过统一的错误处理机制返回标准化的响应确保客户端能够正确处理各种场景
#### 对象导向组件
```mermaid
classDiagram
class WalletCreateReq {
+string path : "/auth/wallet/create"
+string method : "post"
+string summary : "创建钱包信息"
}
class WalletUpdateReq {
+string path : "/auth/wallet/update"
+string method : "post"
+string summary : "修改钱包信息"
+int id
}
class WalletDeleteReq {
+string path : "/auth/wallet/delete"
+string method : "delete"
+string summary : "删除钱包信息"
+int id
}
class WalletListReq {
+string path : "/auth/wallet/getList"
+string method : "get"
+string summary : "获取钱包信息"
+int page
+int limit
}
class SysUserPaymentInput {
+string userId
}
class SysUserPaymentRechargeOrConsumeInput {
+string userId
+string orderNo
+decimal amount
+string remark
+int transactionType
}
WalletCreateReq --> SysUserPaymentInput : "包含"
WalletUpdateReq --> SysUserPaymentInput : "包含"
WalletDeleteReq --> SysUserPaymentInput : "包含"
WalletListReq --> SysUserPaymentInput : "包含"
SysUserPaymentRechargeOrConsumeInput --> SysUserPaymentInput : "扩展"
```
**图示来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [sys_user_payment_record.go](file://internal/model/sys_user_payment_record.go)
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "钱包控制器"
participant Service as "钱包服务"
participant DAO as "数据访问对象"
participant DB as "数据库"
Client->>Controller : POST /auth/wallet/create
Controller->>Controller : 权限验证
Controller->>Service : 调用Add方法
Service->>DAO : 开启事务
DAO->>DB : 检查用户是否存在
DB-->>DAO : 返回结果
DAO->>DB : 插入新钱包记录
DB-->>DAO : 返回插入ID
DAO->>Service : 提交事务
Service-->>Controller : 返回成功
Controller-->>Client : 返回创建结果
Note over Client,DB : 钱包创建流程
```
**图示来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
#### 复杂逻辑组件
```mermaid
flowchart TD
Start([开始]) --> AuthCheck["权限验证"]
AuthCheck --> AuthValid{"验证通过?"}
AuthValid --> |否| ReturnError["返回401错误"]
AuthValid --> |是| TransactionStart["开启事务"]
TransactionStart --> BalanceCheck["检查余额"]
BalanceCheck --> IsEnough{"余额充足?"}
IsEnough --> |否| HandleInsufficient["处理余额不足"]
IsEnough --> |是| UpdateBalance["更新余额"]
UpdateBalance --> CreateLog["创建操作日志"]
CreateLog --> CommitTransaction["提交事务"]
CommitTransaction --> ReturnSuccess["返回成功"]
HandleInsufficient --> RollbackTransaction["回滚事务"]
RollbackTransaction --> ReturnError
ReturnSuccess --> End([结束])
ReturnError --> End
```
**图示来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [v_2_user_wallet_log.go](file://internal/systemV2/dao/internal/v_2_user_wallet_log.go)
**章节来源**
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [sys_user_payment_record.go](file://internal/model/sys_user_payment_record.go)
## 依赖分析
钱包管理系统依赖于多个核心组件包括权限验证数据库访问和事务管理系统通过接口抽象降低耦合度确保各模块可以独立开发和测试
```mermaid
graph TD
A[钱包管理] --> B[权限验证]
A --> C[数据库访问]
A --> D[事务管理]
A --> E[日志记录]
B --> F[用户认证服务]
C --> G[GoFrame ORM]
D --> H[事务协调器]
E --> I[审计日志]
F --> J[用户信息表]
G --> K[用户钱包表]
H --> L[事务日志]
I --> M[操作记录表]
```
**图示来源**
- [fund.go](file://api/fund/fund.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
- [v_2_user_wallet.go](file://internal/systemV2/dao/internal/v_2_user_wallet.go)
**章节来源**
- [fund.go](file://api/fund/fund.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
## 性能考虑
系统在设计时充分考虑了性能优化采用缓存机制减少数据库访问通过批量操作提高处理效率建议在高并发场景下合理配置数据库连接池和缓存策略以确保系统的稳定性和响应速度
## 故障排除指南
当遇到钱包操作失败时应首先检查权限验证结果和输入参数的有效性对于事务相关的错误需要查看数据库日志以确定具体原因系统提供了详细的错误码和消息帮助快速定位和解决问题
**章节来源**
- [fund_v1_wallet_create.go](file://internal/controller/fund/fund_v1_wallet_create.go)
- [sys_user_payment.go](file://internal/service/sys_user_payment.go)
## 结论
钱包管理系统通过清晰的分层架构和严谨的事务控制提供了稳定可靠的钱包管理功能系统设计充分考虑了安全性性能和可维护性为上层应用提供了坚实的基础建议在使用时遵循最佳实践合理配置系统参数以充分发挥系统潜力

View File

@@ -0,0 +1,458 @@
# IP限制API
<cite>
**本文档引用文件**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [entity.go](file://internal/model/entity/v_1_restrict_ip_order_access.go)
- [do.go](file://internal/model/do/v_1_restrict_ip_order_access.go)
- [restriction.go](file://internal/model/restriction.go)
- [restriction.go](file://internal/consts/restriction.go)
- [cache.go](file://utility/cache/cache.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心功能](#核心功能)
3. [IP访问控制端点](#ip访问控制端点)
4. [IP匹配算法](#ip匹配算法)
5. [缓存策略](#缓存策略)
6. [数据库设计](#数据库设计)
7. [错误处理](#错误处理)
8. [性能优化](#性能优化)
9. [集成关系](#集成关系)
10. [客户端调用示例](#客户端调用示例)
11. [常见问题](#常见问题)
## 简介
IP限制API提供了一套完整的IP访问控制机制用于管理系统对特定IP地址的访问权限该系统支持基于商户部署策略的多维度限制包括IP设备卡密和代理检测等多种控制方式系统通过Redis缓存和数据库持久化相结合的方式实现了高性能的IP状态管理
## 核心功能
IP限制系统提供以下核心功能
- IP白名单/黑名单管理
- 基于省份的区域访问控制
- 设备级访问限制
- 卡密关联的访问控制
- 代理使用检测
- 访问记录持久化存储
**IP限制核心功能组件关系图**
```mermaid
graph TD
A[API控制器] --> B[服务接口]
B --> C[业务逻辑]
C --> D[数据访问层]
D --> E[数据库]
C --> F[Redis缓存]
G[商户部署策略] --> C
H[IP匹配算法] --> C
I[访问记录] --> D
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
- [restriction.go](file://internal/logic/restriction/restriction.go#L1-L174)
## IP访问控制端点
### 端点信息
- **HTTP方法**: POST
- **URL模式**: `/api/restriction/v1/check_ip_allowed`
- **认证机制**: 基于商户部署ID的认证
- **权限控制**: 通过商户部署策略配置的限制规则
### 请求参数
请求体包含以下字段
- `orderNo`: 订单号
- `ip`: 待检查的IP地址
- `deviceId`: 设备ID
- `cardPass`: 卡密
- `merchantDeployID`: 商户部署ID
### 响应结构
响应体包含以下字段
- `isAllowed`: 布尔值表示IP是否被允许访问
### 访问控制流程
```mermaid
flowchart TD
Start([开始]) --> GetStrategy["获取商户限制策略"]
GetStrategy --> StrategyValid{"策略有效?"}
StrategyValid --> |否| ReturnError["返回内部错误"]
StrategyValid --> |是| CheckCardPass["检查卡密限制"]
CheckCardPass --> CardPassRestricted{"卡密受限?"}
CardPassRestricted --> |是| ReturnFalse["返回不允许"]
CardPassRestricted --> |否| CheckDevice["检查设备限制"]
CheckDevice --> DeviceRestricted{"设备受限?"}
DeviceRestricted --> |是| ReturnFalse
DeviceRestricted --> |否| CheckProxy["检查代理使用"]
CheckProxy --> ProxyUsed{"使用代理?"}
ProxyUsed --> |是| ReturnFalse
ProxyUsed --> |否| CheckPublicIP["检查公网IP"]
CheckPublicIP --> IsPublic{"公网IP?"}
IsPublic --> |是| CheckIPExist["检查IP是否受限"]
IsPublic --> |否| CheckInternalIP["检查内网IP策略"]
CheckInternalIP --> RestrictInternal{"限制内网IP?"}
RestrictInternal --> |是| ReturnFalse
RestrictInternal --> |否| ReturnTrue["返回允许"]
CheckIPExist --> IPExist{"IP受限?"}
IPExist --> |是| ReturnFalse
IPExist --> |否| CheckArea["检查区域限制"]
CheckArea --> AreaConfigured{"配置区域?"}
AreaConfigured --> |是| CheckAreaAllowed["检查IP是否在允许区域"]
AreaConfigured --> |否| ReturnTrue
CheckAreaAllowed --> AreaAllowed{"在允许区域?"}
AreaAllowed --> |是| ReturnTrue
AreaAllowed --> |否| ReturnFalse
ReturnTrue --> End([结束])
ReturnFalse --> End
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
## IP匹配算法
### 算法实现
IP匹配算法主要通过`CheckIPIsAllowed``IsInProvince`方法实现其核心逻辑如下
```mermaid
flowchart TD
Start([开始]) --> ParseIP["解析IP地址"]
ParseIP --> IsPublicIP["判断是否为公网IP"]
IsPublicIP --> |否| ReturnTrue["返回允许"]
IsPublicIP --> |是| GetIPRecord["获取IP记录"]
GetIPRecord --> RecordExist{"记录存在?"}
RecordExist --> |否| ReturnFalse["返回不允许"]
RecordExist --> |是| IsPublic{"公网地址?"}
IsPublic --> |否| ReturnFalse
IsPublic --> |是| CheckProvince["检查省份"]
CheckProvince --> IsAlpha{"英文省份?"}
IsAlpha --> |是| ConvertToPinyin["转换为拼音"]
IsAlpha --> |否| CompareProvince["直接比较"]
ConvertToPinyin --> CompareProvince
CompareProvince --> InProvince{"在允许省份?"}
InProvince --> |是| ReturnTrue
InProvince --> |否| CheckOverseas["检查海外"]
CheckOverseas --> IsOverseas{"是海外?"}
IsOverseas --> |是| ReturnTrue
IsOverseas --> |否| ReturnFalse
ReturnTrue --> End([结束])
ReturnFalse --> End
```
**图示来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L30-L65)
### 省份匹配逻辑
系统支持34个省级行政区的匹配包括
- 23个省
- 5个自治区
- 4个直辖市
- 2个特别行政区
匹配时支持中文和拼音两种格式系统会自动进行转换和匹配
**本节来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L30-L65)
- [consts.go](file://utility/integration/restriction/consts.go#L17-L23)
## 缓存策略
### Redis缓存实现
系统使用Redis作为缓存层通过`utility/cache/cache.go`文件中的`Cache`结构体实现缓存操作
```mermaid
classDiagram
class Cache {
+*gcache.Cache
+Incr(ctx, key, duration)
+Decr(ctx, key, duration)
+GetPrefixKeyNum(ctx, key)
+SaveTrace(ctx, key)
+GetTrace(ctx, key)
+GetTraceID(ctx)
+DeleteTrace(ctx, key)
}
class PrefixEnum {
+RedeemType
+RedeemWithPaymentType
+RedeemAppleAccountLimitedType
+AccountLimiterType
+JDAccountQueryCache
+JDAccountQueryBalanceWithCookie
+WalmartAccountQueryCache
+WalmartAccountQueryBalanceWithCookie
+AppleMachineAccount
+AppleDuplicatedOrder
+PrefixTrace
+Key(key)
}
Cache --> PrefixEnum : "使用"
```
**图示来源**
- [cache.go](file://utility/cache/cache.go#L1-L127)
### 缓存键设计
系统采用前缀+键的设计模式主要缓存键包括
- `redeem_type`: 兑换类型缓存
- `account_limiter_type`: 账户限流类型
- `jd_account_query_cache`: 京东账户查询缓存
- `walmart_account_query_cache`: 沃尔玛账户查询缓存
- `apple_duplicated_order`: 苹果重复订单
- `trace`: 追踪信息
**本节来源**
- [cache.go](file://utility/cache/cache.go#L1-L127)
## 数据库设计
### 核心表结构
系统使用两个核心表来存储IP限制相关信息
#### 限制IP记录表 (restrict_ip_record)
| 字段名 | 类型 | 描述 |
|--------|------|------|
| id | uint | 主键 |
| ip | string | IP地址 |
| ip_province | string | IP所在省份 |
| is_public | bool | 是否为公网地址 |
| raw_data | string | 原始数据 |
| created_at | *gtime.Time | 创建时间 |
| updated_at | *gtime.Time | 更新时间 |
| deleted_at | *gtime.Time | 删除时间 |
#### IP订单访问表 (restrict_ip_order_access)
| 字段名 | 类型 | 描述 |
|--------|------|------|
| id | uint | 主键 |
| restrict_ip_id | int | 关联的IP地址 |
| order_no | string | 订单号 |
| card_pass | string | 卡密 |
| ip | string | IP地址 |
| status | int | 状态 |
| restrict_strategy | string | 限制策略 |
| device_id | string | 设备ID |
| created_at | *gtime.Time | 创建时间 |
| updated_at | *gtime.Time | 更新时间 |
| deleted_at | *gtime.Time | 删除时间 |
### 表关系
```mermaid
erDiagram
V1RestrictIpRecord ||--o{ V1RestrictIpOrderAccess : "包含"
V1RestrictIpRecord {
uint id PK
string ip
string ip_province
bool is_public
string raw_data
*gtime.Time created_at
*gtime.Time updated_at
*gtime.Time deleted_at
}
V1RestrictIpOrderAccess {
uint id PK
int restrict_ip_id FK
string order_no
string card_pass
string ip
int status
string restrict_strategy
string device_id
*gtime.Time created_at
*gtime.Time updated_at
*gtime.Time deleted_at
}
```
**图示来源**
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go#L1-L28)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go#L1-L27)
- [entity.go](file://internal/model/entity/v_1_restrict_ip_record.go#L1-L22)
- [entity.go](file://internal/model/entity/v_1_restrict_ip_order_access.go#L1-L25)
**本节来源**
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go#L1-L28)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go#L1-L27)
## 错误处理
### 错误处理机制
系统采用统一的错误处理机制主要通过`errHandler`包实现
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "业务逻辑"
Client->>Controller : 发送请求
Controller->>Service : 调用服务
Service->>Logic : 执行业务逻辑
alt 执行成功
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回成功响应
else 执行失败
Logic--xService : 抛出错误
Service--xController : 包装错误
Controller-->>Client : 返回错误响应
end
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
### 错误码
系统定义了以下错误码
- `gcode.CodeInternalError`: 内部错误当获取限制策略失败时返回
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [errHandler.go](file://internal/errHandler/handler.go)
## 性能优化
### 事务处理
系统在添加IP限制记录时使用数据库事务确保数据一致性
```go
err = config.GetDatabaseV1().Ctx(ctx).Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
// 事务内的操作
return nil
})
```
### 缓存优化
系统通过Redis缓存频繁访问的数据减少数据库查询次数
### 并发处理
在省份匹配时系统使用并发处理提高性能
```go
slice.ForEachConcurrent(allProvinceListCopier, func(index int, item string) {
allProvinceListCopier[index] = gstr.ToLower(pinyin.NewDict().Convert(item, "").None())
}, 5)
```
**本节来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L67-L174)
- [cache.go](file://utility/cache/cache.go#L1-L127)
## 集成关系
### 系统集成架构
```mermaid
graph TD
A[前端应用] --> B[API网关]
B --> C[IP限制API]
C --> D[商户部署服务]
C --> E[订单服务]
C --> F[Redis缓存]
C --> G[数据库]
D --> H[配置中心]
E --> I[支付服务]
G --> J[备份系统]
subgraph "核心服务"
C
D
E
end
subgraph "数据存储"
F
G
J
end
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
### 依赖服务
IP限制API依赖以下服务
- 商户部署信息服务获取限制策略
- 订单服务更新订单状态
- Redis服务缓存IP状态
- 数据库服务持久化存储访问记录
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
## 客户端调用示例
### Go语言调用示例
```go
// 创建请求
req := &v1.CheckIPAllowedReq{
OrderNo: "ORDER123456",
Ip: "192.168.1.1",
DeviceId: "DEVICE789",
CardPass: "CARDPASS001",
MerchantDeployID: 1,
}
// 调用API
res, err := controller.CheckIPAllowed(context.Background(), req)
if err != nil {
log.Printf("检查IP失败: %v", err)
return
}
// 处理结果
if res.IsAllowed {
fmt.Println("IP允许访问")
} else {
fmt.Println("IP被限制访问")
}
```
### HTTP调用示例
```bash
curl -X POST https://api.example.com/api/restriction/v1/check_ip_allowed \
-H "Content-Type: application/json" \
-d '{
"orderNo": "ORDER123456",
"ip": "192.168.1.1",
"deviceId": "DEVICE789",
"cardPass": "CARDPASS001",
"merchantDeployID": 1
}'
```
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
## 常见问题
### Q1: 如何配置IP白名单
A: IP白名单通过商户部署策略中的`RestrictArea`字段配置系统会检查IP是否在允许的区域内
### Q2: 内网IP如何处理
A: 系统会检测IP是否为内网IP如果配置了`IsRestrictInternalIp`为false则允许内网IP访问
### Q3: 如何查看IP限制记录
A: 可以通过`GetRestrictRecordByIP`方法查询特定IP的所有限制记录
### Q4: 系统如何处理代理
A: 系统通过`CheckIsDeviceUseProxy`方法检测设备是否使用代理如果检测到使用代理且策略要求限制则拒绝访问
### Q5: 缓存失效时间如何设置
A: 系统使用Redis默认的缓存策略具体失效时间根据不同的缓存键而定
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
- [restriction.go](file://internal/logic/restriction/restriction.go#L1-L174)

View File

@@ -0,0 +1,278 @@
# 地域限制API
<cite>
**本文档引用文件**
- [province.go](file://api/restriction/v1/province.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/model/restriction.go)
- [impl.go](file://utility/integration/restriction/impl.go)
- [models.go](file://utility/integration/restriction/models.go)
- [location.go](file://utility/integration/restriction/location.go)
- [cache.go](file://utility/cache/cache.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/consts/restriction.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了地域限制API的功能实现重点涵盖省份查询和地域控制机制文档深入解析了`restriction_v1_query_all_province`端点的实现细节包括HTTP方法请求响应模式和数据格式同时说明了如何通过省份信息实施地域限制策略并提供了获取所有支持省份列表的使用示例文档还涵盖了地域数据模型查询性能优化如缓存机制与IP地理位置服务的集成方式以及该功能在订单拦截和访问控制中的应用场景
## 项目结构
地域限制功能主要分布在API层控制器层服务层和集成层API定义位于`api/restriction/v1`目录控制器实现位于`internal/controller/restriction`目录核心业务逻辑在`internal/logic/restriction`包中IP地理位置查询集成在`utility/integration/restriction`包中
```mermaid
graph TD
subgraph "API层"
A[province.go]
B[restriction.go]
end
subgraph "控制器层"
C[restriction_v1_query_all_province.go]
D[restriction_v1_check_ip_allowed.go]
end
subgraph "服务层"
E[restriction.go]
end
subgraph "逻辑层"
F[restriction.go]
end
subgraph "模型层"
G[restriction.go]
end
subgraph "集成层"
H[impl.go]
I[models.go]
J[location.go]
end
A --> C
B --> C
C --> E
E --> F
F --> G
H --> F
I --> H
J --> H
```
**图示来源**
- [province.go](file://api/restriction/v1/province.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/model/restriction.go)
- [impl.go](file://utility/integration/restriction/impl.go)
- [models.go](file://utility/integration/restriction/models.go)
- [location.go](file://utility/integration/restriction/location.go)
**本节来源**
- [api/restriction/v1/province.go](file://api/restriction/v1/province.go)
- [internal/controller/restriction/restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
## 核心组件
地域限制API的核心组件包括省份查询接口IP地域检查服务IP地理位置集成和限制策略执行`QueryAllProvince`端点提供获取所有支持省份列表的功能`CheckIPAllowed`端点实现基于省份的访问控制系统通过集成多个IP地理位置服务提供商来确保查询的准确性和可靠性并利用缓存机制优化查询性能
**本节来源**
- [province.go](file://api/restriction/v1/province.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
## 架构概述
地域限制系统采用分层架构设计从API接口到数据访问层清晰分离系统通过RESTful API接收请求由控制器处理并调用服务层服务层协调业务逻辑层和数据访问层完成具体操作IP地理位置查询通过适配器模式集成多个第三方服务确保高可用性和容错能力
```mermaid
graph TB
subgraph "客户端"
Client[客户端应用]
end
subgraph "API网关"
API[RESTful API]
end
subgraph "业务逻辑"
Controller[控制器层]
Service[服务层]
Logic[业务逻辑层]
end
subgraph "外部集成"
IPGeo[IP地理位置服务]
Cache[缓存系统]
Database[数据库]
end
Client --> API
API --> Controller
Controller --> Service
Service --> Logic
Logic --> IPGeo
Logic --> Cache
Logic --> Database
Cache --> Logic
Database --> Logic
```
**图示来源**
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
## 详细组件分析
### 省份查询组件分析
省份查询功能通过`restriction_v1_query_all_province`端点实现提供获取所有支持省份列表的服务该功能在地域限制策略中作为基础数据支持用于定义允许或禁止访问的地理区域
#### 对象导向组件
```mermaid
classDiagram
class QueryAllProvinceReq {
+string path "/restriction/location/getAllProvince"
+string tags "限制"
+string method "get"
+string summary "获取所有的地理位置"
}
class QueryAllProvinceRes {
+CommonDataRes~string~ CommonDataRes
}
class CommonDataRes~T~ {
+int code
+string message
+T data
}
QueryAllProvinceReq --> QueryAllProvinceRes : "返回"
QueryAllProvinceRes --> CommonDataRes~string~ : "泛型继承"
```
**图示来源**
- [province.go](file://api/restriction/v1/province.go)
#### API服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "ControllerV1"
participant Service as "Restriction服务"
participant Logic as "sRestriction逻辑"
Client->>Controller : GET /restriction/location/getAllProvince
Controller->>Service : QueryAllProvince(ctx, req)
Service->>Logic : GetAllProvince(ctx)
Logic-->>Service : 返回省份列表
Service-->>Controller : 构造响应
Controller-->>Client : 返回JSON响应
```
**图示来源**
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
### 地域控制组件分析
地域控制功能通过`CheckIPAllowed`端点实现用于检查特定IP地址是否被允许访问该功能结合商户部署策略和IP地理位置信息决定是否允许请求通过
#### 复杂逻辑组件
```mermaid
flowchart TD
Start([开始]) --> GetStrategy["获取商户部署策略"]
GetStrategy --> CheckCardPass{"卡密限制启用?"}
CheckCardPass --> |是| CheckCardRestrict["检查卡密限制记录"]
CheckCardRestrict --> IsCardRestricted{"存在限制记录?"}
IsCardRestricted --> |是| ReturnFalse["返回不允许"]
CheckCardPass --> |否| CheckDevice{"设备限制启用?"}
CheckDevice --> |是| CheckDeviceRestrict["检查设备限制"]
CheckDeviceRestrict --> IsDeviceRestricted{"设备被限制?"}
IsDeviceRestricted --> |是| ReturnFalse
CheckDevice --> |否| CheckProxy{"代理限制启用?"}
CheckProxy --> |是| CheckProxyUsage["检查是否使用代理"]
CheckProxyUsage --> IsUsingProxy{"使用代理?"}
IsUsingProxy --> |是| ReturnFalse
CheckProxy --> |否| CheckIP{"IP限制启用?"}
CheckIP --> |是| CheckIPRestrict["检查IP限制记录"]
CheckIPRestrict --> IsIPRestricted{"IP被限制?"}
IsIPRestricted --> |是| ReturnFalse
CheckIP --> |否| CheckInternalIP{"内网IP?"}
CheckInternalIP --> |是| CheckInternalSetting{"限制内网IP?"}
CheckInternalSetting --> |否| ReturnTrue["返回允许"]
CheckInternalIP --> |否| CheckArea{"有地域限制?"}
CheckArea --> |是| CheckProvince["检查IP所在省份"]
CheckProvince --> IsInRestrictedArea{"在限制区域?"}
IsInRestrictedArea --> |是| ReturnFalse
CheckArea --> |否| ReturnTrue
ReturnFalse --> End([结束])
ReturnTrue --> End
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
**本节来源**
- [province.go](file://api/restriction/v1/province.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
## 依赖分析
地域限制系统依赖多个内部和外部组件内部依赖包括服务注册机制数据库访问错误处理和配置管理外部依赖主要为多个IP地理位置查询服务提供商系统通过集成多个服务商确保查询的可靠性和容错能力
```mermaid
graph TD
RestrictionAPI --> ServiceLayer
ServiceLayer --> LogicLayer
LogicLayer --> Database
LogicLayer --> Cache
LogicLayer --> IPGeoServices
IPGeoServices --> CSDN
IPGeoServices --> PCOnline
IPGeoServices --> OlTools
IPGeoServices --> IdCd
IPGeoServices --> MeiTu
IPGeoServices --> Vo
IPGeoServices --> DBIP
IPGeoServices --> QJQQ
IPGeoServices --> IQIYI
IPGeoServices --> IP66
Cache --> Redis
Database --> MySQL
```
**图示来源**
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [impl.go](file://utility/integration/restriction/impl.go)
- [cache.go](file://utility/cache/cache.go)
**本节来源**
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [impl.go](file://utility/integration/restriction/impl.go)
- [cache.go](file://utility/cache/cache.go)
## 性能考虑
地域限制系统的性能优化主要体现在缓存机制和IP地理位置查询的容错设计上系统通过Redis缓存频繁访问的数据减少数据库查询压力IP地理位置查询采用随机选择和重试机制确保在某个服务不可用时能够自动切换到其他服务提高系统的可用性和响应速度
**本节来源**
- [cache.go](file://utility/cache/cache.go)
- [location.go](file://utility/integration/restriction/location.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
## 故障排除指南
在使用地域限制API时可能遇到的常见问题包括IP地理位置查询失败缓存不一致和策略配置错误建议首先检查网络连接是否正常确认第三方IP地理位置服务是否可用对于缓存问题可以尝试清除相关缓存键策略配置问题需要检查商户部署配置中的限制设置是否正确
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [impl.go](file://utility/integration/restriction/impl.go)
## 结论
地域限制API提供了一套完整的地理位置控制解决方案通过省份查询和IP检查功能实现了灵活的访问控制策略系统设计考虑了高可用性和性能优化通过集成多个IP地理位置服务提供商和使用缓存机制确保了服务的稳定性和响应速度该功能在订单拦截和访问控制场景中具有重要应用价值

View File

@@ -0,0 +1,231 @@
# 用户信息收集API
<cite>
**本文档引用文件**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/service/restriction.go)
- [user_info.go](file://internal/model/user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_record.go](file://internal/dao/internal/v_1_restrict_ip_record.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了用户信息收集API的技术实现重点介绍restraint_v1_user_info_collection端点的功能该接口用于收集用户设备信息和访问行为数据为风控决策提供支持文档涵盖HTTP方法请求参数结构数据验证规则响应模式数据隐私保护措施信息加密传输存储安全策略以及与风控规则引擎的集成方式同时说明该功能在反欺诈和异常行为检测中的应用并提供性能优化建议
## 项目结构
用户信息收集功能主要分布在API层控制器层服务层和数据访问层核心功能位于restriction模块中涉及用户设备信息收集IP记录管理访问行为分析等
```mermaid
graph TB
subgraph "API层"
collection[api/restriction/v1/collection.go]
end
subgraph "控制器层"
controller[internal/controller/restriction/restriction_v1_user_info_collection.go]
end
subgraph "服务层"
service[internal/service/restriction.go]
end
subgraph "逻辑层"
logic[internal/logic/restriction/restriction.go]
end
subgraph "数据访问层"
dao[internal/dao/v_1_user_info.go]
record[internal/dao/internal/v_1_restrict_*]
end
collection --> controller
controller --> service
service --> logic
logic --> dao
logic --> record
```
**Diagram sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
**Section sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
## 核心组件
用户信息收集API的核心组件包括请求处理数据解密签名验证设备信息存储和IP记录管理系统通过加密传输保护用户隐私使用AES-CBC加密算法确保数据安全并通过MD5签名验证保证数据完整性
**Section sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
## 架构概述
用户信息收集系统的架构分为四个主要层次API接口层负责接收客户端请求控制器层处理业务逻辑服务层提供统一的服务接口数据访问层负责与数据库交互系统通过分层设计实现了关注点分离提高了代码的可维护性和可扩展性
```mermaid
graph TD
Client[客户端] --> API[API接口层]
API --> Controller[控制器层]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> Database[(数据库)]
style Client fill:#f9f,stroke:#333
style Database fill:#ccf,stroke:#333
```
**Diagram sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/service/restriction.go)
## 详细组件分析
### 用户信息收集分析
用户信息收集功能通过POST请求接收加密的用户行为数据经过解密和验证后存储到数据库中用于后续的风控分析
#### 请求处理流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DAO as "数据访问层"
Client->>API : POST /restriction/collection/userInfo
API->>Controller : 转发请求
Controller->>Controller : AES-CBC解密数据
Controller->>Controller : MD5签名验证
Controller->>Service : 调用SaveDeviceInfo
Service->>DAO : 存储设备信息
DAO-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 响应结果
```
**Diagram sources**
- [collection.go](file://api/restriction/v1/collection.go#L1-L23)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
#### 数据模型
```mermaid
classDiagram
class UserInfoCollectionReq {
+string Data
}
class responseModel {
+[]string IPs
+string DeviceID
+string DeviceModel
+string UserAgent
}
class responseWithSign {
+string Sign
}
class RestrictionDeviceInput {
+[]string IPs
+string RemoteIP
+string DeviceID
+string DeviceModel
+string UserAgent
}
UserInfoCollectionReq --> responseWithSign : "解密后"
responseWithSign --> responseModel : "组合"
responseModel --> RestrictionDeviceInput : "转换"
```
**Diagram sources**
- [collection.go](file://api/restriction/v1/collection.go#L1-L23)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [restriction.go](file://internal/model/restriction.go#L11-L17)
**Section sources**
- [collection.go](file://api/restriction/v1/collection.go#L1-L23)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
### 数据验证与安全
系统实现了多层次的数据验证和安全保护机制确保用户信息的完整性和安全性
#### 数据验证流程
```mermaid
flowchart TD
Start([开始]) --> Decrypt["AES-CBC解密"]
Decrypt --> DecryptSuccess{"解密成功?"}
DecryptSuccess --> |否| ReturnError["返回验证失败"]
DecryptSuccess --> |是| ParseJSON["解析JSON"]
ParseJSON --> ParseSuccess{"解析成功?"}
ParseSuccess --> |否| ReturnError
ParseSuccess --> |是| VerifySign["验证MD5签名"]
VerifySign --> SignValid{"签名有效?"}
SignValid --> |否| ReturnError
SignValid --> |是| CheckIP["检查IP一致性"]
CheckIP --> Process["处理业务逻辑"]
Process --> End([结束])
ReturnError --> End
```
**Diagram sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L0-L90)
## 依赖分析
用户信息收集功能依赖于多个核心组件和服务形成了完整的依赖链
```mermaid
graph LR
collection[API定义] --> controller[控制器]
controller --> service[服务接口]
service --> logic[业务逻辑]
logic --> dao[数据访问]
dao --> database[(数据库)]
controller --> crypto[加密组件]
crypto --> aes[AES-CBC]
crypto --> md5[MD5]
logic --> config[数据库配置]
logic --> utils[工具库]
```
**Diagram sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
**Section sources**
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
## 性能考虑
用户信息收集API在设计时考虑了性能优化通过合理的缓存策略数据库索引和异步处理机制确保系统的高效运行建议在高并发场景下使用连接池和批量处理来进一步提升性能
## 故障排除指南
当用户信息收集API出现问题时可按照以下步骤进行排查
1. 检查请求数据是否正确加密
2. 验证MD5签名是否匹配
3. 确认数据库连接是否正常
4. 检查AES密钥和IV是否正确
5. 查看日志中的错误信息
**Section sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L0-L90)
## 结论
用户信息收集API通过安全的加密传输和严格的验证机制有效地收集用户设备信息和访问行为数据为风控决策提供了可靠的数据支持系统设计合理层次分明具有良好的可维护性和扩展性能够满足反欺诈和异常行为检测的需求

View File

@@ -0,0 +1,258 @@
# 风控限制API
<cite>
**本文档中引用的文件**
- [province.go](file://api/restriction/v1/province.go)
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction_v1_block_order.go](file://internal/controller/restriction/restriction_v1_block_order.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
- [consts.go](file://utility/integration/restriction/consts.go)
- [impl.go](file://utility/integration/restriction/impl.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了风控限制API的功能实现涵盖IP限制地域限制和用户信息收集等核心功能系统通过多级风控策略实现对用户访问行为的精细化控制包括基于IP地理位置的访问控制设备识别与限制卡密关联限制等功能API设计遵循RESTful规范提供清晰的端点定义和安全的数据交互机制
## 项目结构
风控限制功能主要分布在API层控制器层服务逻辑层和集成工具层形成清晰的分层架构各层职责分明确保功能的可维护性和可扩展性
```mermaid
graph TB
subgraph "API层"
A[province.go]
B[collection.go]
end
subgraph "控制器层"
C[restriction_v1_check_ip_allowed.go]
D[restriction_v1_query_all_province.go]
E[restriction_v1_user_info_collection.go]
F[restriction_v1_block_order.go]
end
subgraph "服务逻辑层"
G[restriction.go]
H[ip_record.go]
end
subgraph "集成工具层"
I[location.go]
J[consts.go]
K[impl.go]
end
A --> C
B --> E
B --> F
C --> G
D --> G
E --> G
F --> G
G --> H
G --> I
I --> J
I --> K
```
**图示来源**
- [province.go](file://api/restriction/v1/province.go)
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction_v1_block_order.go](file://internal/controller/restriction/restriction_v1_block_order.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
- [consts.go](file://utility/integration/restriction/consts.go)
- [impl.go](file://utility/integration/restriction/impl.go)
**本节来源**
- [api/restriction/v1](file://api/restriction/v1)
- [internal/controller/restriction](file://internal/controller/restriction)
## 核心组件
风控限制系统的核心组件包括IP地理位置查询地域限制检查用户信息收集和订单封禁功能系统通过集成多个第三方IP定位服务实现高可用的地理位置识别并结合商户部署策略进行访问控制决策所有限制记录持久化存储于数据库支持后续审计和分析
**本节来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
## 架构概述
系统采用分层架构设计从API接口到服务逻辑再到外部集成形成完整的风控处理链路API层定义清晰的端点契约控制器层处理请求调度服务层实现核心业务逻辑集成层提供外部服务访问能力
```mermaid
graph TD
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务逻辑]
Service --> Cache[(缓存)]
Service --> Database[(数据库)]
Service --> External[第三方服务]
External --> CSDN[CSDN]
External --> PCOnline[PCOnline]
External --> IP66[IP66]
External --> MeiTu[美图]
```
**图示来源**
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
- [impl.go](file://utility/integration/restriction/impl.go)
## 详细组件分析
### IP访问控制分析
系统通过多源IP地理位置服务实现高可用的IP定位功能采用重试机制确保查询成功率当主要服务失败时自动切换到备用服务保证系统稳定性
#### 类图
```mermaid
classDiagram
class Location {
<<interface>>
+QueryLocationByIP(ctx, ip) Response, error
}
class CSDNClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class PcOnlineClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class OlToolsClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class IdCdClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class MeiTuClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class VoClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class DBIPClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class QJQQClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class IQIYIClient {
+QueryLocationByIP(ctx, ip) Response, error
}
class IP66Client {
+QueryLocationByIP(ctx, ip) Response, error
}
Location <|-- CSDNClient
Location <|-- PcOnlineClient
Location <|-- OlToolsClient
Location <|-- IdCdClient
Location <|-- MeiTuClient
Location <|-- VoClient
Location <|-- DBIPClient
Location <|-- QJQQClient
Location <|-- IQIYIClient
Location <|-- IP66Client
```
**图示来源**
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
- [impl.go](file://utility/integration/restriction/impl.go#L0-L44)
### 省份查询分析
提供获取全国所有省份列表的API接口支持前端下拉选择等场景系统维护完整的省份列表包括特殊行政区和海外地区
#### 序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
Client->>API : GET /restriction/location/getAllProvince
API->>Controller : 调用QueryAllProvince
Controller->>Service : 调用GetAllProvince
Service-->>Controller : 返回省份列表
Controller-->>API : 返回响应
API-->>Client : 返回省份列表
```
**图示来源**
- [province.go](file://api/restriction/v1/province.go#L0-L28)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go#L0-L15)
- [restriction.go](file://internal/logic/restriction/restriction.go#L45-L47)
### 用户信息收集分析
实现用户设备信息收集功能通过加密数据传输确保信息安全系统验证数据签名防止篡改并记录设备指纹用于后续风控决策
#### 流程图
```mermaid
flowchart TD
Start([开始]) --> Decrypt["解密请求数据"]
Decrypt --> Validate["验证数据签名"]
Validate --> SignatureValid{"签名有效?"}
SignatureValid --> |否| ReturnError["返回签名错误"]
SignatureValid --> |是| GetRemoteIP["获取客户端IP"]
GetRemoteIP --> CheckProxy["检查是否使用代理"]
CheckProxy --> SaveDevice["保存设备信息"]
SaveDevice --> End([结束])
ReturnError --> End
```
**图示来源**
- [collection.go](file://api/restriction/v1/collection.go#L0-L23)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [restriction.go](file://internal/logic/restriction/restriction.go)
**本节来源**
- [collection.go](file://api/restriction/v1/collection.go#L0-L23)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
## 依赖分析
系统依赖多个外部IP定位服务和内部服务组件形成复杂的依赖网络通过接口抽象降低耦合度支持服务的灵活替换和扩展
```mermaid
graph TD
RestrictionService --> IPRecordService
RestrictionService --> MerchantDeployInfoService
RestrictionService --> OrderSummaryService
RestrictionService --> Database
RestrictionService --> CSDNService
RestrictionService --> PCOnlineService
RestrictionService --> IP66Service
RestrictionService --> MeiTuService
```
**图示来源**
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
- [consts.go](file://utility/integration/restriction/consts.go)
**本节来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
## 性能考虑
系统通过缓存IP地理位置信息减少外部服务调用提高响应速度采用并发处理和重试机制平衡性能与可靠性确保在高并发场景下的稳定运行
## 故障排除指南
常见问题包括IP定位服务不可用数据签名验证失败和数据库连接异常建议检查网络连接服务配置和密钥设置确保各组件正常运行
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [impl.go](file://utility/integration/restriction/impl.go#L0-L44)
## 结论
风控限制API提供了完整的访问控制解决方案通过多维度限制策略保障系统安全系统设计考虑了高可用性安全性和可扩展性能够满足复杂的业务场景需求

View File

@@ -0,0 +1,333 @@
# 业务逻辑层架构
<cite>
**本文档中引用的文件**
- [main.go](file://main.go)
- [logic.go](file://internal/logic/logic.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [sys_user.go](file://internal/dao/v_1_sys_user.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
- [card_redeem_order.go](file://internal/logic/card_redeem_order/order.go)
- [merchant_order.go](file://internal/logic/merchant_order/order.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [card_t_mall_order.go](file://internal/logic/card_t_mall_order/order.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [merchant_order.go](file://internal/service/merchant_order.go)
- [restriction.go](file://internal/service/restriction.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [config.yaml](file://manifest/config/config.yaml)
</cite>
## 目录
1. [引言](#引言)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 引言
kami_backend 是一个用于管理卡密充值订单处理和账户管理的后端服务系统该系统采用分层架构设计包含 controllerservice logic 三层分别负责请求处理业务逻辑和数据访问系统支持多种卡密类型包括 Apple京东沃尔玛等并提供了灵活的配置和扩展机制本文档旨在描述该系统的业务逻辑层架构包括高阶设计架构模式系统边界核心业务流程组件交互数据流集成模式技术决策基础设施要求可扩展性考虑部署拓扑安全性监控和灾难恢复等横切关注点
## 项目结构
kami_backend 项目采用模块化设计主要分为 apiinternalmanifestutility 等目录api 目录包含各业务模块的 API 定义internal 目录包含核心业务逻辑manifest 目录包含部署配置utility 目录包含工具类和辅助功能
```mermaid
graph TD
subgraph "API层"
A[api/authority]
B[api/card_info_apple]
C[api/card_info_jd]
D[api/card_info_walmart]
E[api/order]
F[api/sysUser]
end
subgraph "内部层"
G[internal/controller]
H[internal/service]
I[internal/logic]
J[internal/dao]
K[internal/model]
end
subgraph "工具层"
L[utility/config]
M[utility/integration]
N[utility/monitor]
end
A --> G
B --> G
C --> G
D --> G
E --> G
F --> G
G --> H
H --> I
I --> J
J --> K
L --> H
M --> I
N --> H
```
**图源**
- [main.go](file://main.go#L1-L50)
- [logic.go](file://internal/logic/logic.go#L1-L37)
## 核心组件
kami_backend 的核心组件包括用户管理卡密充值订单处理权限控制等用户管理组件负责用户账户的创建修改删除和权限分配卡密充值组件支持多种卡密类型包括 Apple京东沃尔玛等提供卡密的充值查询回调等功能订单处理组件负责订单的创建查询状态更新和统计权限控制组件基于 Casbin 实现支持基于角色的访问控制
**组件源**
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
- [card_apple_order.go](file://internal/service/card_apple_order.go#L1-L127)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go#L1-L80)
- [merchant_order.go](file://internal/service/merchant_order.go#L1-L44)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
## 架构概述
kami_backend 采用典型的三层架构包括 controllerservice logic controller 层负责接收和处理 HTTP 请求调用 service 层提供的接口service 层是业务逻辑的核心封装了具体的业务规则和流程调用 logic 层进行数据访问和处理logic 层负责与数据库交互执行 CRUD 操作并提供数据访问的抽象
```mermaid
graph TD
A[客户端] --> B[Controller]
B --> C[Service]
C --> D[Logic]
D --> E[DAO]
E --> F[数据库]
```
**图源**
- [main.go](file://main.go#L1-L50)
- [logic.go](file://internal/logic/logic.go#L1-L37)
## 详细组件分析
### 用户管理组件分析
用户管理组件负责用户账户的全生命周期管理包括创建修改删除查询和权限分配该组件基于 GoFrame 框架实现使用 MySQL 作为持久化存储
#### 类图
```mermaid
classDiagram
class SysUser {
+string Id
+string Username
+int IsAdmin
+string Phone
+*gtime.Time CreatedAt
+*gtime.Time UpdatedAt
+*gtime.Time DeletedAt
+GetCasBinUserPrefix() string
+NotCheckAuthAdminIds(ctx context.Context) *gset.Set
+GetAdminUserByUsernamePassword(ctx context.Context, req *model.UserLoginInput) (user *model.LoginUserOutput, err error)
+GetUserByUsername(ctx context.Context, userName string) (sysUser *model.LoginUserOutput, err error)
+GetUserById(ctx context.Context, id string) (sysUser *model.LoginUserOutput, err error)
+LoginLog(ctx context.Context, params *model.LoginLogParams)
+GetAdminRules(ctx context.Context, userId string) (menuList []*model.UserMenus, permissions []string, err error)
+GetAdminRole(ctx context.Context, userId string, allRoleList []*entity.V1SysRole) (roles []*entity.V1SysRole, err error)
+GetAdminRoleIds(ctx context.Context, userId string) (roleIds []uint, err error)
+GetAllMenus(ctx context.Context) (menus []*model.UserMenus, err error)
+GetAdminMenusByRoleIds(ctx context.Context, roleIds []uint) (menus []*model.UserMenus, err error)
+GetMenusTree(menus []*model.UserMenus, pid uint) []*model.UserMenus
+GetPermissions(ctx context.Context, roleIds []uint) (userButtons []string, err error)
+List(ctx context.Context, req *model.UserSearchInput) (total int, userList []*entity.V1SysUser, err error)
+GetByUserName(ctx context.Context, username string) (userList []*entity.V1SysUser, err error)
+ListWithPayment(ctx context.Context, req *model.UserSearchInput) (total int, userList []*model.UserSearchWithPaymentOutput, err error)
+Add(ctx context.Context, req *model.UserAddInput) (userId string, err error)
+Edit(ctx context.Context, req *model.UserEditInput) (err error)
+EditUserRole(ctx context.Context, roleIds []int64, userId int64) (err error)
+UserNameOrMobileExists(ctx context.Context, userName string, id ...string) (isExist bool, err error)
+GetEditUser(ctx context.Context, id string) (res *model.UserGetEditOutput, err error)
+GetUserInfoById(ctx context.Context, id string, withPwd ...bool) (user *entity.V1SysUser, err error)
+ChangePwd(ctx context.Context, input *model.UserChangePwdInput) (err error)
+ChangeUserStatus(ctx context.Context, input *model.UserStatusInput) (err error)
+DeleteById(ctx context.Context, id string) (err error)
+Delete(ctx context.Context, ids []string) (err error)
+GetUsers(ctx context.Context, ids []string) (users []*model.SysUserSimpleOutput, err error)
+GetUsersAll(ctx context.Context) (users []*model.SysUserSimpleOutput, err error)
+GetUserFromToken(ctx context.Context) (needAuth bool, user *entity.V1SysUser, err error)
+CheckUserNormal(ctx context.Context, userId string) (isNormal bool, err error)
+GetAllUserNormal(ctx context.Context, tx gdb.TX) (user []*entity.V1SysUser, err error)
+GetAllSimpleUser(ctx context.Context) (data []model.UserSimpleUsersOutput, err error)
+GetCurrentOneFromCache(ctx context.Context, channelName consts.CardRedeemAccountCategory) (data *entity.V1SysUser, err error)
+GetOneNormalOneWithPayment(ctx context.Context, userId string, tx gdb.TX) (output *model.UserSearchWithPaymentOutput, err error)
+GetAllNormalWithPayment(ctx context.Context, minAmount float64, tx gdb.TX) (output []*model.UserSearchWithPaymentOutput, err error)
+GetAllNormalWithPaymentAndChannelCfg(ctx context.Context, minAmount float64, tx gdb.TX) (output []*model.UserSearchWithPaymentAndCfgOutput, err error)
+GetNextOne(ctx context.Context, userId string, amount float64, isNext bool, tx gdb.TX) (data *entity.V1SysUser, err error)
+SetTotp(ctx context.Context, data *entity.V1SysUser, key string, secret string) (err error)
+ResetTotp(ctx context.Context, data *entity.V1SysUser) (err error)
}
class SysUserDao {
+V1SysUser *v1SysUserDao
+Get(ctx context.Context, id string) (*entity.V1SysUser, error)
+Create(ctx context.Context, user *entity.V1SysUser) error
+Update(ctx context.Context, user *entity.V1SysUser) error
+Delete(ctx context.Context, id string) error
}
class SysUserModel {
+User *model.User
+UserSearchInput *model.UserSearchInput
+UserSearchWithPaymentOutput *model.UserSearchWithPaymentOutput
+UserSearchWithPaymentAndCfgOutput *model.UserSearchWithPaymentAndCfgOutput
+UserAddInput *model.UserAddInput
+UserEditInput *model.UserEditInput
+UserGetEditOutput *model.UserGetEditOutput
+UserChangePwdInput *model.UserChangePwdInput
+UserStatusInput *model.UserStatusInput
+SysUserSimpleOutput *model.SysUserSimpleOutput
+UserLoginOutInput *model.UserLoginOutInput
+LoginUserOutput *model.LoginUserOutput
+UserLoginOutOutput *model.UserLoginOutOutput
+UserSimpleUsersOutput *model.UserSimpleUsersOutput
}
SysUser --> SysUserDao : "uses"
SysUser --> SysUserModel : "uses"
SysUserDao --> SysUserModel : "returns"
```
**图源**
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L767)
- [sys_user.go](file://internal/dao/v_1_sys_user.go#L1-L28)
- [sys_user.go](file://internal/model/sys_user.go#L1-L92)
### 卡密充值组件分析
卡密充值组件支持多种卡密类型包括 Apple京东沃尔玛等提供卡密的充值查询回调等功能该组件基于 GoFrame 框架实现使用 MySQL 作为持久化存储
#### 序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "Controller"
participant Service as "Service"
participant Logic as "Logic"
participant DAO as "DAO"
participant DB as "数据库"
Client->>Controller : POST /api/card_info_apple/v1/recharge_submit
Controller->>Service : AddRechargeOrder(input)
Service->>Logic : AddRechargeOrder(input)
Logic->>DAO : InsertAndGetId(do.V1CardAppleRechargeInfo)
DAO->>DB : INSERT INTO v1_card_apple_recharge_info
DB-->>DAO : 返回ID
DAO-->>Logic : 返回ID
Logic->>DAO : Insert(do.V1CardAppleHistoryInfo)
DAO->>DB : INSERT INTO v1_card_apple_history_info
DB-->>DAO : 返回结果
DAO-->>Logic : 返回结果
Logic-->>Service : 返回订单号
Service-->>Controller : 返回订单号
Controller-->>Client : 返回订单号
```
**图源**
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go#L1-L343)
- [card_apple_order.go](file://internal/service/card_apple_order.go#L1-L127)
### 订单处理组件分析
订单处理组件负责订单的创建查询状态更新和统计该组件基于 GoFrame 框架实现使用 MySQL 作为持久化存储
#### 流程图
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> InputValid{"输入有效?"}
InputValid --> |否| ReturnError["返回错误响应"]
InputValid --> |是| CheckOrder["检查订单是否存在"]
CheckOrder --> OrderExists{"订单存在?"}
OrderExists --> |是| UpdateOrder["更新订单状态"]
OrderExists --> |否| CreateOrder["创建新订单"]
CreateOrder --> SaveOrder["保存订单到数据库"]
SaveOrder --> UpdateStatus["更新订单状态"]
UpdateStatus --> ReturnResult["返回结果"]
UpdateOrder --> ReturnResult
ReturnResult --> End([结束])
ReturnError --> End
```
**图源**
- [merchant_order.go](file://internal/logic/merchant_order/order.go#L1-L48)
- [merchant_order.go](file://internal/service/merchant_order.go#L1-L44)
### 权限控制组件分析
权限控制组件基于 Casbin 实现支持基于角色的访问控制该组件负责用户权限的验证和管理
#### 类图
```mermaid
classDiagram
class Restriction {
+GetAllProvince(ctx context.Context) []string
+CheckIPIsAllowed(ctx context.Context, ip string, area []string) (isAllowed bool, err error)
+AddToRestrictIP(ctx context.Context, input model.AddRestrictionRecordInput) (err error)
+SetCurrentOrderDisable(ctx context.Context, orderNo string, status consts.RestrictStatus, tx gdb.TX) (err error)
+GetLocationWithProxyByIP(ctx context.Context, ip string) (data *model.RestrictionIPRecordOutput, err error)
+IsInProvince(ctx context.Context, ip string, province []string) (isin bool, m *model.RestrictionIPRecordOutput, err error)
+GetRestrictRecordByCardPass(ctx context.Context, cardPass string) (dataList []entity.V1RestrictIpOrderAccess, err error)
+GetRestrictRecordByIP(ctx context.Context, ip string) (dataList []model.RestrictWithIPRecordOutput, err error)
+GetIPOrderAccessByCardPass(ctx context.Context, cardPass string) (data []entity.V1RestrictIpOrderAccess, err error)
+IsRestrictExistByCardPass(ctx context.Context, cardPass string) (isExist bool)
+IsRestrictExistByIP(ctx context.Context, ip string) (isExist bool)
+IsRestrictDevice(ctx context.Context, deviceId string) (isRestrict bool)
}
class RestrictionDao {
+V1RestrictIpRecord *v1RestrictIpRecordDao
+V1RestrictIpOrderAccess *v1RestrictIpOrderAccessDao
+GetOrSetIPRecord(ctx context.Context, ip string, tx gdb.TX) (m *model.RestrictionIPRecordOutput, err error)
+GetRestrictRecordByCardPass(ctx context.Context, cardPass string) (dataList []entity.V1RestrictIpOrderAccess, err error)
+GetRestrictRecordByIP(ctx context.Context, ip string) (dataList []model.RestrictWithIPRecordOutput, err error)
+GetIPOrderAccessByCardPass(ctx context.Context, cardPass string) (data []entity.V1RestrictIpOrderAccess, err error)
}
class RestrictionModel {
+AddRestrictionRecordInput *model.AddRestrictionRecordInput
+RestrictionIPRecordOutput *model.RestrictionIPRecordOutput
+RestrictWithIPRecordOutput *model.RestrictWithIPRecordOutput
}
Restriction --> RestrictionDao : "uses"
Restriction --> RestrictionModel : "uses"
RestrictionDao --> RestrictionModel : "returns"
```
**图源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L1-L174)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
## 依赖分析
kami_backend 依赖于多个外部组件和库包括 GoFrame 框架MySQL 数据库Redis 缓存OpenTelemetry 监控系统等GoFrame 框架提供了 Web 服务数据库访问配置管理等基础功能MySQL 数据库用于持久化存储用户订单卡密等数据Redis 缓存用于提高系统性能减少数据库访问压力OpenTelemetry 监控系统用于收集和分析系统运行时的性能数据
```mermaid
graph TD
A[kami_backend] --> B[GoFrame]
A --> C[MySQL]
A --> D[Redis]
A --> E[OpenTelemetry]
B --> F[gin]
B --> G[gorm]
C --> H[InnoDB]
D --> I[内存存储]
E --> J[Jaeger]
E --> K[Prometheus]
```
**图源**
- [main.go](file://main.go#L1-L50)
- [config.yaml](file://manifest/config/config.yaml#L1-L10)
## 性能考虑
kami_backend 在设计时充分考虑了性能因素采用了多种优化措施首先系统使用 Redis 缓存热点数据如用户信息配置信息等减少数据库访问次数其次系统采用连接池技术复用数据库连接减少连接创建和销毁的开销此外系统还使用了异步处理机制将耗时操作放入后台任务队列中执行提高响应速度最后系统通过 OpenTelemetry 监控系统实时监控性能指标及时发现和解决性能瓶颈
## 故障排除指南
kami_backend 出现问题时可以按照以下步骤进行排查
1. 检查系统日志查看是否有错误信息
2. 检查数据库连接是否正常是否有慢查询
3. 检查 Redis 缓存是否正常是否有缓存穿透或雪崩
4. 检查 OpenTelemetry 监控系统查看性能指标是否异常
5. 检查配置文件确认配置项是否正确
6. 如果问题仍然无法解决可以联系技术支持团队
**组件源**
- [main.go](file://main.go#L1-L50)
- [config.yaml](file://manifest/config/config.yaml#L1-L10)
## 结论
kami_backend 是一个功能完善性能优良的后端服务系统通过采用分层架构设计系统实现了良好的模块化和可维护性通过使用多种优化措施系统能够高效地处理大量并发请求通过集成 OpenTelemetry 监控系统系统具备了强大的可观测性未来系统可以进一步优化性能增加更多功能提高用户体验

View File

@@ -0,0 +1,203 @@
# Apple卡密充值处理
<cite>
**本文档引用文件**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了Apple卡密充值处理系统的完整流程系统支持商户提交Apple卡密充值订单通过与iTunes系统的回调集成完成充值状态同步并具备重复卡密检测订单状态机管理异步处理错误重试等核心功能系统还与支付系统和风控系统深度集成确保业务流程的完整性与安全性
## 项目结构
Apple卡密充值功能的核心代码位于`internal/controller/card_info_apple`目录下由多个控制器文件组成分别处理订单提交分配回调和异常处理等不同场景数据模型定义在`internal/model`包中而数据库操作则封装在`internal/dao`包内
```mermaid
graph TD
subgraph "API层"
A[RechargeSubmit] --> |提交订单| B[RechargeHandler]
B --> |分配账户| C[RechargeItunesCallback]
C --> |状态回调| D[RechargeDuplicatedCardPass]
D --> |重复卡密处理| A
end
subgraph "服务层"
E[AppleOrder Service] < --> F[AppleAccount Service]
end
subgraph "数据层"
G[V1CardAppleRechargeInfo]
H[V1CardAppleAccountInfo]
end
A --> E
B --> E
C --> E
D --> E
E --> G
F --> H
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L1-L188)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go#L1-L28)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go#L1-L28)
**本节来源**
- [internal/controller/card_info_apple](file://internal/controller/card_info_apple)
- [internal/model](file://internal/model)
- [internal/dao](file://internal/dao)
## 核心组件
Apple卡密充值系统由四个核心控制器方法构成`RechargeSubmit`负责接收并验证商户提交的充值请求`RechargeHandler`负责从待处理订单队列中获取订单并分配合适的Apple账户进行充值`RechargeItunesCallback`处理来自iTunes系统的充值结果回调更新订单状态`RechargeDuplicatedCardPass`则专门处理因卡密重复而被挂起的订单
**本节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L1-L188)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go#L1-L44)
## 架构概述
系统采用分层架构从上至下分为API接口层业务逻辑服务层和数据访问层API层暴露标准化的REST接口供外部系统调用服务层封装了核心业务逻辑如订单状态管理账户分配策略和回调处理数据层通过DAO模式与数据库交互保证数据操作的统一性和安全性整个流程通过Redis缓存实现幂等性控制并利用定时任务gcron实现超时重试机制
```mermaid
graph TB
subgraph "表现层"
API[API Controller]
end
subgraph "业务逻辑层"
Service[AppleOrder Service]
AccountService[AppleAccount Service]
end
subgraph "数据访问层"
DAO[DAO Layer]
end
subgraph "外部系统"
iTunes[iTunes系统]
end
API --> Service
Service --> AccountService
Service --> DAO
AccountService --> DAO
iTunes --> API
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L1-L188)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
## 详细组件分析
### 充值订单提交分析
`RechargeSubmit`方法是整个充值流程的入口它首先通过分布式锁和Redis缓存防止同一商户ID在短时间内重复提交订单接着通过签名验证确保请求的合法性最后调用服务层方法将订单信息持久化到数据库
#### 充值订单提交流程
```mermaid
flowchart TD
Start([开始]) --> ValidateDuplicate["验证重复提交"]
ValidateDuplicate --> |已存在| ReturnError["返回: 订单正在处理"]
ValidateDuplicate --> |不存在| SetCache["写入缓存 (10秒)"]
SetCache --> ValidateSign["验证签名"]
ValidateSign --> |失败| ReturnSignError["返回: 校验错误"]
ValidateSign --> |成功| ValidateCardPass["验证卡密格式"]
ValidateCardPass --> |失败| ReturnCardError["返回: 卡密校验错误"]
ValidateCardPass --> |成功| AddOrder["添加充值订单"]
AddOrder --> |成功| ReturnSuccess["返回: 提交成功"]
AddOrder --> |失败| ReturnDbError["返回: 数据库操作失败"]
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
**本节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
### iTunes回调处理分析
`RechargeItunesCallback`方法处理来自iTunes系统的异步回调它根据不同的状态码如成功失败退款等执行相应的业务逻辑包括更新订单状态记录操作历史调整账户状态以及触发上游回调
#### iTunes回调状态处理
```mermaid
stateDiagram-v2
[*] --> 接收回调
接收回调 --> 查询订单
查询订单 --> 订单不存在 : 失败
查询订单 --> 订单存在 : 成功
订单存在 --> 验证状态 : 检查是否为处理中/等待中
验证状态 --> 状态无效 : 返回错误
验证状态 --> 状态有效 : 继续处理
状态有效 --> 根据状态分支
根据状态分支 --> 成功 : 更新实际金额,回调上游
根据状态分支 --> 失败 : 更新为失败状态,记录原因
根据状态分支 --> 退款 : 退回订单,更新账户状态
根据状态分支 --> 密码错误 : 标记账户异常,退回订单
成功 --> [*]
失败 --> [*]
退款 --> [*]
密码错误 --> [*]
```
**图示来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
**本节来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
### 充值状态同步与重复卡密处理
当iTunes回调返回金额不一致卡密重复等特殊状态时订单状态会被置为金额异议卡密重复`RechargeDuplicatedCardPass`方法提供了一个手动处理接口允许管理员在确认前序订单结果后将挂起的订单与成功订单的实际金额对齐并完成最终的上游回调
**本节来源**
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go#L1-L44)
## 依赖分析
系统内部依赖关系清晰控制器层依赖服务层服务层依赖数据访问层外部依赖包括GoFrame框架用于Web服务数据库操作日志和分布式锁Lancet库用于指针操作以及Redis用于缓存和幂等性控制
```mermaid
graph LR
Controller --> Service
Service --> DAO
DAO --> Database[(MySQL)]
Controller --> Redis[(Redis)]
Controller --> iTunes[iTunes API]
Service --> Config[配置中心]
```
**图示来源**
- [go.mod](file://go.mod)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
**本节来源**
- [go.mod](file://go.mod)
- [internal/controller](file://internal/controller)
- [internal/service](file://internal/service)
- [utility/config](file://utility/config)
## 性能考虑
系统通过多种机制保障性能和稳定性使用Redis缓存实现提交幂等性避免数据库压力利用`gmlock.LockFunc`确保关键操作的线程安全通过`gcron`定时任务处理超时订单避免资源长时间占用在数据库操作中广泛使用事务保证数据一致性
## 故障排除指南
常见问题包括重复提交导致订单正在处理错误应检查客户端重试逻辑回调失败需确认服务器防火墙和iTunes回调地址可达性账户被临时封禁系统会自动在2分钟后恢复订单长时间处于处理中状态可能是定时任务未正确执行需检查cron服务
**本节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go#L1-L70)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go#L1-L188)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go#L1-L245)
## 结论
Apple卡密充值处理系统设计完整涵盖了从订单接收到状态同步的全生命周期管理系统具备良好的扩展性和健壮性通过状态机异步回调和定时重试机制有效应对了第三方系统集成中的各种不确定性建议持续监控回调成功率和账户健康度以进一步优化系统表现

View File

@@ -0,0 +1,206 @@
# Apple卡密历史记录管理
<cite>
**本文档引用文件**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info_history.go](file://internal/dao/v_1_card_apple_account_info_history.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
- [card_apple_account.go](file://internal/model/card_apple_account.go)
- [recharge_history.go](file://internal/logic/card_apple_order/recharge_history.go)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述Apple卡密系统中账户历史记录与充值历史记录的管理机制涵盖历史数据的存储结构查询接口导出功能索引优化数据归档策略以及与审计和对账系统的集成通过分析关键代码实现揭示系统在大数据量下的性能优化手段和数据一致性保障机制
## 项目结构
Apple卡密历史记录管理功能主要分布在`internal`目录下的`controller``dao``model``logic`子模块中围绕Apple卡密业务形成独立的逻辑闭环
```mermaid
graph TB
subgraph "API层"
Controller["internal/controller/card_info_apple"]
end
subgraph "逻辑层"
Logic["internal/logic/card_apple_*"]
end
subgraph "模型层"
Model["internal/model"]
end
subgraph "数据访问层"
DAO["internal/dao"]
end
Controller --> Logic
Logic --> Model
Logic --> DAO
Model --> DAO
```
**图示来源**
- [card_info_apple](file://internal/controller/card_info_apple)
- [logic](file://internal/logic)
- [model](file://internal/model)
- [dao](file://internal/dao)
**本节来源**
- [project_structure](file://)
## 核心组件
系统核心组件包括账户历史记录管理`card_apple_account_info_history`和充值历史记录管理`card_apple_history_info`分别对应账户余额变动和单次充值操作的完整审计日志
**本节来源**
- [v_1_card_apple_account_info_history.go](file://internal/dao/v_1_card_apple_account_info_history.go#L1-L27)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go#L1-L27)
## 架构概述
系统采用典型的分层架构从API接口接收请求经由控制器转发至业务逻辑层逻辑层调用数据访问对象DAO与数据库交互最终返回结构化数据历史记录数据通过实体模型Entity进行映射并在逻辑层进行聚合与处理
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "ControllerV1"
participant Service as "Service"
participant Logic as "Logic"
participant DAO as "DAO"
participant DB as "数据库"
Client->>Controller : 发起历史记录查询请求
Controller->>Service : 调用AppleAccount或AppleOrder服务
Service->>Logic : 转发至具体业务逻辑
Logic->>DAO : 构建查询条件并执行
DAO->>DB : 执行SQL查询
DB-->>DAO : 返回原始数据
DAO-->>Logic : 返回实体列表
Logic-->>Service : 返回处理后的数据
Service-->>Controller : 返回结果
Controller-->>Client : 返回JSON响应
```
**图示来源**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go#L1-L25)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go#L1-L39)
## 详细组件分析
### 充值历史记录管理分析
充值历史记录管理提供基于订单号的详细操作日志查询功能用于追踪单笔充值的完整生命周期
#### 数据结构与查询逻辑
充值历史记录的核心数据结构为`V1CardAppleHistoryInfo`存储于`card_apple_history_info`表中查询逻辑由`GetRechargeDetails`方法实现支持按订单号精确查询并按创建时间倒序排列
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> BuildQuery["构建数据库查询"]
BuildQuery --> SetCondition["设置查询条件: OrderNo"]
SetCondition --> SetOrder["设置排序: CreatedAt DESC"]
SetOrder --> ExecuteQuery["执行数据库查询 ScanAndCount"]
ExecuteQuery --> CheckError{"查询成功?"}
CheckError --> |否| HandleError["返回数据库操作错误"]
CheckError --> |是| ReturnData["返回结果: total, data[]"]
HandleError --> End([结束])
ReturnData --> End
```
**图示来源**
- [recharge_history.go](file://internal/logic/card_apple_order/recharge_history.go#L144-L153)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go#L1-L27)
**本节来源**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go#L1-L25)
- [recharge_history.go](file://internal/logic/card_apple_order/recharge_history.go#L144-L153)
### 账户历史记录管理分析
账户历史记录管理提供更复杂的查询能力支持按账户ID账户名和用户ID进行筛选用于审计特定账户或特定操作员的所有余额变动
#### 数据结构与查询逻辑
账户历史记录的核心数据结构为`V1CardAppleAccountInfoHistory`存储于`card_apple_account_info_history`表中查询逻辑由`GetWalletHistory`方法实现支持多条件组合查询和分页
```mermaid
flowchart TD
Start([开始]) --> InitData["初始化空数据列表"]
InitData --> GetDB["获取数据库连接"]
GetDB --> CheckAccountId{"AccountId是否为空?"}
CheckAccountId --> |否| AddAccountIdFilter["添加AccountId查询条件"]
CheckAccountId --> |是| CheckAccountName{"AccountName是否为空?"}
CheckAccountName --> |否| AddAccountNameFilter["添加AccountName LIKE查询条件"]
CheckAccountName --> |是| CheckUserId{"UserId是否为空?"}
CheckUserId --> |否| QueryUserAccounts["查询用户名下所有账户ID"]
QueryUserAccounts --> AddAccountIdInFilter["添加AccountId IN查询条件"]
CheckUserId --> |是| ApplyPagination["应用分页: Page()"]
AddAccountIdFilter --> ApplyPagination
AddAccountNameFilter --> ApplyPagination
AddAccountIdInFilter --> ApplyPagination
ApplyPagination --> SetOrder["设置排序: CreatedAt DESC"]
SetOrder --> ExecuteQuery["执行数据库查询 ScanAndCount"]
ExecuteQuery --> ReturnResult["返回结果: total, data[]"]
ReturnResult --> End([结束])
```
**图示来源**
- [wallet.go](file://internal/logic/card_apple_account/wallet.go#L56-L78)
- [v_1_card_apple_account_info_history.go](file://internal/dao/v_1_card_apple_account_info_history.go#L1-L27)
**本节来源**
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go#L1-L39)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go#L56-L78)
## 依赖分析
历史记录管理模块依赖于系统的核心服务和数据模型形成了清晰的依赖链
```mermaid
graph TD
A[ControllerV1] --> B[Service.AppleOrder]
A --> C[Service.AppleAccount]
B --> D[Logic.sAppleOrder]
C --> E[Logic.sAppleAccount]
D --> F[DAO.V1CardAppleHistoryInfo]
E --> G[DAO.V1CardAppleAccountInfoHistory]
F --> H[(card_apple_history_info 表)]
G --> I[(card_apple_account_info_history 表)]
C --> J[Service.SysAuth]
J --> K[DAO.V1SysUser]
```
**图示来源**
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go#L1-L25)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go#L1-L39)
- [recharge_history.go](file://internal/logic/card_apple_order/recharge_history.go#L144-L153)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go#L56-L78)
**本节来源**
- [internal/service](file://internal/service)
- [internal/dao](file://internal/dao)
## 性能考虑
系统在设计上已考虑性能优化
1. **索引优化**`card_apple_history_info`表的`order_no``created_at`字段以及`card_apple_account_info_history`表的`account_id``created_at`字段应建立复合索引以加速查询和排序
2. **分页查询**所有列表查询均采用分页机制`Page()`避免一次性加载大量数据
3. **连接查询优化**在账户历史查询中当按用户ID查询时先获取该用户的所有账户ID列表再使用`IN`条件进行查询避免了复杂的表连接
4. **数据一致性**通过事务或原子操作确保账户余额与历史记录的一致性
## 故障排除指南
常见问题及解决方案
- **查询无结果**检查输入的订单号或账户ID是否正确确认数据是否存在
- **查询性能低下**检查相关数据库表的索引是否已建立特别是`order_no``account_id``created_at`字段
- **权限不足错误**确保请求已通过身份验证`SysAuth().LoginWithIFrameAndLogin`调用成功
- **数据库连接错误**检查数据库配置和连接状态
**本节来源**
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go#L1-L39)
- [recharge_history.go](file://internal/logic/card_apple_order/recharge_history.go#L144-L153)
## 结论
Apple卡密历史记录管理系统设计合理功能完整通过分层架构实现了关注点分离利用DAO模式简化了数据库操作系统支持灵活的查询和分页具备良好的可维护性和扩展性建议定期对历史数据表进行归档以维持查询性能并确保关键字段的数据库索引得到维护

View File

@@ -0,0 +1,317 @@
# Apple卡密管理逻辑
<cite>
**本文档中引用的文件**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
- [model.go](file://api/card_info_apple/v1/model.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_apple_account.go](file://internal/logic/card_apple_account/account.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
- [card_apple.go](file://internal/consts/card_apple.go)
- [wallet.go](file://api/fund/v1/wallet.go)
- [form.go](file://api/order/v1/form.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了Apple卡密管理系统的业务逻辑涵盖账户的创建更新删除和状态管理流程以及充值处理历史记录管理与订单和支付系统的集成等核心功能文档深入分析了关键业务方法的实现细节异常处理策略和数据一致性保障机制并提供了性能优化建议和常见问题解决方案
## 项目结构
Apple卡密管理系统采用分层架构主要分为API接口层控制器层服务层逻辑层和数据访问层系统通过清晰的模块划分实现了高内聚低耦合的设计原则
```mermaid
graph TB
subgraph "API层"
A[account_info.go]
B[order.go]
C[config.go]
end
subgraph "控制器层"
D[card_info_apple_v1_*]
end
subgraph "服务层"
E[card_apple_account.go]
F[card_apple_order.go]
end
subgraph "逻辑层"
G[card_apple_account]
H[card_apple_order]
end
subgraph "数据访问层"
I[v_1_card_apple_account_info.go]
J[v_1_card_apple_recharge_info.go]
end
A --> D
B --> D
C --> D
D --> E
D --> F
E --> G
F --> H
G --> I
H --> J
```
**图示来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_apple_account.go](file://internal/logic/card_apple_account/account.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
**章节来源**
- [account_info.go](file://api/card_info_apple/v1/account_info.go)
- [order.go](file://api/card_info_apple/v1/order.go)
- [config.go](file://api/card_info_apple/v1/config.go)
## 核心组件
Apple卡密管理系统的核心组件包括账户管理充值处理状态管理和历史记录等功能模块系统通过服务层和逻辑层的分离实现了业务逻辑与数据访问的解耦
**章节来源**
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_apple_account.go](file://internal/logic/card_apple_account/account.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
## 架构概览
系统采用典型的分层架构设计从上到下分别为API接口层控制器层服务层逻辑层和数据访问层这种设计模式确保了系统的可维护性和可扩展性
```mermaid
graph TD
A[API接口] --> B[控制器]
B --> C[服务]
C --> D[业务逻辑]
D --> E[数据访问]
E --> F[(数据库)]
G[外部系统] --> |iTunes回调| B
H[订单系统] --> |订单集成| C
I[支付系统] --> |支付集成| C
```
**图示来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [form.go](file://api/order/v1/form.go)
- [wallet.go](file://api/fund/v1/wallet.go)
## 详细组件分析
### 账户管理分析
Apple卡密账户管理模块负责账户的全生命周期管理包括创建更新删除和状态变更等操作
#### 账户创建流程
```mermaid
sequenceDiagram
participant 前端 as 前端应用
participant 控制器 as 控制器
participant 服务 as 服务层
participant 逻辑 as 逻辑层
participant 数据库 as 数据访问层
前端->>控制器 : 创建账户请求
控制器->>控制器 : 参数验证
控制器->>服务 : 调用创建方法
服务->>逻辑 : 执行业务逻辑
逻辑->>逻辑 : 生成账户信息
逻辑->>数据库 : 保存账户数据
数据库-->>逻辑 : 返回结果
逻辑-->>服务 : 返回账户对象
服务-->>控制器 : 返回结果
控制器-->>前端 : 返回成功响应
```
**图示来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [card_apple_account.go](file://internal/logic/card_apple_account/account.go)
- [v_1_card_apple_account_info.go](file://internal/dao/v_1_card_apple_account_info.go)
#### 账户状态管理
```mermaid
stateDiagram-v2
[*] --> 正常
正常 --> 暂停 : 暂停操作
暂停 --> 正常 : 恢复操作
正常 --> 删除 : 删除操作
暂停 --> 删除 : 删除操作
删除 --> [*]
note right of 正常
可进行充值和消费
end note
note right of 暂停
账户被临时禁用
end note
note right of 删除
账户数据被标记删除
end note
```
**图示来源**
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_apple_account.go](file://internal/logic/card_apple_account/status.go)
**章节来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
### 充值处理分析
Apple卡密充值模块负责处理用户提交的充值请求包括iTunes回调处理重复卡密检测和状态同步等核心功能
#### 充值提交流程
```mermaid
flowchart TD
A[用户提交充值] --> B{参数验证}
B --> |失败| C[返回错误]
B --> |成功| D[检查重复卡密]
D --> |已存在| E[处理重复卡密]
D --> |新卡密| F[创建充值记录]
F --> G[调用iTunes验证]
G --> H{iTunes响应}
H --> |成功| I[更新账户余额]
H --> |失败| J[记录失败原因]
I --> K[更新充值状态]
J --> K
K --> L[返回结果]
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
#### iTunes回调处理
```mermaid
sequenceDiagram
participant iTunes as iTunes服务器
participant 控制器 as 控制器
participant 服务 as 服务层
participant 逻辑 as 逻辑层
iTunes->>控制器 : 发送回调通知
控制器->>控制器 : 验证签名
控制器->>服务 : 处理回调
服务->>逻辑 : 更新充值状态
逻辑->>逻辑 : 同步账户信息
逻辑-->>服务 : 返回结果
服务-->>控制器 : 返回确认
控制器-->>iTunes : 返回成功响应
```
**图示来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/callback.go)
**章节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_info_apple_v1_recharge_duplicated_card_pass.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_duplicated_card_pass.go)
### 系统集成分析
Apple卡密管理系统与订单系统和支付系统实现了深度集成确保了业务流程的完整性和数据一致性
#### 与订单系统集成
```mermaid
sequenceDiagram
participant 卡密系统 as 卡密系统
participant 订单系统 as 订单系统
卡密系统->>订单系统 : 创建订单请求
订单系统-->>卡密系统 : 返回订单ID
卡密系统->>卡密系统 : 关联充值记录
卡密系统->>订单系统 : 更新订单状态
订单系统-->>卡密系统 : 确认状态更新
```
**图示来源**
- [form.go](file://api/order/v1/form.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
#### 与支付系统集成
```mermaid
sequenceDiagram
participant 卡密系统 as 卡密系统
participant 支付系统 as 支付系统
卡密系统->>支付系统 : 查询支付配置
支付系统-->>卡密系统 : 返回配置信息
卡密系统->>支付系统 : 提交支付记录
支付系统-->>卡密系统 : 返回处理结果
```
**图示来源**
- [wallet.go](file://api/fund/v1/wallet.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
**章节来源**
- [form.go](file://api/order/v1/form.go)
- [wallet.go](file://api/fund/v1/wallet.go)
## 依赖分析
Apple卡密管理系统依赖于多个内部和外部组件确保了系统的完整功能和稳定性
```mermaid
graph TD
A[Apple卡密系统] --> B[iTunes验证服务]
A --> C[订单管理系统]
A --> D[支付管理系统]
A --> E[用户权限系统]
A --> F[配置管理系统]
A --> G[数据库服务]
H[外部系统] --> A
I[内部服务] --> A
```
**图示来源**
- [go.mod](file://go.mod)
- [card_apple.go](file://internal/consts/card_apple.go)
**章节来源**
- [go.mod](file://go.mod)
- [card_apple.go](file://internal/consts/card_apple.go)
## 性能考虑
在高并发场景下Apple卡密管理系统需要考虑多个性能优化点包括数据库查询优化缓存策略和并发控制等
- **数据库优化**对关键查询字段建立索引优化SQL语句
- **缓存策略**使用Redis缓存频繁访问的数据减少数据库压力
- **并发控制**使用分布式锁防止重复充值和账户余额超扣
- **异步处理**将非关键操作异步化提高系统响应速度
## 故障排除指南
本节提供Apple卡密管理系统常见问题的解决方案和调试建议
**章节来源**
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/order.go)
## 结论
Apple卡密管理系统通过清晰的分层架构和模块化设计实现了账户管理充值处理和系统集成等核心功能系统具备良好的可维护性和可扩展性能够满足业务发展的需求建议持续优化性能瓶颈加强异常处理和监控能力确保系统的稳定运行

View File

@@ -0,0 +1,350 @@
# Apple卡密账户管理
<cite>
**本文档引用的文件**
- [account.go](file://internal/logic/card_apple_account/account.go)
- [schdule.go](file://internal/logic/card_apple_account/schdule.go)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_info_apple_v1_card_info_update.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update.go)
- [card_info_apple_v1_card_info_delete.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_delete.go)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go)
- [card_info_apple_v1_card_info_update_status.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_update_status.go)
- [card_info_apple_v1_card_history_info_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_history_info_list.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [v_1_card_apple_account_info.go](file://internal/model/do/v_1_card_apple_account_info.go)
- [v_1_card_apple_account_info.go](file://internal/model/entity/v_1_card_apple_account_info.go)
- [card_apple.go](file://internal/consts/card_apple.go)
- [config.go](file://utility/config/config.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录)
## 简介
本文档详细阐述了Apple卡密账户管理系统的实现细节包括账户的创建更新删除和状态管理流程系统实现了完整的账户生命周期管理涵盖账户激活暂停恢复等状态转换逻辑文档还解释了账户与商户订单系统的集成关系提供了关键业务方法的实现细节记录了异常处理策略和数据一致性保障机制并包含性能优化建议和常见问题解决方案
## 项目结构
Apple卡密账户管理系统采用分层架构设计主要包含API接口层业务逻辑层数据访问层和配置层系统通过API接口暴露账户管理功能由业务逻辑层处理核心业务规则数据访问层负责与数据库交互配置层管理系统的各项配置参数
```mermaid
graph TB
subgraph "API接口层"
API[card_info_apple/v1]
end
subgraph "业务逻辑层"
Logic[internal/logic/card_apple_account]
end
subgraph "服务层"
Service[internal/service/card_apple_account]
end
subgraph "数据访问层"
DAO[internal/dao]
Model[internal/model]
end
subgraph "配置层"
Config[utility/config]
Consts[internal/consts]
end
API --> Logic
Logic --> Service
Service --> DAO
DAO --> Model
Config --> Service
Consts --> Service
```
**图表来源**
- [card_info_apple/v1](file://api/card_info_apple/v1)
- [internal/logic/card_apple_account](file://internal/logic/card_apple_account)
- [internal/service/card_apple_account.go](file://internal/service/card_apple_account.go)
- [internal/dao](file://internal/dao)
- [internal/model](file://internal/model)
- [utility/config](file://utility/config)
- [internal/consts](file://internal/consts)
**章节来源**
- [internal/logic/card_apple_account](file://internal/logic/card_apple_account)
- [api/card_info_apple/v1](file://api/card_info_apple/v1)
## 核心组件
Apple卡密账户管理系统的核心组件包括账户管理服务状态管理模块钱包管理模块和账户分配算法这些组件协同工作确保账户的创建更新删除和状态转换能够正确执行并保证数据的一致性和系统的稳定性
**章节来源**
- [account.go](file://internal/logic/card_apple_account/account.go)
- [schdule.go](file://internal/logic/card_apple_account/schdule.go)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go)
## 架构概述
系统采用典型的分层架构各层职责分明通过清晰的接口进行交互API层接收外部请求调用服务层提供的接口服务层协调业务逻辑层完成具体业务操作业务逻辑层实现核心业务规则并调用数据访问层进行数据持久化
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API控制器"
participant Service as "服务层"
participant Logic as "业务逻辑层"
participant DAO as "数据访问层"
participant DB as "数据库"
Client->>API : 创建账户请求
API->>Service : 调用Add方法
Service->>Logic : 执行添加逻辑
Logic->>DAO : 插入账户数据
DAO->>DB : 执行INSERT语句
DB-->>DAO : 返回结果
DAO-->>Logic : 返回操作结果
Logic-->>Service : 返回成功/失败
Service-->>API : 返回结果
API-->>Client : 返回响应
Note over Client,DB : 账户创建流程
```
**图表来源**
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go)
- [card_apple_account.go](file://internal/service/card_apple_account.go)
- [account.go](file://internal/logic/card_apple_account/account.go)
- [v_1_card_apple_account_info.go](file://internal/model/do/v_1_card_apple_account_info.go)
## 详细组件分析
### 账户管理分析
账户管理组件负责处理Apple卡密账户的全生命周期管理包括创建更新删除和查询等操作系统通过一系列接口和方法实现这些功能确保账户数据的完整性和一致性
#### 账户创建流程
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> CheckExistence["检查账户是否已存在"]
CheckExistence --> IsExist{"账户已存在?"}
IsExist --> |是| ReturnError["返回错误: 账户已存在"]
IsExist --> |否| GenerateUUID["生成账户UUID"]
GenerateUUID --> SetDefaultStatus["设置默认状态为正常"]
SetDefaultStatus --> InsertDB["插入数据库"]
InsertDB --> IsSuccess{"插入成功?"}
IsSuccess --> |是| UpdateCache["更新缓存"]
IsSuccess --> |否| HandleDBError["处理数据库错误"]
UpdateCache --> End([结束])
HandleDBError --> End
```
**图表来源**
- [account.go](file://internal/logic/card_apple_account/account.go#L33-L58)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go#L15-L42)
**章节来源**
- [account.go](file://internal/logic/card_apple_account/account.go#L33-L58)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go#L15-L42)
#### 账户状态管理
```mermaid
stateDiagram-v2
[*] --> Normal
Normal --> Forbidden : 暂停账户
Forbidden --> Normal : 恢复账户
Normal --> Limited : 达到充值限制
Limited --> Normal : 重置限制
Normal --> WrongPassword : 密码错误
WrongPassword --> Normal : 修正密码
Normal --> ForbiddenByLowRecharge : 低于最小充值金额
ForbiddenByLowRecharge --> Normal : 重新激活
state Normal {
[*] --> Active
Active --> Processing : 开始充值
Processing --> Active : 充值完成
Processing --> Limited : 达到限制
}
```
**图表来源**
- [card_apple.go](file://internal/consts/card_apple.go#L15-L18)
- [account.go](file://internal/logic/card_apple_account/account.go#L38-L47)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go#L13-L33)
**章节来源**
- [card_apple.go](file://internal/consts/card_apple.go#L15-L18)
- [account.go](file://internal/logic/card_apple_account/account.go#L38-L47)
- [card_info_apple_v1_card_info_suspend_or_continue.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_suspend_or_continue.go#L13-L33)
### 账户分配算法
账户分配算法是系统的核心组件之一负责在多个可用账户中选择最合适的账户来处理充值订单系统提供了多种分配策略以适应不同的业务场景和性能要求
#### 账户分配流程
```mermaid
flowchart TD
Start([开始]) --> GetCurrentAccount["获取当前目标账户"]
GetCurrentAccount --> FindAvailableAccounts["查找可用账户"]
FindAvailableAccounts --> FilterByStatus["筛选正常状态账户"]
FilterByStatus --> CheckBalance["检查商户余额"]
CheckBalance --> IsEnough{"余额充足?"}
IsEnough --> |否| ReturnEmpty["返回空结果"]
IsEnough --> |是| SelectAccount["选择最合适的账户"]
SelectAccount --> UpdateTargetAccount["更新目标账户缓存"]
UpdateTargetAccount --> SetAccountLimit["设置账户调用限制"]
SetAccountLimit --> End([返回选中账户])
```
**图表来源**
- [schdule.go](file://internal/logic/card_apple_account/schdule.go#L0-L27)
- [account.go](file://internal/logic/card_apple_account/account.go#L198-L203)
**章节来源**
- [schdule.go](file://internal/logic/card_apple_account/schdule.go#L0-L27)
- [account.go](file://internal/logic/card_apple_account/account.go#L198-L203)
## 依赖分析
系统各组件之间存在明确的依赖关系通过接口定义和依赖注入实现松耦合这种设计使得系统更易于维护和扩展同时也便于单元测试
```mermaid
classDiagram
class IAppleAccount {
+Add(ctx, data, tx) err
+Update(ctx, data, tx) err
+Delete(ctx, id, tx) err
+List(ctx, input) total, data, err
+GetDetailById(ctx, id) data, err
+ModifyStatus(ctx, id, status, tx) err
+GetAccordingAccount(ctx, machineId, amount) data, err
}
class sAppleAccount {
-Add(ctx, data, tx) err
-Update(ctx, data, tx) err
-Delete(ctx, id, tx) err
-List(ctx, input) total, data, err
-GetDetailById(ctx, id) data, err
-ModifyStatus(ctx, id, status, tx) err
-GetAccordingAccount(ctx, machineId, amount) data, err
}
class ControllerV1 {
+CardInfoCreate(ctx, req) res, err
+CardInfoUpdate(ctx, req) res, err
+CardInfoDelete(ctx, req) res, err
+CardInfoSuspendOrContinue(ctx, req) res, err
+CardInfoUpdateStatus(ctx, req) res, err
}
IAppleAccount <|-- sAppleAccount : "实现"
ControllerV1 --> IAppleAccount : "依赖"
sAppleAccount --> DAO : "依赖"
DAO --> DB : "依赖"
note right of IAppleAccount
服务接口定义了Apple账户管理
所有必须实现的方法
end
note left of sAppleAccount
具体实现类包含了所有
业务逻辑的实现细节
end
```
**图表来源**
- [card_apple_account.go](file://internal/service/card_apple_account.go#L18-L77)
- [account.go](file://internal/logic/card_apple_account/account.go#L31-L31)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go#L15-L42)
**章节来源**
- [card_apple_account.go](file://internal/service/card_apple_account.go#L18-L77)
- [account.go](file://internal/logic/card_apple_account/account.go#L31-L31)
- [card_info_apple_v1_card_info_create.go](file://internal/controller/card_info_apple/card_info_apple_v1_card_info_create.go#L15-L42)
## 性能考虑
系统在设计时充分考虑了性能因素通过缓存机制数据库优化和并发控制等手段确保系统在高负载下的稳定运行账户分配算法特别针对多线程环境进行了优化避免了性能瓶颈
**章节来源**
- [schdule.go](file://internal/logic/card_apple_account/schdule.go#L0-L27)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go#L0-L19)
## 故障排除指南
### 常见问题及解决方案
当遇到账户管理相关问题时可以按照以下步骤进行排查
1. **账户创建失败**检查账户名是否重复确保上传用户ID有效
2. **状态更新失败**验证账户ID是否存在确认当前状态是否允许转换
3. **分配账户失败**检查是否有可用的正常状态账户确认商户余额是否充足
4. **钱包余额不一致**运行余额校正功能检查流水记录是否完整
**章节来源**
- [account.go](file://internal/logic/card_apple_account/account.go)
- [wallet.go](file://internal/logic/card_apple_account/wallet.go)
## 结论
Apple卡密账户管理系统通过清晰的分层架构和模块化设计实现了完整的账户生命周期管理功能系统不仅提供了基本的CRUD操作还包含了复杂的状态管理账户分配算法和数据一致性保障机制通过合理的缓存策略和并发控制系统能够在高负载环境下稳定运行满足业务需求
## 附录
### 数据库表结构
```mermaid
erDiagram
CARD_APPLE_ACCOUNT_INFO {
string id PK
string account UK
string password
float balance
float balance_itunes
int status
float today_recharge_amount
int today_recharge_count
datetime today_recharge_datetime
string created_user_id FK
string created_user_role
int max_amount_limit
int max_count_limit
string remark
datetime created_at
datetime updated_at
datetime deleted_at
}
CARD_APPLE_ACCOUNT_INFO_HISTORY {
string id PK
string account_id FK
string order_no
float amount
string account_name
string created_user_id
float balance_before_itunes
float balance_after_itunes
float balance_before_auto_increment
float balance_after_auto_increment
string transaction_type
string description
datetime created_at
datetime updated_at
}
SYS_USER {
string id PK
string username UK
string nick_name
string password
string avatar
string phone
string email
int status
datetime created_at
datetime updated_at
datetime deleted_at
}
CARD_APPLE_ACCOUNT_INFO ||--o{ CARD_APPLE_ACCOUNT_INFO_HISTORY : "包含"
SYS_USER ||--o{ CARD_APPLE_ACCOUNT_INFO : "创建"
```
**图表来源**
- [v_1_card_apple_account_info.go](file://internal/model/do/v_1_card_apple_account_info.go#L12-L31)
- [v_1_card_apple_account_info.go](file://internal/model/entity/v_1_card_apple_account_info.go#L11-L29)
### 状态码定义
| 状态码 | 名称 | 描述 |
|--------|------|------|
| 1 | AppleAccountNormal | 账户正常可用于充值 |
| 2 | AppleAccountForbidden | 账户被禁用不可用 |
| 3 | AppleAccountLimited | 账户达到单日充值限制 |
| 4 | AppleAccountWrongPassword | 账户密码错误 |
| 5 | AppleAccountForbiddenByLowRecharge | 因低于最小充值金额被冻结 |
**图表来源**
- [card_apple.go](file://internal/consts/card_apple.go#L15-L18)

View File

@@ -0,0 +1,264 @@
# 京东卡密兑换处理
<cite>
**本文档引用文件**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [card_redeem_cookie.go](file://internal/model/card_redeem_cookie.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
- [v_1_card_redeem_cookie_info.go](file://internal/dao/v_1_card_redeem_cookie_info.go)
- [v_1_card_redeem_cookie_order_jd.go](file://internal/dao/v_1_card_redeem_cookie_order_jd.go)
- [entity/v_1_card_redeem_cookie_order.go](file://internal/model/entity/v_1_card_redeem_cookie_order.go)
- [entity/v_1_card_redeem_cookie_info.go](file://internal/model/entity/v_1_card_redeem_cookie_info.go)
- [entity/v_1_card_redeem_cookie_order_jd.go](file://internal/model/entity/v_1_card_redeem_cookie_order_jd.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了京东卡密兑换处理系统的核心功能包括兑换订单的创建状态管理历史查询等关键流程文档深入分析了订单生命周期状态转换规则和持久化机制详细说明了兑换请求的处理流程涵盖参数验证库存检查交易执行等环节同时文档解释了订单与账户支付系统的集成模式记录了兑换处理中的异常处理策略幂等性保障和数据一致性机制并提供了性能优化建议和常见问题解决方案
## 项目结构
京东卡密兑换处理功能主要集中在 `api/card_redeem_jd` `internal` 目录下API 接口定义在 `api/card_redeem_jd/v1` 核心业务逻辑位于 `internal/logic/card_redeem_cookie`数据访问层在 `internal/dao`服务接口在 `internal/service`数据模型在 `internal/model/entity`常量定义在 `internal/consts` 目录下用于统一管理订单状态账号状态等枚举值
```mermaid
graph TB
subgraph "API层"
A[api/card_redeem_jd/v1/order.go]
end
subgraph "控制层"
B[internal/controller/card_redeem_jd]
end
subgraph "服务层"
C[internal/service/card_redeem_cookie.go]
end
subgraph "逻辑层"
D[internal/logic/card_redeem_cookie/order.go]
end
subgraph "数据访问层"
E[internal/dao/v_1_card_redeem_cookie_*.go]
end
subgraph "实体层"
F[internal/model/entity/v_1_card_redeem_cookie_*.go]
end
A --> B
B --> C
C --> D
D --> E
E --> F
```
**图示来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
- [entity/v_1_card_redeem_cookie_order.go](file://internal/model/entity/v_1_card_redeem_cookie_order.go)
**本节来源**
- [api/card_redeem_jd/v1/order.go](file://api/card_redeem_jd/v1/order.go)
- [internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
## 核心组件
京东卡密兑换处理的核心组件包括订单管理账号管理状态机和持久化层订单管理负责处理兑换请求的创建查询和状态更新账号管理负责维护京东账号Cookie的状态和调度状态机定义了订单和账号的完整生命周期持久化层通过数据库表存储所有关键数据系统通过 `CardRedeemCookie` 服务接口协调各组件确保兑换流程的原子性和一致性
**本节来源**
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
## 架构概览
系统采用分层架构从上至下分为API层控制层服务层逻辑层数据访问层和实体层API层定义了HTTP接口控制层处理请求并调用服务服务层提供统一的业务接口逻辑层实现具体的业务规则数据访问层与数据库交互实体层映射数据库表结构这种分层设计确保了代码的高内聚低耦合便于维护和扩展
```mermaid
graph TD
A[客户端] --> B[API接口]
B --> C[控制器]
C --> D[服务接口]
D --> E[业务逻辑]
E --> F[数据访问对象]
F --> G[(数据库)]
style A fill:#f9f,stroke:#333
style G fill:#ccf,stroke:#333
```
**图示来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
## 详细组件分析
### 兑换订单处理分析
兑换订单处理是系统的核心功能主要涉及订单创建状态管理和查询当用户发起兑换请求时系统首先进行参数验证然后创建或查找订单最后调用京东接口完成兑换
#### 对象导向组件
```mermaid
classDiagram
class V1CardRedeemCookieOrder {
+int id
+string orderNo
+string bankOrderId
+float orderAmount
+string status
+string note
+int cookieId
+string jdOrderNo
+datetime createdAt
+datetime updatedAt
}
class V1CardRedeemCookieInfo {
+int id
+string name
+string cookie
+string status
+uint failCount
+datetime createdAt
+datetime updatedAt
}
class V1CardRedeemCookieOrderJd {
+uint id
+int cookieOrderId
+int cookieAccountId
+string responseData
+string status
+string payId
+string webPayLink
+string clientPayLink
+string orderNo
+string userAgent
+string userClient
+string note
+datetime createdAt
+datetime updatedAt
+string cardNo
+string cardPassword
+string category
}
V1CardRedeemCookieOrder --> V1CardReedemCookieInfo : "使用"
V1CardReedemCookieOrder --> V1CardReedemCookieOrderJd : "包含"
```
**图示来源**
- [entity/v_1_card_redeem_cookie_order.go](file://internal/model/entity/v_1_card_redeem_cookie_order.go)
- [entity/v_1_card_redeem_cookie_info.go](file://internal/model/entity/v_1_card_redeem_cookie_info.go)
- [entity/v_1_card_redeem_cookie_order_jd.go](file://internal/model/entity/v_1_card_redeem_cookie_order_jd.go)
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "逻辑层"
participant DB as "数据库"
Client->>Controller : POST /cookieInfo/jd/order/placeOrder
Controller->>Service : PlaceOrder(请求参数)
Service->>Logic : PlaceOrder(输入模型)
Logic->>Logic : 获取或创建订单
Logic->>Logic : 调度京东账号
Logic->>Logic : 调用京东接口下单
Logic->>DB : 更新订单状态
DB-->>Logic : 操作结果
Logic-->>Service : 返回订单信息
Service-->>Controller : 返回结果
Controller-->>Client : 返回支付链接
```
**图示来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
#### 复杂逻辑组件
```mermaid
flowchart TD
Start([开始下单]) --> ValidateInput["验证输入参数"]
ValidateInput --> CheckOrder{"订单是否存在?"}
CheckOrder --> |是| GetOrder["获取现有订单"]
CheckOrder --> |否| CreateOrder["创建新订单"]
CreateOrder --> InitOrder["初始化订单状态为init"]
GetOrder --> CheckStatus{"订单状态为success?"}
CheckStatus --> |是| ReturnSuccess["直接返回成功"]
CheckStatus --> |否| ScheduleAccount["调度京东账号"]
ScheduleAccount --> CallJdApi["调用京东接口下单"]
CallJdApi --> CheckResult{"下单成功?"}
CheckResult --> |是| UpdateStatusSuccess["更新状态为placeSuccess"]
CheckResult --> |否| UpdateStatusFail["更新状态为placeFail"]
UpdateStatusSuccess --> ReturnPayLink["返回支付链接"]
UpdateStatusFail --> ReturnError["返回错误信息"]
ReturnSuccess --> End([结束])
ReturnPayLink --> End
ReturnError --> End
```
**图示来源**
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [card_redeem_cookie.go](file://internal/model/card_redeem_cookie.go)
**本节来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
## 依赖分析
系统内部组件之间存在明确的依赖关系API层依赖于控制器控制器依赖于服务接口服务接口依赖于具体的逻辑实现逻辑实现依赖于数据访问对象数据访问对象依赖于数据库实体外部依赖包括数据库通过GORM操作京东API通过integration包调用和配置管理通过utility/config系统通过接口隔离和依赖注入确保了组件间的松耦合
```mermaid
graph LR
A[API] --> B[Controller]
B --> C[Service Interface]
C --> D[Logic Implementation]
D --> E[DAO]
E --> F[Entity]
F --> G[(Database)]
D --> H[External API]
D --> I[Config]
style A fill:#f96,stroke:#333
style G fill:#ccf,stroke:#333
style H fill:#6f9,stroke:#333
```
**图示来源**
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
- [entity/v_1_card_redeem_cookie_order.go](file://internal/model/entity/v_1_card_redeem_cookie_order.go)
**本节来源**
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_order.go](file://internal/dao/v_1_card_redeem_cookie_order.go)
## 性能考虑
系统在性能方面采取了多项优化措施首先通过 `gmlock` 实现了基于订单ID的分布式锁防止同一订单被重复处理保障了幂等性其次数据库查询使用了索引优化如在 `bank_order_id` `created_at` 字段上建立索引确保查询效率此外系统采用了事务管理确保订单创建和状态更新的原子性对于高并发场景建议引入缓存机制如Redis缓存热门商品信息和账号状态减轻数据库压力
## 故障排除指南
常见问题包括下单失败支付链接为空账号调度失败等对于下单失败应检查京东API返回的错误信息通常记录在订单的 `note` 字段中支付链接为空可能是由于京东接口未返回支付链接需检查请求参数和账号状态账号调度失败可能是因为所有账号都处于禁用或过期状态需检查 `v1_card_redeem_cookie_info` 表中的账号状态系统日志记录在 `glog` 可通过日志级别InfoError快速定位问题
**本节来源**
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [v_1_card_redeem_cookie_info.go](file://internal/model/entity/v_1_card_redeem_cookie_info.go)
## 结论
京东卡密兑换处理系统设计合理功能完整具备良好的可维护性和扩展性系统通过清晰的分层架构和严格的接口定义实现了高内聚低耦合的设计目标状态机和持久化机制确保了数据的一致性和可靠性未来可考虑引入消息队列解耦订单处理流程进一步提升系统的吞吐量和容错能力

View File

@@ -0,0 +1,248 @@
# 京东卡密分组管理
<cite>
**本文档引用文件**
- [group.go](file://internal/logic/card_redeem_account/group.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem.go](file://internal/model/card_redeem.go)
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [consts.go](file://internal/consts/card_redeem.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了京东卡密分组管理系统的功能实现涵盖账户分组的创建更新删除和统计功能系统通过分组机制实现对京东卡密账户的高效组织与管理支持分组级别的操作权限控制和统计信息计算文档深入分析了分组数据结构成员管理规则统计计算逻辑以及异常处理机制为开发者和运维人员提供全面的技术参考
## 项目结构
京东卡密分组管理功能主要分布在后端项目的特定目录中采用分层架构设计包括API接口层服务层逻辑层和数据访问层各层职责分明确保代码的可维护性和可扩展性
```mermaid
graph TD
subgraph "API接口层"
A[card_info_jd/v1/account.go]
B[card_info_walmart/v1/group.go]
end
subgraph "服务层"
C[service/card_redeem_account.go]
end
subgraph "逻辑层"
D[logic/card_redeem_account/group.go]
E[logic/card_redeem_account/summary.go]
end
subgraph "数据访问层"
F[dao/v_1_card_redeem_account_group.go]
G[dao/v_1_card_redeem_account_info.go]
end
subgraph "模型层"
H[model/entity/v_1_card_redeem_account_group.go]
I[model/entity/v_1_card_redeem_account_info.go]
end
A --> C
B --> C
C --> D
C --> E
D --> F
E --> G
D --> H
E --> I
```
**图示来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L1-L20)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L1-L20)
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go#L1-L10)
**本节来源**
- [internal/logic/card_redeem_account/group.go](file://internal/logic/card_redeem_account/group.go#L1-L50)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go#L1-L30)
## 核心组件
京东卡密分组管理的核心组件包括分组管理服务分组数据模型和分组统计逻辑这些组件协同工作实现分组的全生命周期管理
**本节来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L19-L31)
- [card_redeem.go](file://internal/model/card_redeem.go#L1-L20)
## 架构概述
系统采用典型的分层架构从上至下分为API接口层服务层逻辑层和数据访问层API接口层接收外部请求服务层定义业务接口逻辑层实现具体业务逻辑数据访问层负责与数据库交互
```mermaid
graph TB
subgraph "表现层"
API[API接口]
end
subgraph "服务层"
Service[分组管理服务]
end
subgraph "逻辑层"
Logic[分组管理逻辑]
end
subgraph "数据层"
DAO[数据访问对象]
DB[(数据库)]
end
API --> Service
Service --> Logic
Logic --> DAO
DAO --> DB
```
**图示来源**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L10-L50)
- [group.go](file://internal/logic/card_redeem_account/group.go#L20-L40)
## 详细组件分析
### 分组管理功能分析
分组管理功能提供了完整的CRUD操作包括分组的创建查询更新和删除每个操作都经过精心设计确保数据的一致性和安全性
#### 分组数据结构
```mermaid
classDiagram
class V1CardRedeemAccountGroup {
+int id
+string name
+string notes
+string category
+string createdUserId
+*gtime.Time createdAt
+*gtime.Time updatedAt
+*gtime.Time deletedAt
}
class V1CardRedeemAccountInfo {
+string id
+int groupId
+string name
+string cookie
+string nickname
+string username
+string createUserId
+string category
+float64 amountTotalSum
+float64 amountTodaySum
+float64 balance
+float64 effectiveBalance
+int status
+int maxCountLimit
+int maxAmountLimit
+int amountTotalCount
+int amountTodayCount
+bool accountStatus
+string remark
+*gtime.Time createdAt
+*gtime.Time updatedAt
+*gtime.Time deletedAt
}
V1CardRedeemAccountInfo --> V1CardRedeemAccountGroup : "belongsTo"
V1CardRedeemAccountGroup --> V1CardRedeemAccountInfo : "hasMany"
```
**图示来源**
- [v_1_card_redeem_account_group.go](file://internal/model/entity/v_1_card_redeem_account_group.go#L11-L20)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go#L1-L35)
#### 分组创建流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Service as "分组服务"
participant Logic as "分组逻辑"
participant DAO as "数据访问对象"
participant DB as "数据库"
Client->>Service : 调用GroupAdd
Service->>Logic : 转发创建请求
Logic->>DAO : 构建插入语句
DAO->>DB : 执行插入操作
DB-->>DAO : 返回插入ID
DAO-->>Logic : 返回结果
Logic-->>Service : 返回分组ID
Service-->>Client : 返回成功响应
Note over Client,DB : 分组创建成功
```
**图示来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L19-L31)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L50-L60)
#### 分组统计计算逻辑
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> InputValid{"参数有效?"}
InputValid --> |否| ReturnError["返回错误"]
InputValid --> |是| QueryAccounts["查询关联账户"]
QueryAccounts --> GetAccountList["获取账户列表"]
GetAccountList --> QueryOrders["查询订单数据"]
QueryOrders --> CalculateStats["计算统计指标"]
CalculateStats --> TotalAccount["统计账户总数"]
CalculateStats --> ActiveAccount["统计活跃账户"]
CalculateStats --> OrderCount["统计订单数量"]
CalculateStats --> OrderAmount["统计订单金额"]
CalculateStats --> SuccessCount["统计成功订单"]
CalculateStats --> SuccessAmount["统计成功金额"]
CalculateStats --> ReturnResult["返回统计结果"]
ReturnError --> End([结束])
ReturnResult --> End
```
**图示来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L132-L218)
- [card_redeem.go](file://internal/model/card_redeem.go#L200-L208)
**本节来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L1-L218)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L1-L120)
- [card_redeem.go](file://internal/model/card_redeem.go#L1-L208)
## 依赖分析
分组管理功能依赖于多个核心组件包括数据库访问层服务接口和数据模型这些依赖关系确保了功能的完整性和稳定性
```mermaid
graph TD
GroupService[分组管理服务] --> GroupLogic[分组管理逻辑]
GroupService --> AccountLogic[账户管理逻辑]
GroupLogic --> GroupDAO[分组数据访问]
GroupLogic --> AccountDAO[账户数据访问]
GroupDAO --> Database[数据库]
AccountDAO --> Database
GroupService --> Consts[常量定义]
GroupLogic --> Utils[工具函数]
```
**图示来源**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L1-L20)
- [group.go](file://internal/logic/card_redeem_account/group.go#L1-L20)
**本节来源**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L1-L120)
- [group.go](file://internal/logic/card_redeem_account/group.go#L1-L218)
## 性能考虑
在设计分组管理功能时充分考虑了性能优化通过合理的数据库索引事务管理和并发控制确保系统在高负载下的稳定运行
- **数据库索引**在分组名称创建用户ID和创建时间等字段上建立索引提高查询效率
- **事务管理**关键操作使用数据库事务确保数据一致性
- **并发控制**使用全局锁防止分组重复创建
- **批量操作**支持批量添加和更新减少数据库交互次数
- **缓存机制**考虑引入缓存层减少对数据库的直接访问
## 故障排除指南
在使用分组管理功能时可能会遇到各种问题以下是一些常见问题及其解决方案
**本节来源**
- [group.go](file://internal/logic/card_redeem_account/group.go#L34-L51)
- [group.go](file://internal/logic/card_redeem_account/group.go#L114-L131)
## 结论
京东卡密分组管理系统通过完善的分层架构和精心设计的业务逻辑实现了对卡密账户的高效管理系统具备良好的可扩展性和稳定性能够满足大规模业务需求通过持续优化和改进系统性能和用户体验将不断提升

View File

@@ -0,0 +1,275 @@
# 京东卡密管理逻辑
<cite>
**本文档引用文件**
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go)
- [card_info_jd_v1_jd_account_update.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_update.go)
- [card_info_jd_v1_jd_account_delete.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_delete.go)
- [card_info_jd_v1_jd_account_update_status.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_update_status.go)
- [card_redeem_jd_v1_account_add.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_add.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go)
- [operation.go](file://internal/logic/card_redeem_account/operation.go)
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [place.go](file://internal/logic/card_redeem_cookie/place.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [v_1_card_redeem_order_info.go](file://internal/model/entity/v_1_card_redeem_order_info.go)
</cite>
## 目录
1. [简介](#简介)
2. [京东卡密账户管理](#京东卡密账户管理)
3. [京东卡密兑换流程](#京东卡密兑换流程)
4. [系统集成模式](#系统集成模式)
5. [异常处理与数据一致性](#异常处理与数据一致性)
6. [性能优化建议](#性能优化建议)
7. [常见问题解决方案](#常见问题解决方案)
## 简介
本文档详细阐述了京东卡密管理系统的业务逻辑涵盖账户的创建更新删除和状态管理以及卡密兑换的核心流程系统通过集成京东平台的API接口实现了自动化卡密兑换功能支持账户分组扣款规则和历史记录管理文档还详细说明了与订单系统和支付系统的集成模式以及异常处理策略和数据一致性保障机制
## 京东卡密账户管理
京东卡密账户管理模块负责京东卡密账户的全生命周期管理包括账户的创建更新删除和状态变更系统通过`CardRedeemAccount`服务提供统一的账户管理接口支持对账户信息的增删改查操作
账户创建时系统会验证提供的Cookie有效性并查询账户余额信息每个账户包含基本信息如用户名昵称余额以及业务配置如最大充值金额限制最大充值次数限制等账户支持分组管理便于按业务需求进行分类
```mermaid
classDiagram
class V1CardRedeemAccountInfo {
+string id
+int groupId
+string name
+string cookie
+string nickname
+string username
+string createUserId
+string category
+float64 balance
+float64 effectiveBalance
+int status
+int maxCountLimit
+int maxAmountLimit
+bool accountStatus
+string remark
+*gtime.Time createdAt
+*gtime.Time updatedAt
+*gtime.Time deletedAt
}
class RedeemAccountAddInput {
+string Category
+bool AccountStatus
+int Status
+string CreateUserId
+string Cookie
+string Username
+string Nickname
+string Name
+int GroupId
+float64 Balance
+int MaxAmountLimit
+int MaxCountLimit
+string Remark
}
class RedeemAccountUpdateInput {
+CommonStrId CommonStrId
+int Status
+string Cookie
+string Name
+string Remark
+int GroupId
+int MaxAmountLimit
+int MaxCountLimit
}
V1CardRedeemAccountInfo <|-- RedeemAccountAddInput
V1CardRedeemAccountInfo <|-- RedeemAccountUpdateInput
```
**图示来源**
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go#L1-L36)
- [operation.go](file://internal/logic/card_redeem_account/operation.go#L1-L131)
**本节来源**
- [card_info_jd_v1_jd_account_create.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_create.go#L22-L52)
- [card_info_jd_v1_jd_account_update.go](file://internal/controller/card_info_jd/card_info_jd_v1_jd_account_update.go#L1-L24)
- [operation.go](file://internal/logic/card_redeem_account/operation.go#L1-L131)
### 账户创建流程
京东卡密账户创建流程始于用户提交账户信息包括Cookie账户名称等系统首先验证用户登录状态然后使用提供的Cookie查询京东账户信息如果账户信息有效且未重复系统将创建新的卡密账户记录并初始化账户余额和状态
创建过程中系统会调用京东API验证Cookie的有效性并获取账户的用户名和昵称信息同时系统会查询账户当前余额并将其作为初始余额存储账户创建成功后系统会记录创建历史包括初始余额和创建时间等信息
### 账户更新与删除
账户更新功能允许修改账户的基本信息和业务配置包括账户状态名称备注以及最大充值金额和次数限制系统在更新账户信息时会进行必要的验证确保更新后的配置符合业务规则
账户删除功能会从系统中移除指定的卡密账户删除操作是永久性的因此系统会进行确认验证删除账户时系统会检查该账户是否有关联的未完成订单如果有则不允许删除以确保业务数据的完整性
### 账户状态管理
京东卡密账户支持多种状态包括正常禁用临时暂停等系统通过状态机管理账户状态的转换确保状态变更的合法性和一致性例如当账户因频繁操作被临时暂停时系统会在一定时间后自动恢复其正常状态
状态管理还包括对账户使用情况的监控如每日充值限额累计充值金额等当账户达到预设的限制条件时系统会自动变更其状态防止超额使用管理员也可以手动调整账户状态以应对特殊情况
## 京东卡密兑换流程
京东卡密兑换流程是系统的核心功能负责处理用户提交的卡密兑换请求流程从接收兑换订单开始经过订单验证账号分配卡密绑定到最终结果回调的完整过程
```mermaid
sequenceDiagram
participant 用户 as 用户
participant 控制器 as 控制器
participant 服务层 as 服务层
participant 京东API as 京东API
用户->>控制器 : 提交卡密兑换请求
控制器->>服务层 : 调用AddOne方法
服务层->>服务层 : 验证订单信息
服务层->>服务层 : 分配可用账号
服务层->>服务层 : 预扣款处理
服务层->>京东API : 绑定卡密
京东API-->>服务层 : 返回绑定结果
服务层->>服务层 : 处理回调数据
服务层->>服务层 : 完成退款处理
服务层-->>控制器 : 返回处理结果
控制器-->>用户 : 返回兑换结果
```
**图示来源**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L28)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L1-L357)
- [place.go](file://internal/logic/card_redeem_cookie/place.go#L1-L200)
**本节来源**
- [card_info_jd_v1_submit.go](file://internal/controller/card_info_jd/card_info_jd_v1_submit.go#L1-L28)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L1-L357)
### 兑换订单创建
用户通过API接口提交卡密兑换请求包含卡号卡密订单金额等信息系统接收到请求后首先验证用户权限然后调用`CardRedeemOrder`服务的`AddOne`方法创建兑换订单
订单创建过程中系统会进行多项验证包括卡号格式验证金额范围验证等如果验证通过系统将订单状态设置为"待处理"并将其加入处理队列订单创建成功后系统会触发订单处理流程开始寻找合适的京东账号进行卡密兑换
### 订单状态管理
京东卡密兑换订单支持多种状态包括待处理处理中充值成功充值失败等系统通过状态码精确描述订单的当前状态和处理结果
```mermaid
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中 : 开始处理
处理中 --> 充值成功 : 绑定成功
处理中 --> 充值失败 : 绑定失败
充值成功 --> 已回调 : 回调上游
充值失败 --> 已回调 : 回调上游
充值成功 --> 金额异议 : 金额不一致
金额异议 --> 补卡成功 : 二次处理
充值失败 --> 重复订单 : 重复提交
充值失败 --> 卡密冻结 : 账号问题
```
**图示来源**
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L118)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L177-L200)
**本节来源**
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L118)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L177-L200)
### 历史查询功能
系统提供完整的兑换历史查询功能支持按订单号时间范围状态等多种条件进行查询历史记录包含订单的完整处理过程包括每次状态变更的时间和原因
历史查询接口返回详细的订单信息包括卡号卡密脱敏订单金额实际金额处理结果等系统还记录了与订单相关的操作日志便于问题排查和审计对于失败的订单系统会记录详细的失败原因帮助用户理解问题所在
## 系统集成模式
京东卡密管理系统与订单系统和支付系统通过API接口进行集成实现了业务流程的自动化和数据的实时同步
```mermaid
flowchart TD
A[用户] --> B[前端应用]
B --> C[京东卡密API]
C --> D[订单系统]
C --> E[支付系统]
D --> F[京东API]
E --> G[第三方支付]
F --> H[京东卡密]
G --> I[用户钱包]
H --> J[兑换结果]
I --> J
J --> K[回调通知]
K --> D
K --> E
```
**图示来源**
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go#L1-L44)
- [place.go](file://internal/logic/card_redeem_cookie/place.go#L1-L200)
**本节来源**
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go#L1-L44)
- [place.go](file://internal/logic/card_redeem_cookie/place.go#L1-L200)
### 与订单系统集成
系统与订单系统通过标准化的API接口进行通信当用户提交卡密兑换请求时京东卡密系统会创建相应的兑换订单并与订单系统中的主订单进行关联
订单状态的变更会实时同步到订单系统确保两个系统间的数据一致性当兑换成功时系统会通知订单系统更新订单状态当兑换失败时系统会提供详细的失败原因便于订单系统进行相应的处理
### 与支付系统集成
支付系统集成主要体现在扣款和退款两个方面在卡密兑换过程中系统会从京东账号中预扣相应金额确保有足够的余额完成兑换如果兑换成功预扣金额将正式扣除如果兑换失败系统会执行退款操作将金额返还到原账户
系统通过支付系统的API接口发起扣款和退款请求并处理相应的回调通知支付结果会记录在兑换订单的历史记录中形成完整的交易流水
## 异常处理与数据一致性
系统设计了完善的异常处理机制确保在各种异常情况下仍能保持数据的一致性和业务的连续性
### 异常处理策略
系统识别并处理多种异常情况包括网络超时接口调用失败数据验证失败等对于可恢复的异常系统会进行重试对于不可恢复的异常系统会记录详细的错误信息并将订单状态更新为相应的失败状态
```mermaid
flowchart TD
A[异常发生] --> B{异常类型}
B --> |网络异常| C[重试机制]
B --> |数据验证失败| D[返回用户]
B --> |账号问题| E[更换账号]
B --> |系统错误| F[记录日志]
C --> G[成功处理]
C --> H[达到重试上限]
H --> I[标记失败]
D --> I
E --> G
F --> I
I --> J[通知用户]
```
**图示来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L118)
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L118)
### 数据一致性保障
系统通过数据库事务和分布式锁机制保障数据一致性关键操作如账户余额变更订单状态更新等都在数据库事务中执行确保操作的原子性
对于并发访问的资源系统使用分布式锁进行保护防止竞态条件导致的数据不一致例如在处理同一订单时系统会获取订单级别的锁确保同一时间只有一个进程在处理该订单
## 性能优化建议
### 并发处理优化
系统采用并发处理机制提高订单处理效率通过goroutine池管理并发任务避免创建过多的goroutine导致系统资源耗尽同时系统设置了合理的并发数限制平衡处理速度和系统负载
### 缓存策略
系统充分利用缓存减少对后端服务的调用对于频繁访问的数据如京东账户信息配置信息等系统会将其缓存到内存中并设置合理的过期时间这不仅提高了访问速度也减轻了后端服务的压力
### 数据库优化
数据库层面系统通过索引优化查询优化等手段提高数据访问效率对于大表查询系统采用分页处理避免一次性加载过多数据同时系统定期清理过期的历史数据保持数据库的良好性能
## 常见问题解决方案
### 账户Cookie失效
当账户Cookie失效时系统会自动检测并更新账户状态解决方案包括重新获取有效的Cookie或使用备用账号进行兑换系统会记录Cookie失效的次数当达到一定阈值时会通知管理员进行处理
### 兑换金额不一致
当出现兑换金额与订单金额不一致的情况时系统会根据配置决定是否允许此类交易如果允许系统会记录为"金额异议"状态并在后续处理中进行补偿如果不允许系统会直接拒绝该订单
### 高并发处理
在高并发场景下系统可能面临资源竞争和性能瓶颈解决方案包括增加服务器资源优化数据库性能调整并发处理策略等系统还提供了监控指标便于及时发现和解决性能问题

View File

@@ -0,0 +1,224 @@
# 京东卡密账户管理
<cite>
**本文档引用的文件**
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [status.go](file://internal/logic/card_redeem_account/status.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录) (如有必要)
## 简介
本文档详细阐述了京东卡密账户管理系统的设计与实现系统主要负责管理京东卡密账户的创建更新删除和状态管理流程包括账户信息的数据结构验证规则和持久化机制文档深入解析了账户状态机设计涵盖正常暂停禁用等状态的转换逻辑并解释了账户与商户支付渠道的关联关系通过具体的代码示例展示了关键业务方法如账户创建状态更新的实现细节同时文档记录了账户管理中的异常处理策略和数据一致性保障机制并提供了性能优化建议和常见问题解决方案
## 项目结构
京东卡密账户管理功能主要分布在项目的`internal`目录下特别是`internal/consts``internal/logic``internal/model``internal/service`等子目录核心的账户状态定义位于`internal/consts/card_redeem.go`业务逻辑实现在`internal/logic/card_redeem_account`包中数据模型定义在`internal/model/entity``internal/model/do`包中服务接口则在`internal/service`包中声明
```mermaid
graph TB
subgraph "API接口层"
A[card_redeem_jd_v1_account_status.go]
end
subgraph "服务层"
B[card_redeem_account.go]
end
subgraph "业务逻辑层"
C[status.go]
end
subgraph "数据模型层"
D[v_1_card_redeem_account_info.go]
end
subgraph "常量定义层"
E[card_redeem.go]
end
A --> B --> C --> D
E --> C
```
**图示来源**
- [card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [status.go](file://internal/logic/card_redeem_account/status.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
**节来源**
- [internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 核心组件
京东卡密账户管理的核心组件包括账户状态机账户数据模型状态更新服务和控制器账户状态机定义了账户的多种状态及其转换规则确保账户状态的正确性和一致性账户数据模型定义了账户信息的结构包括账户ID名称Cookie状态等字段状态更新服务提供了更新账户状态的业务逻辑而控制器则负责处理外部请求并调用服务层的方法
**节来源**
- [internal/consts/card_redeem.go](file://internal/consts/card_redeem.go)
- [internal/model/entity/v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [internal/logic/card_redeem_account/status.go](file://internal/logic/card_redeem_account/status.go)
## 架构概述
京东卡密账户管理系统的架构遵循典型的分层设计模式包括API接口层服务层业务逻辑层和数据模型层API接口层负责接收外部请求并进行初步处理服务层定义了业务服务的接口提供了高层次的业务操作业务逻辑层实现了具体的业务逻辑如状态更新账户调度等数据模型层定义了数据结构和数据库操作
```mermaid
graph TD
A[客户端] --> B[API接口]
B --> C[服务层]
C --> D[业务逻辑层]
D --> E[数据模型层]
E --> F[数据库]
```
**图示来源**
- [card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [status.go](file://internal/logic/card_redeem_account/status.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
## 详细组件分析
### 账户状态机分析
京东卡密账户状态机定义了账户的多种状态包括正常禁用充值速度过快最大充值金额限制等状态机通过`RedeemAccountStatus`枚举类型定义每个状态都有对应的文本描述状态转换由`UpdateStatus`方法控制该方法根据传入的状态值更新账户状态并在特定情况下如状态为`RedeemAccountForbiddenByTooFast`设置缓存和定时任务
#### 状态机类图
```mermaid
classDiagram
class RedeemAccountStatus {
+RedeemAccountForbidden : int
+RedeemAccountNormal : int
+RedeemAccountForbiddenByTooFast : int
+RedeemAccountForbiddenByMaxLimit : int
+RedeemAccountLimited : int
+RedeemAccountForbiddenByLowRecharge : int
+RedeemAccountForbiddenBySafetyReason : int
+RedeemAccountTmpStoppedByTooManyRequest : int
+RedeemAccountForbiddenDaily : int
+GetStatusText() : string
}
class V1CardRedeemAccountInfo {
+Id : string
+GroupId : int
+Name : string
+Cookie : string
+Nickname : string
+Username : string
+CreateUserId : string
+Category : string
+AmountTotalSum : float64
+AmountTodaySum : float64
+Balance : float64
+EffectiveBalance : float64
+Status : int
+MaxCountLimit : int
+MaxAmountLimit : int
+AmountTotalCount : int
+AmountTodayCount : int
+AccountStatus : bool
+Remark : string
+CreatedAt : *gtime.Time
+UpdatedAt : *gtime.Time
+DeletedAt : *gtime.Time
}
class ICardRedeemAccount {
+UpdateStatus(ctx, id, status, tx) : error
}
class sCardRedeemAccount {
+UpdateStatus(ctx, id, status, tx) : error
+CheckForbiddenByTooFast(ctx) : void
}
ICardRedeemAccount <|-- sCardRedeemAccount
sCardRedeemAccount --> V1CardRedeemAccountInfo
sCardRedeemAccount --> RedeemAccountStatus
```
**图示来源**
- [card_redeem.go](file://internal/consts/card_redeem.go#L18-L94)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go#L1-L35)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L97-L97)
- [status.go](file://internal/logic/card_redeem_account/status.go#L19-L36)
### 账户状态更新流程分析
账户状态更新流程从API接口层开始经过服务层和业务逻辑层最终更新数据库中的账户状态当用户请求更新账户状态时控制器调用服务层的`UpdateStatus`方法服务层再调用业务逻辑层的具体实现在更新状态的同时系统还会根据状态值执行相应的附加操作如设置缓存启动定时任务等
#### 状态更新序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "业务逻辑层"
participant DB as "数据库"
participant Cache as "缓存"
Client->>Controller : 调用AccountStatus接口
Controller->>Service : 调用UpdateStatus方法
Service->>Logic : 调用UpdateStatus实现
Logic->>DB : 更新账户状态
alt 状态为RedeemAccountForbiddenByTooFast
Logic->>Cache : 设置缓存
Logic->>Logic : 启动定时任务
end
DB-->>Logic : 更新成功
Logic-->>Service : 返回结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回响应
```
**图示来源**
- [card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go#L1-L19)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go#L97-L97)
- [status.go](file://internal/logic/card_redeem_account/status.go#L19-L36)
**节来源**
- [internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_status.go)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [internal/logic/card_redeem_account/status.go](file://internal/logic/card_redeem_account/status.go)
## 依赖分析
京东卡密账户管理系统依赖于多个内部组件和外部库内部组件包括`internal/consts``internal/dao``internal/model``internal/service`等包外部库包括`github.com/gogf/gf/v2`系列库和`github.com/duke-git/lancet/v2`这些依赖关系确保了系统的模块化和可维护性
```mermaid
graph TD
A[京东卡密账户管理] --> B[internal/consts]
A --> C[internal/dao]
A --> D[internal/model]
A --> E[internal/service]
A --> F[github.com/gogf/gf/v2]
A --> G[github.com/duke-git/lancet/v2]
```
**图示来源**
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [status.go](file://internal/logic/card_redeem_account/status.go)
- [v_1_card_redeem_account_info.go](file://internal/model/entity/v_1_card_redeem_account_info.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
**节来源**
- [internal/consts/card_redeem.go](file://internal/consts/card_redeem.go)
- [internal/dao](file://internal/dao)
- [internal/model](file://internal/model)
- [internal/service](file://internal/service)
## 性能考虑
为了提高系统性能京东卡密账户管理系统采用了多种优化措施首先通过缓存机制减少了对数据库的频繁访问特别是在处理高并发请求时其次使用定时任务异步处理一些耗时操作如检查账户状态是否需要解封此外系统还通过合理的数据库索引和查询优化提高了数据读写的效率
## 故障排除指南
在使用京东卡密账户管理系统时可能会遇到一些常见问题例如账户状态无法更新可能是由于数据库连接问题或事务处理错误此时应检查数据库连接配置和事务管理代码又如账户状态更新后未生效可能是由于缓存未及时更新或定时任务未正确执行此时应检查缓存设置和定时任务配置
**节来源**
- [internal/consts/card_redeem.go](file://internal/consts/card_redeem.go)
- [internal/logic/card_redeem_account/status.go](file://internal/logic/card_redeem_account/status.go)
- [internal/service/card_redeem_account.go](file://internal/service/card_redeem_account.go)
## 结论
京东卡密账户管理系统通过清晰的分层架构和严谨的状态机设计实现了对账户的高效管理和维护系统不仅提供了丰富的账户管理功能还通过缓存定时任务等技术手段确保了高性能和高可用性未来可以进一步优化系统的监控和报警机制提高系统的稳定性和可靠性

View File

@@ -0,0 +1,256 @@
# 卡密管理逻辑
<cite>
**本文档引用的文件**
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [card_info_t_mall_game.go](file://api/card_info_t_mall_game/card_info_t_mall_game.go)
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [sys_auth.go](file://internal/service/sys_auth.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
- [operation.go](file://internal/logic/card_redeem_account/operation.go)
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [process.go](file://internal/logic/card_redeem_order/process.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了kami_backend系统中卡密管理的业务逻辑涵盖Apple京东天猫等各平台卡密账户的创建更新删除和状态管理流程文档深入解析了卡密充值逻辑包括充值历史记录重复卡密处理充值状态同步等核心功能同时解释了卡密账户与订单系统支付系统的集成模式记录了异常处理策略和数据一致性保障机制并提供了性能优化建议和常见问题解决方案
## 项目结构
kami_backend项目采用模块化设计主要分为API接口层内部逻辑层和工具层API层按平台划分如card_info_applecard_info_jd等每个平台有独立的v1版本接口内部逻辑层包含controllerdaologicmodelservice等目录实现具体的业务逻辑工具层utility提供缓存配置定时任务等通用功能
**Section sources**
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [card_info_t_mall_game.go](file://api/card_info_t_mall_game/card_info_t_mall_game.go)
## 核心组件
系统核心组件包括卡密账户管理卡密订单处理状态管理异常处理等卡密账户管理负责各平台账户的生命周期管理卡密订单处理负责充值请求的接收处理和状态更新状态管理维护账户和订单的各种状态异常处理确保系统在各种异常情况下的稳定运行
**Section sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
## 架构概述
系统采用分层架构从上到下分为API层Controller层Service层Logic层和DAO层API层接收外部请求Controller层处理请求路由Service层提供业务服务接口Logic层实现具体业务逻辑DAO层负责数据访问各层之间通过清晰的接口进行通信确保了系统的可维护性和可扩展性
```mermaid
graph TB
subgraph "API层"
A[Apple API]
B[京东 API]
C[天猫 API]
D[Walmart API]
end
subgraph "Controller层"
E[CardInfoAppleController]
F[CardInfoJDController]
G[CardInfoTMallController]
H[CardInfoWalmartController]
end
subgraph "Service层"
I[CardRedeemAccountService]
J[CardRedeemOrderService]
K[RechargeTMallGameAccountService]
end
subgraph "Logic层"
L[CardRedeemAccountLogic]
M[CardRedeemOrderLogic]
N[CardTmallAccountLogic]
end
subgraph "DAO层"
O[V1CardRedeemAccountInfo]
P[V1CardRedeemOrderInfo]
Q[V1RechargeTmallAccount]
end
A --> E
B --> F
C --> G
D --> H
E --> I
F --> J
G --> K
H --> J
I --> L
J --> M
K --> N
L --> O
M --> P
N --> Q
```
**Diagram sources**
- [card_info_apple.go](file://api/card_info_apple/card_info_apple.go)
- [card_info_jd.go](file://api/card_info_jd/card_info_jd.go)
- [card_info_t_mall_game.go](file://api/card_info_t_mall_game/card_info_t_mall_game.go)
- [card_info_walmart.go](file://api/card_info_walmart/card_info_walmart.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
## 详细组件分析
### 卡密账户管理分析
卡密账户管理组件负责各平台卡密账户的创建更新删除和状态管理系统通过统一的接口处理不同平台的账户操作确保了代码的复用性和一致性
#### 对象导向组件
```mermaid
classDiagram
class ICardRedeemAccount {
+Add(ctx, input, tx) error
+UpdateCookie(ctx, id, cookie, tx) error
+GetByCK(ctx, cookie) ([]*entity.V1CardRedeemAccountInfo, error)
+GetRandomOne(ctx, tx) (data *entity.V1CardRedeemAccountInfo, err error)
+CheckAccountNumberNormal(ctx, accountNumber, tx) bool
}
class CardRedeemAccountService {
-localCardRedeemAccount ICardRedeemAccount
+CardRedeemAccount() ICardRedeemAccount
}
class sCardRedeemAccount {
+Add(ctx, input, tx) error
+AddWithGroup(ctx, input, tx) error
+UpdateCookie(ctx, id, cookie, tx) error
}
ICardRedeemAccount <|.. sCardRedeemAccount : 实现
CardRedeemAccountService --> ICardRedeemAccount : 使用
```
**Diagram sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [operation.go](file://internal/logic/card_redeem_account/operation.go)
### 卡密充值流程分析
卡密充值流程是系统的核心功能涉及订单创建状态管理异常处理等多个环节系统通过异步处理机制确保充值请求的高效处理
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "Controller"
participant Service as "Service"
participant Logic as "Logic"
participant DAO as "DAO"
Client->>Controller : 提交充值请求
Controller->>Service : 调用Add方法
Service->>Logic : 执行业务逻辑
Logic->>DAO : 检查账号是否存在
DAO-->>Logic : 返回检查结果
alt 账号不存在
Logic->>DAO : 创建新账号
DAO-->>Logic : 返回创建结果
else 账号存在
Logic->>Logic : 更新现有账号
end
Logic-->>Service : 返回处理结果
Service-->>Controller : 返回服务结果
Controller-->>Client : 返回响应
```
**Diagram sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [operation.go](file://internal/logic/card_redeem_account/operation.go)
### 卡密状态管理分析
卡密状态管理涉及多种状态的定义和转换系统通过枚举类型明确定义了各种状态码确保了状态管理的一致性和可维护性
#### 复杂逻辑组件
```mermaid
flowchart TD
Start([开始]) --> CheckStatus["检查卡密状态"]
CheckStatus --> StatusValid{"状态有效?"}
StatusValid --> |是| ProcessOrder["处理充值订单"]
StatusValid --> |否| HandleError["处理异常"]
ProcessOrder --> CheckAmount["检查金额一致性"]
CheckAmount --> AmountMatch{"金额匹配?"}
AmountMatch --> |是| CompleteOrder["完成订单"]
AmountMatch --> |否| HandleAmountDiscrepancy["处理金额差异"]
HandleAmountDiscrepancy --> CheckConfig["检查配置是否允许差异"]
CheckConfig --> ConfigAllow{"配置允许?"}
ConfigAllow --> |是| CompleteWithDiff["完成差异订单"]
ConfigAllow --> |否| SuspendCallback["暂停回调"]
CompleteOrder --> End([结束])
CompleteWithDiff --> End
SuspendCallback --> End
HandleError --> End
```
**Diagram sources**
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [process.go](file://internal/logic/card_redeem_order/process.go)
## 依赖分析
系统各组件之间存在明确的依赖关系API层依赖Controller层Controller层依赖Service层Service层依赖Logic层Logic层依赖DAO层此外系统还依赖外部服务如缓存数据库等
```mermaid
graph TD
A[API层] --> B[Controller层]
B --> C[Service层]
C --> D[Logic层]
D --> E[DAO层]
E --> F[数据库]
C --> G[缓存]
C --> H[外部服务]
D --> I[工具库]
```
**Diagram sources**
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
## 性能考虑
系统在设计时充分考虑了性能因素通过使用缓存减少数据库访问采用异步处理提高响应速度利用数据库事务保证数据一致性对于高并发场景系统通过锁机制防止资源竞争确保操作的原子性
## 故障排除指南
当系统出现异常时可参考以下常见问题及解决方案
**Section sources**
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [process.go](file://internal/logic/card_redeem_order/process.go)
### 常见错误代码
| 错误代码 | 含义 | 解决方案 |
|--------|------|--------|
| 100 | 充值失败 | 检查卡密有效性 |
| 1 | 充值成功 | 无需处理 |
| 2 | 待处理 | 等待系统处理 |
| 3 | 验证失败 | 检查账号信息 |
| 4 | 账号失效 | 更新账号cookie |
| 5 | 账号频繁 | 降低请求频率 |
| 6 | 未知状态 | 检查系统日志 |
| 7 | 最大调用次数限制 | 调整配置或等待 |
| 8 | 金额不一致(已充值) | 确认实际充值金额 |
| 9 | 卡密类型错误 | 检查卡密类型 |
| 10 | 金额不一致(未充值) | 检查订单金额 |
| 11 | 卡密被绑定 | 使用未绑定卡密 |
| 12 | 重复绑卡 | 避免重复提交 |
| 13 | 账号受限制 | 等待限制解除 |
| 15 | 卡片不存在 | 检查卡密有效性 |
| 16 | 卡片过期 | 使用有效卡密 |
| 19 | 重复订单 | 避免重复提交 |
| 20 | 卡号不符合规则 | 检查卡号格式 |
| 21 | 卡密冻结 | 联系发卡方解冻 |
## 结论
kami_backend的卡密管理系统设计合理功能完整能够有效支持多平台卡密的管理需求系统通过分层架构和模块化设计确保了代码的可维护性和可扩展性在性能和稳定性方面系统采用了多种优化措施能够应对高并发场景未来可进一步优化异常处理机制提升系统的健壮性

View File

@@ -0,0 +1,224 @@
# 天猫卡密工作空间管理
<cite>
**本文档引用文件**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了天猫卡密工作空间管理系统的功能与实现机制系统主要围绕数据同步统计分析和日常订单汇总三大核心功能展开实现了与账户系统订单系统的高效数据流转通过自动化任务保障数据一致性并提供全面的异常处理策略文档还包含性能优化建议和常见问题解决方案确保系统稳定高效运行
## 项目结构
天猫卡密工作空间管理功能主要分布在 `api/card_info_t_mall_game/v1` `internal/controller/card_info_t_mall_game` 目录下`workspace.go` 定义了工作空间相关的API请求和响应结构体`card_info_t_mall_game_v1_t_mall_game_*.go` 文件实现了具体的控制器逻辑数据同步功能由 `utility/cron/t_mall_game_data_sync.go` 中的定时任务驱动业务逻辑由 `internal/service/card_t_mall_order.go` 中的服务接口统一管理
```mermaid
graph TD
subgraph "API 接口层"
A[workspace.go] --> B[TMallGameDailyOrderSummaryReq]
A --> C[TMallGameStatsReq]
end
subgraph "控制器层"
D[card_info_t_mall_game_v1_t_mall_game_data_sync.go]
E[card_info_t_mall_game_v1_t_mall_game_stats.go]
F[card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go]
end
subgraph "服务层"
G[card_t_mall_order.go] --> H[IRechargeTMallGameOrder]
end
subgraph "定时任务"
I[t_mall_game_data_sync.go] --> J[SyncTMallGameData]
end
A --> D
D --> G
E --> G
F --> G
I --> G
```
**Diagram sources**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
**Section sources**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
## 核心组件
核心组件包括工作空间API定义数据同步控制器统计分析服务和定时同步任务`TMallGameDailyOrderSummaryReq` `TMallGameStatsReq` 结构体定义了获取订单统计和基本统计信息的请求参数`TMallGameDataSync` 函数负责从远程服务拉取最新数据并持久化到本地数据库`IRechargeTMallGameOrder` 接口定义了所有订单相关的业务操作是系统功能的核心
**Section sources**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go#L1-L48)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go#L1-L86)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L84)
## 架构概述
系统采用分层架构从上至下分为API接口层控制器层服务层和数据访问层API层定义了外部可调用的HTTP端点控制器层负责处理HTTP请求进行参数校验和转换服务层封装了核心业务逻辑确保了代码的可重用性和可测试性数据访问通过DAOData Access Object模式实现定时任务独立运行通过调用控制器或服务层接口来执行数据同步
```mermaid
graph TD
A[客户端] --> B[API 接口]
B --> C[控制器]
C --> D[服务]
D --> E[DAO]
E --> F[(数据库)]
G[定时任务] --> C
G --> D
```
**Diagram sources**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
## 详细组件分析
### 工作空间数据同步分析
数据同步功能是确保工作空间数据实时性的关键它通过一个定时任务周期性地从上游服务拉取最新的账户订单店铺等数据
#### 数据同步流程
```mermaid
sequenceDiagram
participant Cron as 定时任务
participant Controller as 数据同步控制器
participant Service as 订单服务
participant DAO as 数据访问对象
participant DB as 数据库
participant Upstream as 上游服务
Cron->>Controller : TMallGameDataSync(请求)
Controller->>DAO : 查询最近更新的订单
DAO-->>Controller : 订单列表
Controller->>DAO : 查询关联的账户信息
DAO-->>Controller : 账户列表
Controller->>DAO : 查询关联的店铺信息
DAO-->>Controller : 店铺列表
Controller->>DAO : 查询关联的订单历史
DAO-->>Controller : 订单历史列表
Controller->>DAO : 查询关联的店铺历史
DAO-->>Controller : 店铺历史列表
Controller-->>Cron : 返回所有数据
Cron->>Upstream : POST /api/recharge/tMallGame/data/sync
Upstream-->>Cron : 返回同步结果
Cron->>DB : 批量保存所有数据
```
**Diagram sources**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go#L1-L86)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go#L1-L76)
### 统计分析功能分析
统计分析功能为工作空间提供关键的业务洞察包括订单成功率金额汇总等
#### 统计计算实现
```mermaid
flowchart TD
Start([获取统计请求]) --> Validate["验证渠道名称"]
Validate --> GetService["获取订单服务实例"]
GetService --> CallService["调用服务层 GetOrderStats 方法"]
CallService --> ServiceLogic["服务层执行统计计算"]
ServiceLogic --> QueryDB["查询数据库聚合数据"]
QueryDB --> FormatRes["格式化响应数据"]
FormatRes --> ReturnRes["返回 TMallGameStatsRes"]
CallService --> HandleError["处理错误"]
HandleError --> WrapError["包装错误信息"]
WrapError --> ReturnError["返回错误响应"]
ReturnRes --> End([结束])
ReturnError --> End
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_stats.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_stats.go#L1-L27)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L66-L66)
### 日常订单汇总分析
日常订单汇总功能提供按日粒度的订单数据统计用于生成日报
#### 汇总数据处理
```mermaid
flowchart TD
Req([收到汇总请求]) --> InitRes["初始化响应结构"]
InitRes --> GetService["获取订单服务"]
GetService --> CallService["调用 GetOrderSummary"]
CallService --> ServiceLogic["服务层执行分页汇总查询"]
ServiceLogic --> QueryDB["数据库查询并分组统计"]
QueryDB --> CopyData["使用 copier 复制数据"]
CopyData --> SetTotal["设置总记录数"]
CopyData --> HandleError["处理复制错误"]
HandleError --> WrapError["包装错误"]
WrapError --> ReturnError["返回错误"]
SetTotal --> ReturnSuccess["返回成功响应"]
ReturnSuccess --> End([结束])
ReturnError --> End
```
**Diagram sources**
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go#L1-L30)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L65-L65)
## 依赖分析
系统内部组件间依赖清晰控制器层依赖于服务层接口 `IRechargeTMallGameOrder` 来执行业务逻辑服务层依赖于DAO层进行数据持久化定时任务 `t_mall_game_data_sync.go` 直接依赖于配置模块 `config` 和日志模块 `glog`并通过HTTP客户端与上游服务通信API定义文件 `workspace.go` 被控制器和模型层所依赖作为数据传输的契约
```mermaid
graph TD
A[t_mall_game_data_sync.go] --> B[config]
A --> C[glog]
A --> D[gclient]
E[card_info_t_mall_game_v1_*.go] --> F[IRechargeTMallGameOrder]
F --> G[DAO]
G --> H[数据库]
I[workspace.go] --> J[控制器]
I --> K[模型]
```
**Diagram sources**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_*.go](file://internal/controller/card_info_t_mall_game/)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
**Section sources**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go#L1-L86)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L84)
## 性能考虑
数据同步采用批量保存`Save`而非逐条插入显著提升了写入性能统计查询在服务层实现避免了在控制器中编写复杂的SQL逻辑提高了代码可维护性使用 `gtime.S * 5` 设置了合理的HTTP请求超时时间防止任务长时间阻塞数据库查询使用了 `Unscoped()` 方法确保能获取到所有状态的数据但需注意这可能影响查询性能建议在数据量大时建立合适的索引
## 故障排除指南
**问题数据同步延迟**
* **检查点**确认 `t_mall_game_data_sync.go` 中的定时任务是否正常运行
* **检查点**检查 `syncCfg.Interval` 配置项确保同步间隔合理
* **检查点**查看日志中是否有 "请求失败" "保存...失败" 的错误信息排查网络或数据库连接问题
**问题统计结果不准确**
* **检查点**确认数据同步任务是否成功执行本地数据库是否已更新
* **检查点**检查 `GetOrderSummary` `GetOrderStats` 方法的查询条件和聚合逻辑是否正确
* **检查点**验证 `workspace.go` 中定义的 `TMAllGameSummaryListRecord` 结构体字段与数据库实际存储的数据类型是否匹配
**问题服务启动失败**
* **检查点**检查 `card_t_mall_order.go` 中的 `localRechargeTMallGameOrder` 变量是否已正确注册实现避免出现 "implement not found" 的panic
**Section sources**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go#L1-L86)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L84)
## 结论
天猫卡密工作空间管理系统通过清晰的分层架构和模块化设计有效地实现了数据同步统计分析和订单汇总等核心功能系统通过定时任务保障了数据的实时性并通过服务层接口保证了业务逻辑的统一完善的错误处理和日志记录机制为系统的稳定运行提供了保障未来可进一步优化数据库查询性能并增加更多的监控指标

View File

@@ -0,0 +1,305 @@
# 天猫卡密管理逻辑
<cite>
**本文档引用的文件**
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go)
- [card_info_t_mall_game_v1_t_mall_game_account_delete.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_delete.go)
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go)
</cite>
## 目录
1. [天猫卡密账户管理](#天猫卡密账户管理)
2. [天猫卡密订单处理](#天猫卡密订单处理)
3. [AGISO回调处理](#agiso回调处理)
4. [数据同步与统计](#数据同步与统计)
5. [系统集成与异常处理](#系统集成与异常处理)
## 天猫卡密账户管理
天猫卡密账户管理模块负责账户的全生命周期管理包括创建删除状态切换和授权等核心功能系统通过统一的接口服务层IRechargeTMallGameAccount提供账户管理能力确保操作的一致性和可维护性
### 账户创建与删除
账户创建功能通过`TMallGameAccountCreate`接口实现接收账户创建请求参数调用账户服务进行持久化存储系统在创建过程中会验证账户信息的完整性和唯一性确保不会创建重复账户账户删除功能通过`TMallGameAccountDelete`接口实现根据账户ID执行删除操作同时清理相关联的数据
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> CheckExistence["检查账户是否存在"]
CheckExistence --> AccountExists{"账户已存在?"}
AccountExists --> |是| ReturnError["返回错误: 账户已存在"]
AccountExists --> |否| CreateAccount["创建账户记录"]
CreateAccount --> SaveToDB["保存到数据库"]
SaveToDB --> UpdateCache["更新缓存"]
UpdateCache --> End([结束])
DeleteStart([开始]) --> ValidateID["验证账户ID"]
ValidateID --> FindAccount["查找账户"]
FindAccount --> AccountFound{"账户找到?"}
AccountFound --> |否| ReturnNotFound["返回: 账户不存在"]
AccountFound --> |是| DeleteRelated["删除关联数据"]
DeleteRelated --> RemoveFromDB["从数据库移除"]
RemoveFromDB --> ClearCache["清除缓存"]
ClearCache --> End
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L22)
- [card_info_t_mall_game_v1_t_mall_game_account_delete.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_delete.go#L1-L19)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L22)
- [card_info_t_mall_game_v1_t_mall_game_account_delete.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_delete.go#L1-L19)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L51)
### 账户状态管理
账户状态管理功能允许系统管理员对账户进行启用/禁用操作通过`TMallGameAccountToggle`接口接收状态切换请求调用服务层的Toggle方法更新账户状态系统会记录状态变更历史便于审计和问题追踪状态切换操作是幂等的即重复执行相同的状态切换请求不会产生副作用
```mermaid
flowchart TD
Start([开始]) --> ValidateRequest["验证请求参数"]
ValidateRequest --> GetAccount["获取账户信息"]
GetAccount --> AccountExists{"账户存在?"}
AccountExists --> |否| ReturnError["返回错误: 账户不存在"]
AccountExists --> |是| GetCurrentStatus["获取当前状态"]
GetCurrentStatus --> DetermineNewStatus["确定新状态"]
DetermineNewStatus --> UpdateStatus["更新账户状态"]
UpdateStatus --> LogChange["记录状态变更日志"]
LogChange --> NotifySystem["通知相关系统"]
NotifySystem --> End([结束])
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go#L1-L22)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go#L1-L22)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L51)
### 账户授权与工作空间管理
账户授权功能通过`TMallGameAccountAuthorizeCallback`接口处理来自第三方平台如阿奇索天猫店铺的授权回调系统根据回调中的渠道信息区分处理逻辑对于天猫店铺授权会调用天猫API进行OAuth2登录验证授权成功后系统会更新账户的授权状态并建立与工作空间的关联关系
```mermaid
sequenceDiagram
participant ThirdParty as "第三方平台"
participant System as "卡密系统"
participant TMallAPI as "天猫API"
ThirdParty->>System : 发送授权回调
System->>System : 验证回调签名
alt 阿奇索渠道
System->>System : 记录授权信息
System-->>ThirdParty : 返回成功
else 天猫店铺渠道
System->>TMallAPI : 调用OAuth2Login
alt 授权成功
TMallAPI-->>System : 返回授权结果
System->>System : 更新账户授权状态
System-->>ThirdParty : 返回成功
else 授权失败
TMallAPI-->>System : 返回错误
System->>System : 记录授权失败日志
System-->>ThirdParty : 返回失败
end
else 其他渠道
System-->>ThirdParty : 返回不支持
end
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go#L1-L31)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go#L1-L31)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L51)
## 天猫卡密订单处理
天猫卡密订单处理模块负责订单的全生命周期管理从订单提交到最终完成的整个流程系统通过统一的订单服务接口IRechargeTMallGameOrder提供订单管理能力确保订单处理的一致性和可靠性
### 订单提交流程
订单提交功能通过`TMallGameOrderSubmit`接口实现系统首先验证请求参数的完整性然后根据账户号码查找对应的账户信息如果账户不存在或不可用系统会返回相应的错误信息验证通过后系统调用订单服务创建新订单并返回订单号和状态信息订单创建过程中会进行数据一致性检查确保订单金额回调地址等关键信息的正确性
```mermaid
flowchart TD
Start([开始]) --> ValidateRequest["验证请求参数"]
ValidateRequest --> FindAccount["查找账户信息"]
FindAccount --> AccountValid{"账户有效?"}
AccountValid --> |否| ReturnError["返回错误: 账户不存在或不可用"]
AccountValid --> |是| CreateOrder["创建订单记录"]
CreateOrder --> SetOrderStatus["设置订单初始状态"]
SetOrderStatus --> GenerateOrderNo["生成订单号"]
GenerateOrderNo --> SaveOrder["保存订单到数据库"]
SaveOrder --> ReturnSuccess["返回订单号和成功状态"]
ReturnSuccess --> End([结束])
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go#L1-L44)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go#L1-L44)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L85)
## AGISO回调处理
AGISO回调处理模块负责处理来自AGISO平台的各类订单状态变更通知包括买家付款确认收货申请退款和评价等事件系统通过`TMallGameAgisoCallback`接口接收回调请求并根据回调类型分发到相应的处理函数
### 回调处理机制
系统采用并发安全的处理机制通过互斥锁和缓存确保同一订单不会被重复处理每个回调请求都会先验证签名的正确性防止伪造请求处理成功后系统会更新订单状态并根据业务规则执行相应的后续操作如虚拟发货回调第三方等
```mermaid
flowchart TD
Start([开始]) --> ValidateSign["验证回调签名"]
ValidateSign --> SignValid{"签名有效?"}
SignValid --> |否| ReturnError["返回错误: 签名验证失败"]
SignValid --> |是| CheckDuplicate["检查重复处理"]
CheckDuplicate --> IsDuplicate{"正在处理?"}
IsDuplicate --> |是| ReturnBusy["返回: 订单正在处理"]
IsDuplicate --> |否| AcquireLock["获取处理锁"]
AcquireLock --> ProcessCallback["处理回调事件"]
ProcessCallback --> UpdateOrder["更新订单状态"]
UpdateOrder --> ExecuteAction["执行后续操作"]
ExecuteAction --> ReleaseLock["释放锁"]
ReleaseLock --> ReturnSuccess["返回成功"]
ReturnSuccess --> End([结束])
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go#L1-L666)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go#L1-L666)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L85)
### 买家付款处理
当收到买家付款回调时系统会先检查订单是否已存在防止重复处理然后创建淘宝订单记录并调用天猫API获取详细的订单信息系统会尝试进行虚拟发货最多重试三次如果发货成功更新订单状态为发货成功如果失败则标记为发货失败并记录错误日志
```mermaid
sequenceDiagram
participant Agiso as "AGISO平台"
participant System as "卡密系统"
participant TMallAPI as "天猫API"
Agiso->>System : 买家付款回调
System->>System : 检查订单是否已存在
alt 订单已存在
System-->>Agiso : 返回 : 订单已存在
else 订单不存在
System->>System : 创建淘宝订单记录
System->>TMallAPI : 获取订单详情
alt 获取成功
TMallAPI-->>System : 返回订单详情
System->>System : 尝试虚拟发货
loop 重试3次
System->>TMallAPI : 虚拟发货
alt 发货成功
TMallAPI-->>System : 发货成功
System->>System : 更新订单状态为发货成功
break
else 发货失败
TMallAPI-->>System : 发货失败
System->>System : 记录发货失败日志
end
end
else 获取失败
TMallAPI-->>System : 获取失败
System->>System : 记录获取失败日志
end
System-->>Agiso : 返回处理结果
end
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go#L1-L666)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go#L1-L666)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L85)
## 数据同步与统计
数据同步与统计模块提供数据实时同步和业务统计功能支持系统间的数据一致性维护和业务决策支持
### 数据同步机制
`TMallGameDataSync`接口提供数据同步功能允许客户端获取指定时间段内的最新数据变更系统会查询订单账户店铺和历史记录等实体的更新数据并按类别返回同步机制采用时间戳过滤确保只返回增量数据提高同步效率
```mermaid
flowchart TD
Start([开始]) --> ParseRequest["解析请求参数"]
ParseRequest --> GetDuration["获取同步时长"]
GetDuration --> CalculateTime["计算起始时间"]
CalculateTime --> QueryOrders["查询订单变更"]
QueryOrders --> QueryAccounts["查询账户变更"]
QueryAccounts --> QueryShops["查询店铺变更"]
QueryShops --> QueryOrderHistory["查询订单历史变更"]
QueryOrderHistory --> QueryShopHistory["查询店铺历史变更"]
QueryShopHistory --> AssembleData["组装返回数据"]
AssembleData --> ReturnData["返回同步数据"]
ReturnData --> End([结束])
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go#L1-L77)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go#L1-L77)
- [v_1_recharge_t_mall_order.go](file://internal/dao/v_1_recharge_t_mall_order.go#L1-L28)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go#L1-L28)
### 订单统计功能
`TMallGameDailyOrderSummary`接口提供订单统计功能支持按时间范围状态等条件查询订单汇总数据系统会调用订单服务的统计方法获取符合条件的订单总数和详细记录并进行数据转换后返回统计功能支持分页查询便于处理大量数据
```mermaid
flowchart TD
Start([开始]) --> ParseParams["解析统计参数"]
ParseParams --> CallService["调用订单统计服务"]
CallService --> GetTotal["获取订单总数"]
GetTotal --> GetList["获取订单列表"]
GetList --> TransformData["转换数据格式"]
TransformData --> ReturnResult["返回统计结果"]
ReturnResult --> End([结束])
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go#L1-L31)
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_daily_order_summary.go#L1-L31)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L85)
## 系统集成与异常处理
系统集成与异常处理模块确保天猫卡密管理系统与其他系统的稳定集成并提供完善的错误处理机制
### 系统集成模式
天猫卡密管理系统通过标准化的API接口与订单系统支付系统等外部系统集成系统采用异步回调机制当订单状态发生变更时会通过预设的回调地址通知第三方系统集成过程中使用数字签名验证确保通信安全防止数据篡改和伪造请求
### 异常处理策略
系统采用分层的异常处理策略在控制器层所有异常都会被统一捕获并包装为标准的错误响应业务逻辑层会根据异常类型进行分类处理如数据验证错误系统错误第三方服务错误等对于可恢复的错误系统会尝试重试对于不可恢复的错误会记录详细的错误日志并通知相关人员
### 数据一致性保障
系统通过事务管理确保数据的一致性关键操作如订单创建状态更新等都会在数据库事务中执行确保要么全部成功要么全部回滚系统还实现了幂等性设计相同的操作重复执行不会产生副作用此外通过定期的数据校验任务系统能够及时发现并修复数据不一致问题
**本节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go#L1-L666)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go#L1-L85)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L51)

View File

@@ -0,0 +1,177 @@
# 天猫卡密订单处理
<cite>
**本文档引用的文件**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [v_1_recharge_t_mall_order.go](file://internal/model/do/v_1_recharge_t_mall_order.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [agiso.go](file://internal/model/agiso.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了天猫卡密订单处理系统的完整流程包括订单的提交查询状态修改和回调处理系统集成了支付系统和AGISO系统实现了订单分类查询状态同步和成功状态修改等核心功能文档深入分析了订单处理中的异常处理策略和数据一致性保障机制并提供了性能优化建议和常见问题解决方案
## 项目结构
天猫卡密订单处理系统采用分层架构主要分为API层控制器层服务层逻辑层和数据访问层系统通过API接口接收订单请求由控制器协调处理服务层提供业务接口逻辑层实现具体业务逻辑数据访问层负责与数据库交互
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[逻辑层]
D --> E[数据访问层]
E --> F[数据库]
```
**图表来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
## 核心组件
系统的核心组件包括订单提交状态修改回调处理和数据同步订单提交组件负责接收和创建新订单状态修改组件处理订单状态的变更回调处理组件接收来自AGISO系统的异步通知数据同步组件确保系统间数据的一致性
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
## 架构概述
系统采用微服务架构各组件通过清晰的接口进行通信订单处理流程从API接收请求开始经过控制器调度由服务层协调最终在逻辑层完成具体业务处理系统通过缓存机制提高性能使用事务保证数据一致性
```mermaid
graph TD
A[客户端] --> B[API接口]
B --> C[控制器]
C --> D[服务层]
D --> E[逻辑层]
E --> F[数据访问层]
F --> G[数据库]
C --> H[缓存]
D --> I[外部系统]
```
**图表来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
## 详细组件分析
### 订单提交分析
订单提交组件负责接收订单请求并创建新订单系统首先验证账户信息然后创建订单记录并返回订单号
```mermaid
sequenceDiagram
participant 客户端
participant 控制器
participant 服务层
participant 数据访问层
客户端->>控制器 : 提交订单请求
控制器->>服务层 : 验证账户信息
服务层->>数据访问层 : 查询账户数据
数据访问层-->>服务层 : 返回账户信息
服务层->>数据访问层 : 创建订单记录
数据访问层-->>服务层 : 返回订单号
服务层-->>控制器 : 返回结果
控制器-->>客户端 : 返回订单号和状态
```
**图表来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
### 回调处理分析
回调处理组件负责处理来自AGISO系统的异步通知包括付款成功确认收货和评价成功等事件
```mermaid
flowchart TD
Start([开始]) --> ValidateSign["验证签名"]
ValidateSign --> SignValid{"签名有效?"}
SignValid --> |否| ReturnError["返回验证失败"]
SignValid --> |是| HandleCallback["处理回调类型"]
HandleCallback --> PaymentSuccess{"付款成功?"}
PaymentSuccess --> |是| ProcessPayment["处理付款"]
HandleCallback --> ConfirmReceipt{"确认收货?"}
ConfirmReceipt --> |是| ProcessConfirm["处理确认收货"]
HandleCallback --> Evaluation{"评价成功?"}
Evaluation --> |是| ProcessEvaluation["处理评价"]
ProcessPayment --> End([结束])
ProcessConfirm --> End
ProcessEvaluation --> End
ReturnError --> End
```
**图表来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [agiso.go](file://internal/model/agiso.go)
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [agiso.go](file://internal/model/agiso.go)
## 依赖分析
系统各组件之间存在明确的依赖关系API层依赖控制器层控制器层依赖服务层服务层依赖逻辑层逻辑层依赖数据访问层系统还依赖外部的AGISO系统和淘宝API
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[逻辑层]
D --> E[数据访问层]
E --> F[数据库]
C --> G[AGISO系统]
C --> H[淘宝API]
B --> I[缓存系统]
```
**图表来源**
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
**章节来源**
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [order.go](file://internal/logic/card_t_mall_order/order.go)
## 性能考虑
系统通过多种机制优化性能使用缓存减少数据库访问采用连接池管理数据库连接通过异步处理提高响应速度利用批量操作减少网络开销对于高并发场景系统采用限流和降级策略确保稳定性
## 故障排除指南
### 订单状态不一致
当出现订单状态不一致时应首先检查数据库记录然后查看日志文件确认是否有未处理的回调可以通过数据同步接口手动同步状态
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
### 回调处理失败
回调处理失败通常由签名验证失败或网络问题引起应检查签名算法是否正确确认网络连接是否正常并查看错误日志获取详细信息
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [agiso.go](file://internal/model/agiso.go)
## 结论
天猫卡密订单处理系统设计合理功能完整能够高效处理各种订单场景系统通过清晰的分层架构和明确的组件职责确保了代码的可维护性和可扩展性建议持续监控系统性能定期优化数据库查询并加强异常处理机制

View File

@@ -0,0 +1,372 @@
# 天猫卡密账户管理
<cite>
**本文档引用文件**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go)
- [card_info_t_mall_game_v1_t_mall_game_account_delete.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_delete.go)
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go)
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go)
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go)
- [account.go](file://internal/logic/card_t_mall_account/account.go)
- [v_1_recharge_t_mall_account.go](file://internal/model/entity/v_1_recharge_t_mall_account.go)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心功能概述](#核心功能概述)
3. [账户生命周期管理](#账户生命周期管理)
4. [账户授权与认证](#账户授权与认证)
5. [账户状态管理](#账户状态管理)
6. [账户查询与获取](#账户查询与获取)
7. [数据模型与持久化](#数据模型与持久化)
8. [异常处理与数据一致性](#异常处理与数据一致性)
9. [性能优化与缓存策略](#性能优化与缓存策略)
10. [常见问题与解决方案](#常见问题与解决方案)
## 简介
本文档详细阐述了天猫卡密账户管理系统的设计与实现系统为天猫游戏卡密业务提供完整的账户管理解决方案涵盖账户的创建更新删除查询等全生命周期管理功能系统通过分层架构设计实现了业务逻辑与数据访问的分离确保了系统的可维护性和扩展性账户系统与工作空间订单系统深度集成支持自动化卡密充值流程
**Section sources**
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L1-L71)
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L21)
## 核心功能概述
天猫卡密账户管理系统提供以下核心功能
- 账户批量创建与管理
- 账户状态切换启用/禁用
- 账户删除与回收
- 账户列表查询与分页
- 随机账户获取与分配
- 天猫平台授权与认证
- 账户授权状态检测
- 与订单系统的集成协作
系统通过RESTful API接口暴露所有功能采用GoFrame框架构建遵循清晰的MVC架构模式控制器层处理HTTP请求服务层封装核心业务逻辑数据访问层负责与数据库交互
```mermaid
graph TB
subgraph "API接口层"
A[账户创建]
B[账户删除]
C[状态切换]
D[列表查询]
E[随机获取]
F[授权回调]
G[状态检测]
end
subgraph "业务逻辑层"
H[账户服务]
I[订单服务]
J[缓存服务]
end
subgraph "数据访问层"
K[账户DAO]
L[订单DAO]
end
subgraph "外部系统"
M[天猫平台]
N[阿奇索]
end
A --> H
B --> H
C --> H
D --> H
E --> H
F --> H
G --> H
H --> K
H --> L
H --> J
F --> M
F --> N
```
**Diagram sources **
- [account.go](file://api/card_info_t_mall_game/v1/account.go#L1-L71)
- [card_t_mall_account.go](file://internal/service/card_t_mall_account.go#L1-L50)
## 账户生命周期管理
### 账户创建
账户创建功能支持批量创建指定数量的天猫游戏账户系统通过`TMallGameAccountCreate`接口接收创建请求包含需要创建的账户数量服务层在事务中执行创建逻辑确保数据一致性
创建流程如下
1. 接收创建请求验证参数
2. 在数据库事务中执行
3. 循环生成唯一账户号码邮箱格式
4. 检查账户号码是否已存在
5. 构建账户数据列表
6. 批量插入数据库
账户号码采用随机生成策略由大小写字母和数字组成的前缀与随机字母组成的后缀构成邮箱格式确保全局唯一性
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L21)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L30-L55)
### 账户删除
账户删除功能通过`TMallGameAccountDelete`接口实现接收账户ID作为参数服务层调用数据访问对象执行删除操作直接从数据库中移除指定ID的账户记录
删除操作为物理删除不保留软删除标记系统未实现删除前的依赖检查需确保账户未被订单引用后再执行删除操作
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_delete.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_delete.go#L1-L18)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L205-L212)
## 账户授权与认证
### 授权回调处理
系统提供`TMallGameAccountAuthorizeCallback`接口处理来自天猫平台和阿奇索的授权回调接口根据渠道参数区分处理逻辑
- **天猫渠道**使用OAuth2.0协议完成授权调用天猫API客户端进行登录验证获取访问令牌
- **阿奇索渠道**记录授权开始日志具体处理逻辑需在其他模块实现
授权失败时系统返回相应的错误码和错误信息便于前端展示和问题排查
```mermaid
sequenceDiagram
participant 天猫平台
participant 系统
participant 数据库
天猫平台->>系统 : 授权回调请求(code)
系统->>系统 : 验证渠道参数
alt 天猫渠道
系统->>天猫平台 : OAuth2登录验证
天猫平台-->>系统 : 访问令牌
系统->>数据库 : 存储授权信息
系统-->>天猫平台 : 成功响应
else 阿奇索渠道
系统->>系统 : 记录授权日志
系统-->>天猫平台 : 成功响应
else 其他渠道
系统-->>天猫平台 : 不支持渠道错误
end
```
**Diagram sources **
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go#L1-L30)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go#L1-L20)
### 认证状态检测
`TMallGameAccountTMallAuthStatus`接口用于检测天猫平台的授权状态系统从缓存中获取OAuth令牌信息检查其过期时间
1. 获取缓存中的授权令牌
2. 检查令牌是否存在且有效
3. 比较当前时间与令牌过期时间
4. 返回授权状态和过期时间
此功能确保系统在执行需要天猫授权的操作前能够验证授权的有效性避免因授权过期导致的操作失败
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_t_mall_auth_status.go#L1-L32)
- [card_recharge_t_mall.go](file://internal/consts/card_recharge_t_mall.go#L1-L20)
## 账户状态管理
### 状态切换
账户状态切换功能通过`TMallGameAccountToggle`接口实现用于在启用和禁用状态之间切换账户系统采用事务性操作确保状态变更的原子性
1. 根据账户ID查询当前账户信息
2. 读取当前状态值
3. 切换状态启用禁用
4. 在同一事务中更新数据库
状态值定义在常量中启用状态为"enable"禁用状态为"disable"状态切换操作记录创建时间和更新时间便于审计和追踪
```mermaid
flowchart TD
Start([开始状态切换]) --> Query["查询账户当前状态"]
Query --> Check{"状态为启用?"}
Check --> |是| SetDisable["设置为禁用"]
Check --> |否| SetEnable["设置为启用"]
SetDisable --> Update["更新数据库"]
SetEnable --> Update
Update --> End([结束])
```
**Diagram sources **
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go#L1-L21)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L110-L130)
## 账户查询与获取
### 账户列表查询
`TMallGameAccountList`接口提供账户列表查询功能支持分页和按账户号码模糊查询查询参数包括当前页码每页大小和账户号码关键字
系统构建查询条件链
- 应用分页参数
- 如果提供账户号码则添加模糊匹配条件
- 扫描结果并返回总数和数据列表
查询结果包含账户ID账户号码余额充值次数状态和时间戳等完整信息
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_list.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_list.go#L1-L22)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L90-L105)
### 随机账户获取
`TMallGameAccountGetOneRandom`接口实现随机账户获取功能主要用于订单处理时自动分配账户该功能采用多级策略确保高可用性
1. **缓存优先**首先尝试从Redis缓存中获取与订单号关联的账户
2. **排除已用**收集所有缓存中的账户号码避免重复分配
3. **随机选择**从可用账户池中随机选取一个未被使用的账户
4. **自动补货**当可用账户少于阈值时异步创建新账户
5. **缓存结果**将分配的账户与订单号关联并缓存24小时
系统使用分布式锁gmlock确保并发环境下的数据一致性防止同一订单被分配多个账户
```mermaid
flowchart TD
Start([开始获取随机账户]) --> CheckCache["检查订单缓存"]
CheckCache --> CacheHit{"缓存命中?"}
CacheHit --> |是| ReturnCache["返回缓存账户"]
CacheHit --> |否| GetKeys["获取所有缓存键"]
GetKeys --> Filter["筛选账户缓存"]
Filter --> Collect["收集已用账户"]
Collect --> RandomSelect["随机选择可用账户"]
RandomSelect --> LowStock{"账户不足?"}
LowStock --> |是| CreateBatch["异步创建100个新账户"]
LowStock --> |否| Assign["分配账户"]
CreateBatch --> Assign
Assign --> CacheResult["缓存分配结果"]
CacheResult --> ReturnResult["返回账户"]
ReturnCache --> End([结束])
ReturnResult --> End
```
**Diagram sources **
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go#L1-L59)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L135-L185)
## 数据模型与持久化
### 数据实体
账户数据模型`V1RechargeTMallAccount`包含以下字段
- **id**: 账户唯一标识UUID
- **accountNumber**: 账户号码邮箱格式
- **balance**: 账户余额浮点数
- **rechargeTimes**: 充值次数整数
- **status**: 账户状态字符串
- **createdAt**: 创建时间
- **updatedAt**: 更新时间
- **deletedAt**: 删除时间软删除标记
数据模型通过GoFrame的ORM映射到数据库表`recharge_t_mall_account`支持时间戳自动管理
### 数据访问层
数据访问对象`V1RechargeTMallAccount`封装了对账户表的所有数据库操作包括
- 插入新账户
- 查询账户列表
- 根据ID或账户号码查询单个账户
- 更新账户状态
- 删除账户记录
所有写操作均支持事务上下文确保在复杂业务逻辑中的数据一致性
**Section sources**
- [v_1_recharge_t_mall_account.go](file://internal/model/entity/v_1_recharge_t_mall_account.go#L1-L21)
- [v_1_recharge_t_mall_account.go](file://internal/dao/v_1_recharge_t_mall_account.go#L1-L27)
## 异常处理与数据一致性
### 异常处理策略
系统采用分层异常处理机制
- **控制器层**使用`errHandler.WrapError`统一包装错误转换为标准错误码
- **服务层**返回原始错误由上层决定处理方式
- **数据访问层**抛出数据库异常由事务管理器处理
关键操作如账户创建状态切换等均在数据库事务中执行确保原子性当操作失败时事务自动回滚避免数据不一致
### 数据一致性保障
系统通过以下机制保障数据一致性
- **事务性操作**所有写操作在事务中执行
- **唯一性检查**创建账户前验证账户号码唯一性
- **状态验证**操作前检查账户当前状态是否允许变更
- **缓存同步**账户分配后及时更新缓存状态
对于账户创建操作系统在循环中生成账户号码并检查唯一性确保不会创建重复账户
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_create.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_create.go#L1-L21)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L30-L55)
## 性能优化与缓存策略
### 缓存设计
系统采用Redis作为缓存存储实现以下优化
- **订单-账户映射缓存**将订单号与分配的账户号码关联缓存有效期24小时
- **热点账户预加载**监控账户使用情况自动补充可用账户池
- **分布式锁**使用`gmlock`防止并发冲突确保缓存操作的原子性
缓存策略显著减少了数据库查询压力特别是在高并发订单处理场景下避免了重复的账户分配计算
### 异步补货机制
当系统检测到可用账户数量低于阈值10自动触发异步补货
- 启动goroutine创建100个新账户
- 在后台执行不影响主业务流程
- 避免账户耗尽导致的服务中断
该机制确保账户池始终保持充足提高系统可用性
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go#L1-L59)
- [account.go](file://internal/logic/card_t_mall_account/account.go#L135-L185)
## 常见问题与解决方案
### 账户授权失败
**问题现象**调用天猫授权接口返回失败无法获取访问令牌
**可能原因**
- 授权码code已过期
- 应用配置错误AppKey/Secret
- 网络连接问题
- 天猫平台服务异常
**解决方案**
1. 检查授权码有效期重新发起授权流程
2. 验证应用配置信息是否正确
3. 检查网络连接和防火墙设置
4. 查看系统日志获取详细错误信息
5. 重试机制实现指数退避重试策略
### 状态同步异常
**问题现象**账户状态在数据库和缓存中不一致导致分配了已禁用的账户
**可能原因**
- 状态切换未及时更新缓存
- 缓存过期策略不合理
- 并发操作导致竞态条件
**解决方案**
1. 实现状态变更时的缓存失效机制
2. 在状态切换后清除相关缓存
3. 加强分布式锁的使用范围
4. 增加缓存一致性检查逻辑
5. 实现缓存与数据库的最终一致性同步
### 随机账户获取超时
**问题现象**在高并发场景下随机获取账户接口响应缓慢或超时
**可能原因**
- 账户池耗尽频繁触发补货
- 缓存访问瓶颈
- 数据库查询性能下降
**解决方案**
1. 调整补货阈值和数量提前补充账户
2. 优化缓存访问模式减少锁竞争
3. 为账户表添加适当索引
4. 实现账户预分配池减少实时计算
5. 监控账户使用速率动态调整策略
**Section sources**
- [card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_get_one_random.go#L1-L59)
- [card_info_t_mall_game_v1_t_mall_game_account_toggle.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_toggle.go#L1-L21)

View File

@@ -0,0 +1,304 @@
# 商户管理逻辑
<cite>
**本文档引用的文件**
- [merchant.go](file://internal/model/merchant.go)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
- [merchant_v1_merchant_config_detail.go](file://internal/controller/merchant/merchant_v1_merchant_config_detail.go)
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go)
- [merchant_v1_merchant_sample_all_list.go](file://internal/controller/merchant/merchant_v1_merchant_sample_all_list.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
- [v_1_merchant_deploy_info.go](file://internal/dao/internal/v_1_merchant_deploy_info.go)
- [merchant.go](file://internal/service/merchant.go)
- [config.go](file://api/merchant/v1/config.go)
</cite>
## 目录
1. [引言](#引言)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录)如有必要
## 引言
本文档详细阐述了kami_backend系统中商户管理业务逻辑的实现重点说明商户配置管理商户部署信息维护和商户样本管理的功能实现以及商户与卡密通道支付方式的关联关系文档解释了商户配置的增删改查操作流程和权限控制机制描述了商户部署信息的同步策略和状态管理并提供了商户管理API的使用示例和最佳实践同时包括了商户数据隔离策略和多租户支持的实现细节
## 项目结构
商户管理功能主要分布在`api/merchant``internal/controller/merchant`目录下通过分层架构实现业务逻辑API接口定义在`api/merchant/v1`包中控制器实现位于`internal/controller/merchant`包中服务层逻辑在`internal/service/merchant.go`中定义数据访问对象DAO则在`internal/dao/internal`包中实现
```mermaid
graph TB
subgraph "API层"
A[api/merchant/v1/config.go]
B[api/merchant/v1/deploy.go]
C[api/merchant/v1/model.go]
end
subgraph "控制器层"
D[internal/controller/merchant/merchant_v1_merchant_config_list.go]
E[internal/controller/merchant/merchant_v1_merchant_config_detail.go]
F[internal/controller/merchant/merchant_v1_merchant_config_update.go]
G[internal/controller/merchant/merchant_v1_merchant_config_status.go]
H[internal/controller/merchant/merchant_v1_merchant_sample_all_list.go]
end
subgraph "服务层"
I[internal/service/merchant.go]
end
subgraph "数据访问层"
J[internal/dao/internal/v_1_merchant_info.go]
K[internal/dao/internal/v_1_merchant_deploy_info.go]
end
A --> D
B --> D
C --> D
D --> I
E --> I
F --> I
G --> I
H --> I
I --> J
I --> K
```
**图示来源**
- [config.go](file://api/merchant/v1/config.go)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
- [merchant.go](file://internal/service/merchant.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
**章节来源**
- [merchant.go](file://internal/model/merchant.go)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
## 核心组件
商户管理的核心组件包括商户配置管理商户部署信息维护和商户样本管理这些功能通过`IMerchant`接口定义并由`service.Merchant()`实现系统通过`V1MerchantInfoDao``V1MerchantDeployInfoDao`两个数据访问对象分别管理商户基本信息和部署信息
**章节来源**
- [merchant.go](file://internal/service/merchant.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
- [v_1_merchant_deploy_info.go](file://internal/dao/internal/v_1_merchant_deploy_info.go)
## 架构概述
商户管理模块采用典型的分层架构从API接口到数据访问层形成清晰的调用链路API层定义了商户配置的增删改查接口控制器层处理HTTP请求并调用服务层服务层封装业务逻辑并协调数据访问DAO层负责与数据库交互
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant DAO as "数据访问层"
participant DB as "数据库"
Client->>API : 发起商户配置请求
API->>Controller : 路由到对应控制器
Controller->>Service : 调用服务方法
Service->>DAO : 执行数据操作
DAO->>DB : 执行SQL查询
DB-->>DAO : 返回查询结果
DAO-->>Service : 返回数据实体
Service-->>Controller : 返回业务结果
Controller-->>API : 返回响应数据
API-->>Client : 返回JSON响应
Note over Client,DB : 商户管理模块调用流程
```
**图示来源**
- [merchant.go](file://internal/service/merchant.go)
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
## 详细组件分析
### 商户配置管理分析
商户配置管理功能实现了商户信息的增删改查操作包括商户基本信息状态管理和权限控制系统通过`MerchantConfigList``MerchantConfigDetail``MerchantConfigUpdate``MerchantConfigStatus`等接口提供完整的配置管理能力
#### 商户配置类图
```mermaid
classDiagram
class MerchantInfoRecord {
+string MerchantName
+string MerchantUid
+string MerchantKey
+string MerchantSecret
+string LoginAccount
+string LoginPassword
+bool AutoSettle
+bool AutoPayFor
+string WhiteIps
+string Remark
+string SinglePayForRoadUid
+string RollPayForRoadCode
+float PayforFee
}
class MerchantSimpleInfoRecord {
+string MerchantUid
+string MerchantName
+string BelongAgentUid
+string BelongAgentName
+int Status
+string OtpSecret
}
class MerchantListParamsInput {
+string MerchantUid
+string MerchantName
+int Current
+int PageSize
}
class MerchantDeployInfoStrategyOutput {
+string[] RestrictArea
+bool IsRestrictAgent
+bool IsRestrictCardPass
+bool IsRestrictDevice
+bool IsRestrictIp
+bool IsRestrictInternalIp
}
MerchantInfoRecord <|-- MerchantSimpleInfoRecord : "继承"
MerchantListParamsInput --> MerchantInfoRecord : "查询参数"
MerchantDeployInfoStrategyOutput --> MerchantSimpleInfoRecord : "部署策略"
```
**图示来源**
- [merchant.go](file://internal/model/merchant.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
#### 商户配置更新序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "ControllerV1"
participant Service as "IMerchant"
participant DAO as "V1MerchantInfoDao"
participant DB as "数据库"
Client->>Controller : MerchantConfigUpdate请求
Controller->>Service : 调用UpdateDetail方法
Service->>DAO : 获取商户信息
DAO->>DB : 查询merchant_info表
DB-->>DAO : 返回商户数据
DAO-->>Service : 返回数据实体
Service->>Service : 更新商户信息
Service->>DAO : 保存更新
DAO->>DB : 执行UPDATE语句
DB-->>DAO : 返回执行结果
DAO-->>Service : 返回操作结果
Service-->>Controller : 返回成功/失败
Controller-->>Client : 返回响应
Note over Client,DB : 商户配置更新流程
```
**图示来源**
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go)
- [merchant.go](file://internal/service/merchant.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
**章节来源**
- [merchant_v1_merchant_config_update.go](file://internal/controller/merchant/merchant_v1_merchant_config_update.go)
- [merchant.go](file://internal/service/merchant.go)
### 商户部署信息管理分析
商户部署信息管理功能负责维护商户的部署策略和通道配置包括支付方式代付通道区域限制等系统通过`merchant_deploy_info`表存储这些配置信息并提供相应的增删改查接口
#### 商户部署信息类图
```mermaid
classDiagram
class MerchantDeployRecord {
+string MerchantUid
+string PayType
+string SingleRoadUid
+string SingleRoadName
+float SingleRoadPlatformRate
+float SingleRoadAgentRate
+string RollRoadCode
+string RollRoadName
+float RollRoadPlatformRate
+float RollRoadAgentRate
+string[] RestrictArea
+bool IsLoan
+float LoanRate
+int LoanDays
+int UnfreezeHour
+float WaitUnfreezeAmount
+float LoanAmount
+bool AutoSettle
+bool AutoPayfor
+bool IsRestrictAgent
+bool IsRestrictCardPass
+bool IsRestrictDevice
+bool IsRestrictIp
+bool IsRestrictInternalIp
+string SubmitStrategy
}
class MerchantDeployInfoStrategyOutput {
+string[] RestrictArea
+bool IsRestrictAgent
+bool IsRestrictCardPass
+bool IsRestrictDevice
+bool IsRestrictIp
+bool IsRestrictInternalIp
}
MerchantDeployRecord --> MerchantDeployInfoStrategyOutput : "包含"
```
**图示来源**
- [merchant.go](file://internal/model/merchant.go)
- [v_1_merchant_deploy_info.go](file://internal/dao/internal/v_1_merchant_deploy_info.go)
**章节来源**
- [v_1_merchant_deploy_info.go](file://internal/dao/internal/v_1_merchant_deploy_info.go)
- [merchant.go](file://internal/model/merchant.go)
## 依赖分析
商户管理模块与其他系统组件存在明确的依赖关系它依赖于权限认证系统进行访问控制依赖于数据库访问层进行数据持久化并为其他业务模块提供商户信息查询服务
```mermaid
graph TD
A[商户管理模块] --> B[权限认证系统]
A --> C[数据库访问层]
A --> D[配置管理]
A --> E[代付通道管理]
A --> F[卡密通道管理]
B --> G[SysAuth]
C --> H[V1MerchantInfoDao]
C --> I[V1MerchantDeployInfoDao]
D --> J[SysConfigDict]
E --> K[PayForRoad]
F --> L[CardChannel]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#bbf,stroke:#333
style D fill:#bbf,stroke:#333
style E fill:#bbf,stroke:#333
style F fill:#bbf,stroke:#333
```
**图示来源**
- [merchant.go](file://internal/service/merchant.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
- [v_1_merchant_deploy_info.go](file://internal/dao/internal/v_1_merchant_deploy_info.go)
**章节来源**
- [merchant.go](file://internal/service/merchant.go)
- [sys_auth.go](file://internal/service/sys_auth.go)
- [v_1_merchant_info.go](file://internal/dao/internal/v_1_merchant_info.go)
## 性能考虑
商户管理模块在设计时考虑了性能优化通过分页查询缓存机制和数据库索引等方式提高查询效率对于频繁访问的商户信息系统可以考虑引入Redis缓存减少数据库访问压力同时所有数据库操作都使用了参数化查询防止SQL注入攻击
## 故障排除指南
当商户管理功能出现异常时可以按照以下步骤进行排查
1. 检查API接口返回的错误码和错误信息
2. 查看系统日志中的相关错误记录
3. 验证数据库连接是否正常
4. 检查商户信息表中的数据完整性
5. 确认权限认证是否通过
**章节来源**
- [merchant_v1_merchant_config_list.go](file://internal/controller/merchant/merchant_v1_merchant_config_list.go)
- [merchant_v1_merchant_config_detail.go](file://internal/controller/merchant/merchant_v1_merchant_config_detail.go)
- [merchant_v1_merchant_config_status.go](file://internal/controller/merchant/merchant_v1_merchant_config_status.go)
## 结论
kami_backend的商户管理模块实现了完整的商户配置管理部署信息维护和样本管理功能系统通过清晰的分层架构和规范的接口设计提供了稳定可靠的商户管理服务权限控制机制确保了数据安全而灵活的配置选项满足了不同商户的个性化需求该模块为整个系统的商户管理提供了坚实的基础

View File

@@ -0,0 +1,291 @@
# 权限策略管理
<cite>
**本文档引用文件**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_auth_rule_v1_rule_search.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_search.go)
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go)
- [v1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go)
</cite>
## 目录
1. [简介](#简介)
2. [权限策略数据模型](#权限策略数据模型)
3. [权限策略动态管理机制](#权限策略动态管理机制)
4. [权限策略查询接口实现](#权限策略查询接口实现)
5. [权限策略持久化与一致性保障](#权限策略持久化与一致性保障)
6. [权限策略备份恢复与迁移](#权限策略备份恢复与迁移)
7. [权限策略审计日志记录](#权限策略审计日志记录)
8. [性能监控与告警配置](#性能监控与告警配置)
## 简介
本文档详细阐述了kami_backend系统中权限策略的管理机制系统采用基于Casbin的RBAC基于角色的访问控制模型实现了权限策略的动态加载更新和同步权限策略以菜单按钮等形式组织支持分层树形结构并通过角色进行权限分配系统提供了完整的权限策略生命周期管理功能包括创建查询更新删除以及与角色的绑定操作
## 权限策略数据模型
权限策略的核心数据结构定义在`internal/model/sys_auth_rule.go`主要包含以下字段
- **Name**: 规则名称
- **Title**: 菜单标题
- **MenuType**: 类型0目录1菜单2按钮
- **Weigh**: 权重用于排序
- **IsHide**: 显示状态
- **Path**: 路由地址
- **IdAdmin**: 是否管理员独享
- **Component**: 组件路径
- **Children**: 子节点列表形成树形结构
权限策略与角色的关联通过Casbin的策略规则实现存储在数据库的`sys_casbin_rule`表中
```mermaid
classDiagram
class SysAuthRule {
+string Name
+string Title
+uint MenuType
+int Weigh
+uint IsHide
+string Path
+int IdAdmin
+string Component
+[]*SysAuthRule Children
}
class V1SysAuthRule {
+uint Id
+string CreatedAt
+string UpdatedAt
+string DeletedAt
}
class SysAuthRuleInfoOutput {
+uint Id
+string Name
+string Title
+uint MenuType
+int Weigh
+uint IsHide
+string Path
+int IdAdmin
+string Component
+[]*SysAuthRuleInfoOutput Children
}
class SysAuthRuleTreeOutput {
+uint Id
+string Name
+string Title
+uint MenuType
+int Weigh
+uint IsHide
+string Path
+int IdAdmin
+string Component
+[]*SysAuthRuleTreeOutput Children
}
SysAuthRule <|-- V1SysAuthRule : "继承"
SysAuthRule --> SysAuthRuleInfoOutput : "转换"
SysAuthRule --> SysAuthRuleTreeOutput : "转换"
```
**Diagram sources**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L10)
**Section sources**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L40)
## 权限策略动态管理机制
权限策略的动态管理通过控制器层Controller和服务层Service协同完成控制器接收HTTP请求调用服务层接口执行具体业务逻辑
### 权限策略加载流程
系统启动时权限策略从数据库`v1_sys_auth_rule`表中加载并构建树形结构缓存当用户登录时系统根据用户角色动态生成其可访问的菜单列表
### 权限策略更新与同步流程
权限策略的更新操作添加修改删除通过API接口触发流程如下
1. 前端发起HTTP请求POST/PUT/DELETE
2. 控制器接收请求并进行参数校验
3. 调用`ISysAuthRule`服务接口执行数据库操作
4. 操作成功后更新Casbin策略引擎中的权限规则
5. 返回操作结果给前端
```mermaid
sequenceDiagram
participant 前端 as 前端
participant 控制器 as 控制器
participant 服务 as 服务
participant 数据库 as 数据库
participant Casbin as Casbin引擎
前端->>控制器 : 发起权限更新请求
控制器->>控制器 : 参数校验
控制器->>服务 : 调用服务方法
服务->>数据库 : 执行数据库操作
数据库-->>服务 : 返回结果
服务->>Casbin : 更新策略规则
Casbin-->>服务 : 确认更新
服务-->>控制器 : 返回结果
控制器-->>前端 : 返回响应
```
**Diagram sources**
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L14)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L14)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L14)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**Section sources**
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L14)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L14)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L14)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
## 权限策略查询接口实现
权限策略的查询接口支持分页条件过滤和结果排序功能主要通过`RuleSearch`接口实现
### 查询接口定义
查询接口定义在`api/sys_auth_rule/v1/sys_auth_rule.go`主要参数包括
- **Title**: 菜单名称用于模糊匹配
- **Component**: 组件路径用于精确匹配
### 查询实现逻辑
查询逻辑在`internal/service/sys_auth_rule.go`中实现流程如下
1. 接收查询请求参数
2. 构建数据库查询条件
3. `v1_sys_auth_rule`表中查询数据
4. 将查询结果转换为树形结构
5. 返回结果给调用方
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["校验输入参数"]
ValidateInput --> InputValid{"参数有效?"}
InputValid --> |否| ReturnError["返回错误"]
InputValid --> |是| BuildQuery["构建查询条件"]
BuildQuery --> ExecuteQuery["执行数据库查询"]
ExecuteQuery --> TransformResult["转换为树形结构"]
TransformResult --> ReturnResult["返回结果"]
ReturnError --> End([结束])
ReturnResult --> End
```
**Diagram sources**
- [sys_auth_rule_v1_rule_search.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_search.go#L1-L14)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**Section sources**
- [sys_auth_rule_v1_rule_search.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_search.go#L1-L14)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
## 权限策略持久化与一致性保障
### 持久化存储方案
权限策略数据持久化存储在关系型数据库中主要涉及以下表
- **v1_sys_auth_rule**: 存储权限策略的基本信息
- **v1_sys_casbin_rule**: 存储Casbin策略规则实现权限的细粒度控制
### 分布式环境下的策略一致性保障
在分布式环境下系统通过以下机制保障权限策略的一致性
1. **数据库事务**: 所有权限策略的变更操作都使用数据库事务确保数据的原子性和一致性
2. **Casbin适配器**: 使用数据库适配器确保Casbin策略引擎与数据库中的策略规则保持同步
3. **缓存一致性**: 当权限策略变更时清除相关缓存确保所有节点获取到最新的权限数据
```mermaid
erDiagram
v1_sys_auth_rule {
uint id PK
string name
string title
uint menu_type
int weigh
uint is_hide
string path
int id_admin
string component
uint parent_id FK
timestamp created_at
timestamp updated_at
}
v1_sys_casbin_rule {
uint id PK
string p_type
string v0
string v1
string v2
string v3
string v4
string v5
timestamp created_at
timestamp updated_at
}
v1_sys_auth_rule ||--o{ v1_sys_casbin_rule : "权限规则"
```
**Diagram sources**
- [v1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go#L1-L20)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
**Section sources**
- [v1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go#L1-L20)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 权限策略备份恢复与迁移
### 备份方案
权限策略的备份应包含以下内容
1. **数据库备份**: 定期备份`v1_sys_auth_rule``v1_sys_casbin_rule`表的数据
2. **配置文件备份**: 备份Casbin模型配置文件`rbac_model.conf`
### 恢复方案
权限策略的恢复流程
1. 恢复数据库备份到目标环境
2. 验证数据完整性
3. 重启服务确保Casbin引擎重新加载策略规则
### 迁移指南
权限策略迁移时应注意
1. 确保源环境和目标环境的Casbin模型配置一致
2. 迁移过程中应停止服务避免数据不一致
3. 迁移完成后进行全面的权限功能测试
**Section sources**
- [v1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go#L1-L20)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 权限策略审计日志记录
系统通过记录权限策略的变更日志实现操作的可追溯性审计日志应包含以下信息
- **操作类型**: 添加修改删除等
- **操作人**: 执行操作的用户ID
- **操作时间**: 操作发生的时间戳
- **操作详情**: 变更前后的权限策略信息
审计日志的记录应在权限策略变更的事务中完成确保日志与数据变更的一致性
**Section sources**
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L14)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L14)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L14)
## 性能监控与告警配置
### 性能监控指标
建议监控以下关键性能指标
- **权限查询响应时间**: 监控`RuleSearch`等查询接口的平均响应时间
- **权限更新成功率**: 监控权限策略更新操作的成功率
- **Casbin策略加载时间**: 监控Casbin引擎加载策略规则的时间
### 异常告警配置
建议配置以下告警规则
- 当权限查询平均响应时间超过500ms时告警
- 当权限更新操作失败率超过1%时告警
- 当Casbin策略加载时间超过1秒时告警
这些监控和告警配置有助于及时发现权限系统中的性能瓶颈和异常情况
**Section sources**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [sys_auth_rule_v1_rule_search.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_search.go#L1-L14)

View File

@@ -0,0 +1,364 @@
# 权限规则定义
<cite>
**本文档引用文件**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [model.go](file://api/sys_auth_rule/v1/model.go)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
</cite>
## 目录
1. [简介](#简介)
2. [权限规则数据模型设计](#权限规则数据模型设计)
3. [权限规则接口实现](#权限规则接口实现)
4. [权限规则与角色菜单的关联关系](#权限规则与角色菜单的关联关系)
5. [多层级权限继承机制](#多层级权限继承机制)
6. [权限规则配置最佳实践](#权限规则配置最佳实践)
7. [权限规则冲突检测与解决策略](#权限规则冲突检测与解决策略)
8. [权限规则版本管理建议](#权限规则版本管理建议)
## 简介
本文档详细阐述了 kami_backend 系统中权限规则的定义实现机制与最佳实践权限系统是保障系统安全的核心组件通过精细化的权限控制实现不同角色对系统资源的访问隔离本文深入分析权限规则的数据结构接口实现关联关系及高级特性为系统维护和扩展提供全面的技术指导
## 权限规则数据模型设计
权限规则的数据模型设计基于树形结构支持目录菜单和按钮三级权限粒度核心字段包括规则ID规则类型规则值等具备良好的扩展性和查询效率
```mermaid
erDiagram
SYS_AUTH_RULE {
uint id PK
uint pid FK
string name UK
string title
uint menuType
int weigh
uint isHide
string path
string component
uint isLink
uint isIframe
uint isCached
uint isAffix
string linkUrl
string redirect
string icon
string condition
string remark
string moduleType
uint modelId
datetime createdAt
datetime updatedAt
}
SYS_AUTH_RULE ||--o{ SYS_AUTH_RULE : "父子关系"
```
**图示来源**
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
- [v_1_sys_auth_rule.go](file://internal/dao/v_1_sys_auth_rule.go#L21-L23)
**本节来源**
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
- [model.go](file://api/sys_auth_rule/v1/model.go#L6-L52)
### 核心字段说明
| 字段名 | 类型 | 必填 | 约束 | 说明 |
|--------|------|------|------|------|
| id | uint | | 主键 | 权限规则唯一标识 |
| pid | uint | | 外键 | 父级规则ID根节点为0 |
| name | string | | 唯一索引 | 规则编码用于权限校验 |
| title | string | | 长度1-100 | 规则显示名称 |
| menuType | uint | | 0-2 | 类型0目录 1菜单 2按钮 |
| weigh | int | | - | 权重用于排序 |
| isHide | uint | | 0或1 | 显示状态0显示 1隐藏 |
| path | string | | - | 路由地址 |
| component | string | | - | 前端组件路径 |
| isLink | uint | | 0或1 | 是否外链 |
| isIframe | uint | | 0或1 | 是否内嵌iframe |
| isCached | uint | | 0或1 | 是否缓存 |
| isAffix | uint | | 0或1 | 是否固定标签页 |
| linkUrl | string | | - | 外链地址 |
| redirect | string | | - | 路由重定向地址 |
| icon | string | | - | 图标标识 |
| condition | string | | - | 权限条件表达式 |
| remark | string | | - | 备注信息 |
| moduleType | string | | - | 所属模块类型 |
| modelId | uint | | - | 关联模型ID |
**本节来源**
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
- [model.go](file://api/sys_auth_rule/v1/model.go#L6-L52)
## 权限规则接口实现
权限规则的增删改查接口实现了完整的业务逻辑包括请求参数验证数据持久化和缓存更新等关键环节
### 创建接口实现
创建权限规则接口`RuleAdd`接收前端提交的规则信息执行严格的参数验证后持久化到数据库
```mermaid
sequenceDiagram
participant 前端 as 前端应用
participant 控制器 as 控制器
participant 服务层 as 服务层
participant 数据访问层 as 数据访问层
participant 数据库 as 数据库
前端->>控制器 : POST /menu/add
控制器->>控制器 : 参数验证
控制器->>服务层 : 调用Add方法
服务层->>数据访问层 : 插入记录
数据访问层->>数据库 : 执行INSERT
数据库-->>数据访问层 : 返回结果
数据访问层-->>服务层 : 返回插入ID
服务层->>服务层 : 更新缓存
服务层-->>控制器 : 返回成功
控制器-->>前端 : 返回响应
```
**图示来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L30-L67)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L15)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**本节来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L30-L67)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L15)
### 更新接口实现
更新权限规则接口`RuleUpdate`接收规则ID和更新字段确保数据一致性并维护缓存同步
```mermaid
sequenceDiagram
participant 前端 as 前端应用
participant 控制器 as 控制器
participant 服务层 as 服务层
participant 数据访问层 as 数据访问层
participant 数据库 as 数据库
前端->>控制器 : PUT /menu/update
控制器->>控制器 : 参数验证
控制器->>服务层 : 调用Update方法
服务层->>数据访问层 : 查询原记录
数据访问层->>数据库 : 执行SELECT
数据库-->>数据访问层 : 返回记录
数据访问层-->>服务层 : 返回记录
服务层->>数据访问层 : 更新记录
数据访问层->>数据库 : 执行UPDATE
数据库-->>数据访问层 : 返回结果
数据访问层-->>服务层 : 返回结果
服务层->>服务层 : 清除缓存
服务层-->>控制器 : 返回成功
控制器-->>前端 : 返回响应
```
**图示来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L75-L104)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L15)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**本节来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L75-L104)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L15)
### 删除接口实现
删除权限规则接口`RuleDelete`支持批量删除采用软删除策略并维护树形结构完整性
```mermaid
flowchart TD
A[接收删除请求] --> B{参数验证}
B --> |失败| C[返回错误]
B --> |成功| D[查询待删除节点]
D --> E{是否存在子节点}
E --> |是| F[级联删除子节点]
E --> |否| G[标记删除状态]
F --> H[更新数据库]
G --> H
H --> I[清除相关缓存]
I --> J[返回成功]
```
**图示来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L102-L104)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L15)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**本节来源**
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go#L102-L104)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L15)
## 权限规则与角色菜单的关联关系
权限规则通过中间表与角色建立多对多关联关系实现灵活的权限分配机制
```mermaid
erDiagram
SYS_ROLE {
uint id PK
string name
string remark
}
SYS_AUTH_RULE {
uint id PK
string name
string title
}
SYS_ROLE_RULE {
uint roleId PK,FK
uint ruleId PK,FK
}
SYS_ROLE ||--o{ SYS_ROLE_RULE : "包含"
SYS_AUTH_RULE ||--o{ SYS_ROLE_RULE : "被包含"
```
**图示来源**
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
- [sys_role.go](file://internal/model/entity/v_1_sys_role.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
**本节来源**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
### 关联管理接口
系统提供专门的接口用于管理角色与权限规则的绑定关系
- `BindRoleRule`: 绑定角色与权限规则
- `UpdateRoleRule`: 更新角色权限规则
- `GetMenuRoles`: 获取规则关联的角色列表
这些接口确保权限分配的原子性和一致性避免出现权限配置不一致的问题
**本节来源**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [sys_auth_rule.go](file://internal/controller/sys_auth_rule/sys_auth_rule.go)
## 多层级权限继承机制
系统采用树形结构实现多层级权限继承子节点自动继承父节点的权限配置
```mermaid
classDiagram
class SysAuthRule {
+uint id
+uint pid
+string name
+string title
+uint menuType
+int weigh
+uint isHide
+string path
+string component
+Children []*SysAuthRule
}
class SysAuthRuleTreeRes {
+*SysAuthRuleInfoRes
+Children []*SysAuthRuleTreeRes
}
class RuleSearchInput {
+MenuCreateReq
}
SysAuthRule <|-- SysAuthRuleTreeRes
SysAuthRuleTreeRes "1" *-- "0..*" SysAuthRuleTreeRes : 包含
```
**图示来源**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L10)
- [model.go](file://api/sys_auth_rule/v1/model.go#L20-L25)
- [model.go](file://api/sys_auth_rule/v1/model.go#L6-L17)
**本节来源**
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L10)
- [model.go](file://api/sys_auth_rule/v1/model.go#L20-L25)
### 继承实现逻辑
1. **树形结构构建**通过 `GetMenuListTree` 方法递归构建完整的菜单树
2. **父子关系维护**`FindSonByParentId` 方法用于查找指定父节点的所有子节点
3. **权限继承计算**在权限校验时自动包含父节点的所有权限规则
这种设计确保了权限配置的层次性和可维护性简化了复杂系统的权限管理
**本节来源**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L10)
## 权限规则配置最佳实践
### 权限编码规范
权限编码应遵循统一的命名规范便于管理和维护
- **格式**`模块:功能:操作`
- **示例**`user:profile:read``order:management:create`
- **要求**小写字母数字冒号和下划线长度不超过50字符
### 权限分类
建议将权限规则按以下维度进行分类管理
| 分类 | 说明 | 示例 |
|------|------|------|
| 功能权限 | 系统功能模块访问控制 | dashboard:view |
| 数据权限 | 数据范围访问控制 | order:data:own |
| 操作权限 | 具体操作行为控制 | user:create |
| 字段权限 | 字段级访问控制 | user:profile:email |
### 权限粒度控制
根据业务需求合理设置权限粒度
1. **粗粒度**适用于功能模块级别的控制
2. **细粒度**适用于具体操作和数据范围的控制
3. **动态权限**结合条件表达式实现动态权限判断
**本节来源**
- [model.go](file://api/sys_auth_rule/v1/model.go#L6-L52)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
## 权限规则冲突检测与解决策略
系统提供权限冲突检测机制确保权限配置的一致性和有效性
### 冲突检测规则
1. **编码冲突**同一层级下权限编码必须唯一
2. **路径冲突**路由路径不能重复
3. **循环引用**禁止父子节点形成循环引用
4. **权限重叠**避免相同功能的权限规则重复定义
### 解决策略
- **优先级机制**明确权限规则的优先级顺序
- **继承覆盖**子节点可以覆盖父节点的特定权限
- **显式声明**通过明确的权限声明避免隐式冲突
- **审计日志**记录权限变更历史便于追溯和分析
**本节来源**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
## 权限规则版本管理建议
为确保权限系统的稳定性和可追溯性建议实施以下版本管理策略
1. **变更记录**详细记录每次权限规则的变更内容
2. **版本快照**定期创建权限配置的版本快照
3. **灰度发布**新权限配置先在测试环境验证
4. **回滚机制**建立快速回滚通道应对配置错误
5. **审批流程**重要权限变更需经过审批流程
通过完善的版本管理可以有效降低权限配置风险保障系统安全稳定运行
**本节来源**
- [v_1_sys_auth_rule.go](file://internal/model/entity/v_1_sys_auth_rule.go#L11-L34)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)

View File

@@ -0,0 +1,413 @@
# 权限规则管理
<cite>
**本文档引用文件**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [sys_auth_rule.go](file://internal/logic/sys_auth_rule/sysAuthRule.go)
- [auth.go](file://internal/middleware/auth.go)
- [sys_role.go](file://internal/logic/sys_role/sysRole.go)
- [sys_casbin.go](file://internal/service/sys_casbin.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
</cite>
## 目录
1. [引言](#引言)
2. [权限系统架构](#权限系统架构)
3. [RBAC模型定义](#rbac模型定义)
4. [权限策略存储与查询](#权限策略存储与查询)
5. [权限验证中间件](#权限验证中间件)
6. [角色与权限管理流程](#角色与权限管理流程)
7. [菜单权限管理](#菜单权限管理)
8. [权限继承与检查机制](#权限继承与检查机制)
9. [权限缓存与性能优化](#权限缓存与性能优化)
10. [安全审计建议](#安全审计建议)
11. [常见权限问题解决方案](#常见权限问题解决方案)
12. [最佳实践](#最佳实践)
## 引言
本文档详细阐述了kami_backend系统中基于Casbin的RBAC基于角色的访问控制权限控制系统的实现机制系统通过灵活的权限规则配置实现了细粒度的访问控制支持角色创建权限分配策略更新等核心功能文档深入分析了权限系统的架构设计实现细节和最佳实践为开发者和系统管理员提供全面的技术参考
## 权限系统架构
kami_backend的权限控制系统采用分层架构设计主要包括权限模型定义策略存储权限验证中间件和管理接口四个核心组件系统基于Casbin框架实现通过RBAC模型进行权限控制支持动态的角色和权限管理
```mermaid
graph TB
subgraph "前端"
UI[用户界面]
end
subgraph "API网关"
AuthMiddleware[权限验证中间件]
end
subgraph "权限核心"
Casbin[Casbin引擎]
RBACModel[RBAC模型]
PolicyStorage[策略存储]
end
subgraph "管理接口"
RoleAPI[角色管理API]
RuleAPI[权限规则API]
MenuAPI[菜单管理API]
end
UI --> AuthMiddleware
AuthMiddleware --> Casbin
Casbin --> RBACModel
Casbin --> PolicyStorage
RoleAPI --> Casbin
RuleAPI --> Casbin
MenuAPI --> Casbin
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L0-L154)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L0-L154)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
## RBAC模型定义
系统采用标准的RBAC权限模型定义在`resource/casbin/rbac_model.conf`文件中该模型包含请求定义策略定义角色定义策略效果和匹配器五个部分实现了基于角色的访问控制
```mermaid
classDiagram
class RBACModel {
+request_definition r = sub, obj, act
+policy_definition p = sub, obj, act
+role_definition g = _, _
+policy_effect e = some(where (p.eft == allow))
+matchers m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
}
class Request {
+string sub
+string obj
+string act
}
class Policy {
+string sub
+string obj
+string act
}
class Role {
+string role
+string parent
}
RBACModel --> Request : "定义"
RBACModel --> Policy : "定义"
RBACModel --> Role : "定义"
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L0-L13)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L0-L13)
## 权限策略存储与查询
权限策略持久化存储在数据库中通过`V1SysCasbinRule`表进行管理系统实现了完整的策略生命周期管理包括保存加载添加删除等操作
### 策略存储结构
权限策略存储采用通用的六字段结构支持Casbin框架的所有策略类型
- **Ptype**: 策略类型p表示权限策略g表示角色继承策略
- **V0-V5**: 策略参数分别对应角色ID规则ID操作类型等
### 策略操作接口
系统提供了完整的策略操作接口封装在`ICasbin`接口中
```mermaid
classDiagram
class ICasbin {
+CasbinEnforcer(ctx) (*SyncedEnforcer, error)
+SavePolicy(model) error
+LoadPolicy(model) error
+AddPolicy(sec, pType, rule) error
+RemovePolicy(sec, pType, rule) error
+AddPolicies(sec, pType, rules) error
+RemovePolicies(sec, pType, rules) error
+RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues) error
}
class CasbinService {
-Enforcer *SyncedEnforcer
-EnforcerErr error
-Ctx context.Context
}
ICasbin <|-- CasbinService
```
**Diagram sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L15-L32)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L34-L38)
**Section sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L0-L49)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
## 权限验证中间件
系统通过中间件实现权限验证支持多种认证方式和白名单机制权限验证流程包括白名单检查Token验证和权限检查三个阶段
```mermaid
flowchart TD
Start([请求进入]) --> WhiteListCheck["检查白名单"]
WhiteListCheck --> IsWhiteList{"在白名单中?"}
IsWhiteList --> |是| AllowAccess["允许访问"]
IsWhiteList --> |否| TokenFrom["获取Token来源"]
TokenFrom --> HasTokenFrom{"有Token来源?"}
HasTokenFrom --> |否| ReturnError["返回Token来源不明"]
HasTokenFrom --> |是| CheckTokenType["检查Token类型"]
CheckTokenType --> IsLogin{"类型为login?"}
IsLogin --> |是| LoginAuth["执行Login认证"]
IsLogin --> |否| IsIframe{"类型为iframe?"}
IsIframe --> |是| IFrameAuth["执行IFrame认证"]
IsIframe --> |否| ReturnError
LoginAuth --> AuthResult{"认证成功?"}
IFrameAuth --> AuthResult
AuthResult --> |是| AllowAccess
AuthResult --> |否| ReturnAuthError["返回认证错误"]
AllowAccess --> NextMiddleware["继续后续中间件"]
ReturnAuthError --> ResponseError["返回错误响应"]
ReturnError --> ResponseError
ResponseError --> End([响应返回])
NextMiddleware --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L0-L154)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L0-L154)
## 角色与权限管理流程
系统提供了完整的角色和权限管理功能支持角色的创建编辑删除和权限分配角色管理通过API接口暴露实现了前后端分离的管理模式
### 角色管理API
角色管理API提供了以下核心功能
- 角色创建创建新的角色并分配初始权限
- 角色编辑修改角色信息和权限分配
- 角色删除删除角色及其关联的权限
- 角色列表获取所有角色信息
### 权限分配流程
权限分配流程如下
1. 管理员选择目标角色
2. 选择需要分配的权限规则
3. 系统调用Casbin API更新策略
4. 权限变更实时生效
```mermaid
sequenceDiagram
participant Admin as "管理员"
participant Frontend as "前端界面"
participant Backend as "后端服务"
participant Casbin as "Casbin引擎"
participant Database as "数据库"
Admin->>Frontend : 发起角色创建请求
Frontend->>Backend : 发送创建角色API请求
Backend->>Casbin : 初始化角色策略
Casbin-->>Backend : 返回策略初始化结果
Backend->>Database : 保存角色信息
Database-->>Backend : 返回保存结果
Backend-->>Frontend : 返回创建成功响应
Frontend->>Admin : 显示创建成功
Admin->>Frontend : 发起权限分配请求
Frontend->>Backend : 发送权限分配API请求
Backend->>Casbin : 调用AddPolicy添加权限
Casbin->>Database : 保存策略到数据库
Database-->>Casbin : 返回保存结果
Casbin-->>Backend : 返回策略添加结果
Backend-->>Frontend : 返回分配成功响应
Frontend->>Admin : 显示分配成功
```
**Diagram sources**
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
**Section sources**
- [sys_role.go](file://internal/logic/sys_role/sysRole.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
## 菜单权限管理
菜单权限管理是系统权限控制的重要组成部分实现了菜单与权限规则的绑定系统支持菜单的增删改查和树形结构展示
### 菜单数据结构
菜单权限数据包含以下关键字段
- **Id**: 菜单ID
- **Pid**: 父菜单ID
- **Name**: 菜单标识符
- **Title**: 菜单标题
- **Path**: 路由路径
- **Component**: 组件路径
- **MenuType**: 菜单类型0:目录, 1:菜单, 2:按钮
- **Weigh**: 权重用于排序
- **IsHide**: 是否隐藏
### 菜单管理流程
```mermaid
flowchart TD
Start([菜单管理开始]) --> OperationChoice["选择操作类型"]
OperationChoice --> CreateMenu{"创建菜单?"}
CreateMenu --> |是| ValidateMenuInfo["验证菜单信息"]
CreateMenu --> |否| EditMenu{"编辑菜单?"}
EditMenu --> |是| FindMenu["查找目标菜单"]
EditMenu --> |否| DeleteMenu{"删除菜单?"}
DeleteMenu --> |是| ConfirmDelete["确认删除"]
DeleteMenu --> |否| ListMenu["获取菜单列表"]
ValidateMenuInfo --> CheckNameExists["检查菜单标识是否存在"]
CheckNameExists --> NameExists{"已存在?"}
NameExists --> |是| ReturnError["返回已存在错误"]
NameExists --> |否| SaveMenu["保存菜单信息"]
FindMenu --> MenuFound{"找到菜单?"}
MenuFound --> |否| ReturnNotFound["返回未找到"]
MenuFound --> |是| UpdateMenu["更新菜单信息"]
ConfirmDelete --> HasChildren{"有子菜单?"}
HasChildren --> |是| DeleteWithChildren["删除菜单及子菜单"]
HasChildren --> |否| DeleteOnly["仅删除当前菜单"]
SaveMenu --> BindPermissions["绑定角色权限"]
UpdateMenu --> BindPermissions
DeleteWithChildren --> RemovePermissions["移除权限策略"]
DeleteOnly --> RemovePermissions
BindPermissions --> UpdateCasbin["更新Casbin策略"]
RemovePermissions --> UpdateCasbin
UpdateCasbin --> Success["操作成功"]
Success --> End([菜单管理结束])
ReturnError --> End
ReturnNotFound --> End
```
**Diagram sources**
- [sys_auth_rule.go](file://internal/logic/sys_auth_rule/sysAuthRule.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
**Section sources**
- [sys_auth_rule.go](file://internal/logic/sys_auth_rule/sysAuthRule.go#L0-L295)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
## 权限继承与检查机制
系统实现了完整的权限继承和检查机制确保权限控制的准确性和高效性
### 权限继承
权限继承基于Casbin的g角色定义支持多级角色继承当一个角色继承另一个角色时它自动获得父角色的所有权限
```mermaid
classDiagram
class Role {
+string Id
+string Name
+string ParentId
+string Remark
}
class UserRole {
+string UserId
+string RoleId
}
class PermissionRule {
+string Id
+string Name
+string Title
+string Path
+int MenuType
}
Role "1" --> "0..*" Role : "继承"
UserRole "1" --> "1" Role : "关联"
Role "1" --> "0..*" PermissionRule : "拥有"
```
### 权限检查流程
权限检查流程如下
1. 解析用户Token获取用户信息
2. 获取用户所属角色
3. 根据请求的资源和操作类型构建权限检查请求
4. 调用Casbin引擎进行权限验证
5. 返回验证结果
**Section sources**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
- [auth.go](file://internal/middleware/auth.go#L0-L154)
## 权限缓存与性能优化
系统通过多种机制优化权限检查的性能确保高并发场景下的响应速度
### 缓存策略
- **Casbin SyncedEnforcer**: 使用SyncedEnforcer实现策略的自动同步和缓存
- **Redis缓存**: 对频繁访问的权限数据进行Redis缓存
- **本地缓存**: 在应用层实现本地缓存减少数据库查询
### 性能优化措施
1. **批量操作**: 支持权限策略的批量添加和删除
2. **事务处理**: 在数据库操作中使用事务确保数据一致性
3. **异步更新**: 对非关键权限变更采用异步更新机制
4. **连接池**: 使用数据库连接池提高数据库访问效率
**Section sources**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
- [utility/pool/pool.go](file://utility/pool/pool.go)
## 安全审计建议
为确保权限系统的安全性建议采取以下审计措施
### 安全审计要点
- **权限变更审计**: 记录所有权限策略的变更操作包括创建修改和删除
- **访问日志**: 记录所有权限检查的请求和结果
- **异常检测**: 监控异常的权限请求模式
- **定期审查**: 定期审查角色和权限分配的合理性
### 安全最佳实践
1. **最小权限原则**: 为角色分配完成工作所需的最小权限
2. **职责分离**: 关键操作需要多个角色协同完成
3. **定期轮换**: 定期轮换管理员账号和权限
4. **多因素认证**: 对敏感操作实施多因素认证
**Section sources**
- [sys_login_log.go](file://internal/logic/sys_login_log/sysLoginLog.go)
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
## 常见权限问题解决方案
### 问题1权限变更未生效
**现象**: 修改角色权限后用户仍无法访问新分配的资源
**解决方案**:
1. 检查Casbin策略是否正确更新
2. 确认数据库中的策略记录已同步
3. 清除相关缓存
4. 重新登录以刷新权限
### 问题2权限继承异常
**现象**: 子角色未正确继承父角色的权限
**解决方案**:
1. 检查角色继承关系配置
2. 验证Casbin的g策略是否正确生成
3. 检查角色继承链是否存在循环引用
### 问题3性能下降
**现象**: 权限检查响应时间变长
**解决方案**:
1. 检查数据库连接池状态
2. 优化权限策略结构减少策略数量
3. 增加缓存容量
4. 分析慢查询日志
**Section sources**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L245)
- [errHandler/handler.go](file://internal/errHandler/handler.go)
## 最佳实践
### 角色设计最佳实践
- **基于职责设计角色**: 按照业务职责划分角色而非按用户划分
- **控制角色数量**: 避免创建过多细粒度的角色
- **使用角色组**: 对相似角色进行分组管理
### 权限分配最佳实践
- **先分配后调整**: 先为角色分配基础权限再根据需要调整
- **批量操作**: 使用批量接口进行大规模权限分配
- **权限复用**: 尽量复用现有权限规则避免重复创建
### 系统维护最佳实践
- **定期备份**: 定期备份权限策略数据
- **版本控制**: 对权限配置进行版本控制
- **文档记录**: 详细记录角色和权限的设计 rationale
**Section sources**
- [sys_role.go](file://internal/logic/sys_role/sysRole.go)
- [sys_auth_rule.go](file://internal/logic/sys_auth_rule/sysAuthRule.go)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)

View File

@@ -0,0 +1,290 @@
# 权限验证机制
<cite>
**本文档引用的文件**
- [auth.go](file://internal/middleware/auth.go)
- [sys_casbin.go](file://internal/service/sys_casbin.go)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [sysRule.go](file://internal/logic/sys_role/sysRule.go)
- [sysAuthRule.go](file://internal/logic/sys_auth_rule/sysAuthRule.go)
</cite>
## 目录
1. [介绍](#介绍)
2. [权限验证中间件实现](#权限验证中间件实现)
3. [RBAC模型配置](#rbac模型配置)
4. [权限检查流程](#权限检查流程)
5. [权限缓存机制](#权限缓存机制)
6. [调试与日志记录](#调试与日志记录)
7. [性能优化策略](#性能优化策略)
8. [扩展与安全加固](#扩展与安全加固)
## 介绍
本文档详细阐述了kami_backend系统中基于Casbin的权限验证机制该机制实现了完整的RBAC基于角色的访问控制模型通过中间件拦截请求识别用户身份并执行权限检查系统支持灵活的权限策略配置高效的权限缓存机制以及可扩展的自定义验证逻辑确保了系统的安全性和高性能
## 权限验证中间件实现
权限验证中间件是整个权限系统的核心组件负责拦截HTTP请求并执行身份验证和权限检查中间件实现了多种验证方式包括标准登录验证和iframe嵌入验证同时维护了一个白名单机制允许特定接口无需权限验证即可访问
中间件的主要功能包括
- 白名单验证检查请求路径是否在无需验证的白名单中
- 登录身份验证解析和验证用户Token确保其有效性和未过期
- iframe身份验证处理嵌入式场景下的特殊身份验证需求
- Token续签在验证通过后自动续签Token提升用户体验
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Middleware as "权限中间件"
participant Token as "Token服务"
participant Redis as "Redis缓存"
Client->>Middleware : 发起API请求
Middleware->>Middleware : 检查白名单
alt 在白名单中
Middleware-->>Client : 直接放行
else 需要验证
Middleware->>Token : 解析请求Token
Token->>Redis : 验证Token有效性
Redis-->>Token : 返回验证结果
Token-->>Middleware : 返回解析结果
alt Token有效
Middleware->>Token : 续签Token
Token-->>Middleware : 返回新Token
Middleware->>Client : 设置新Token并放行
else Token无效
Middleware->>Client : 返回未授权错误
end
end
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L15-L154)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L15-L154)
## RBAC模型配置
系统采用标准的RBAC基于角色的访问控制模型通过配置文件定义权限验证的基本规则和匹配逻辑RBAC模型配置文件位于`resource/casbin/rbac_model.conf`定义了请求定义策略定义角色定义策略效果和匹配器等核心组件
配置文件结构如下
- **请求定义**定义了权限检查的基本参数包括主体sub对象obj和操作act
- **策略定义**定义了权限策略的结构与请求定义保持一致
- **角色定义**定义了角色继承关系支持用户到角色的映射
- **策略效果**定义了当存在至少一个允许策略时即允许访问的逻辑
- **匹配器**定义了具体的权限匹配规则包括角色继承对象匹配和操作匹配
```mermaid
erDiagram
USER ||--o{ USER_ROLE : "拥有"
ROLE ||--o{ ROLE_PERMISSION : "拥有"
PERMISSION ||--o{ MENU : "对应"
USER_ROLE }o--|| ROLE : "关联"
ROLE_PERMISSION }o--|| PERMISSION : "关联"
MENU ||--o{ SUB_MENU : "包含"
USER {
string id PK
string username
string password
int status
datetime created_at
}
ROLE {
int id PK
string name
string remark
int status
int list_order
}
PERMISSION {
int id PK
string name
string title
string path
string component
int menu_type
int weigh
}
MENU {
int id PK
int pid
string name
string title
string path
string component
int menu_type
int is_hide
int is_cached
int is_affix
}
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 权限检查流程
权限检查流程是系统安全控制的核心通过Casbin引擎执行具体的权限验证流程从用户登录开始经过角色分配权限加载到最终的权限检查形成了完整的闭环
### 用户身份识别
系统通过Token机制识别用户身份Token中包含用户ID和会话信息在每次请求时中间件会解析Token并验证其有效性确保用户身份的真实性和安全性
### 权限检查执行
权限检查执行过程包括
1. 获取用户角色通过Casbin的Grouping Policy查询用户关联的角色
2. 加载用户权限根据角色获取对应的权限策略
3. 执行权限匹配使用Casbin的Enforcer执行具体的权限检查
4. 返回检查结果根据匹配结果决定是否允许访问
```mermaid
flowchart TD
Start([开始]) --> CheckWhiteList["检查白名单"]
CheckWhiteList --> IsInWhiteList{"在白名单中?"}
IsInWhiteList --> |是| AllowAccess["允许访问"]
IsInWhiteList --> |否| ParseToken["解析Token"]
ParseToken --> ValidateToken["验证Token有效性"]
ValidateToken --> IsTokenValid{"Token有效?"}
IsTokenValid --> |否| ReturnUnauthorized["返回未授权"]
IsTokenValid --> |是| GetUserRoles["获取用户角色"]
GetUserRoles --> LoadPermissions["加载用户权限"]
LoadPermissions --> CheckPermission["执行权限检查"]
CheckPermission --> IsAllowed{"权限允许?"}
IsAllowed --> |是| AllowAccess
IsAllowed --> |否| ReturnForbidden["返回禁止访问"]
AllowAccess --> End([结束])
ReturnUnauthorized --> End
ReturnForbidden --> End
```
**Diagram sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L39-L49)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L244)
**Section sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L39-L49)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L244)
## 权限缓存机制
系统实现了高效的权限缓存机制通过减少数据库查询次数来提升权限验证的性能缓存机制包括策略缓存角色缓存和用户权限缓存等多个层次确保了系统的高性能和可扩展性
### 缓存更新策略
缓存更新策略采用写时更新模式当权限策略发生变化时立即更新缓存具体更新操作包括
- 添加策略在添加新的权限策略时同步更新缓存
- 删除策略在删除权限策略时从缓存中移除相应条目
- 修改策略在修改权限策略时更新缓存中的对应条目
### 缓存失效处理
系统实现了完善的缓存失效处理机制确保缓存数据的一致性当发生以下情况时相关缓存会被清除
- 用户角色变更
- 权限策略修改
- 系统配置更新
- 定期缓存刷新
```mermaid
classDiagram
class CasbinService {
+CasbinEnforcer(ctx) Enforcer
+SavePolicy(model) error
+LoadPolicy(model) error
+AddPolicy(sec, pType, rule) error
+RemovePolicy(sec, pType, rule) error
}
class CasbinAdapter {
+SavePolicy(model) error
+LoadPolicy(model) error
+AddPolicy(sec, pType, rule) error
+RemovePolicy(sec, pType, rule) error
+AddPolicies(sec, pType, rules) error
+RemovePolicies(sec, ptype, rules) error
+RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues) error
}
class Database {
+V1SysCasbinRule
+Insert(line) error
+Delete(condition) error
+Scan(lines) error
}
class Cache {
+Get(key) value
+Set(key, value) error
+Delete(key) error
+Flush() error
}
CasbinService --> CasbinAdapter : "使用"
CasbinAdapter --> Database : "持久化"
CasbinAdapter --> Cache : "缓存"
Cache --> Database : "回源"
```
**Diagram sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L59-L195)
**Section sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L59-L195)
## 调试与日志记录
系统提供了完善的调试方法和日志记录机制帮助开发人员和运维人员快速定位和解决问题日志记录涵盖了权限验证的各个环节包括Token验证权限检查和错误处理等
### 调试方法
- 启用详细日志通过配置开启详细的权限验证日志
- 使用测试Token在开发环境中使用预定义的测试Token进行调试
- 检查缓存状态监控缓存命中率和缓存大小等指标
- 验证策略加载确认权限策略正确加载到Casbin引擎
### 日志记录建议
- 记录所有权限拒绝事件包括原因和上下文信息
- 记录Token验证失败的详细信息便于安全审计
- 记录权限策略变更操作确保可追溯性
- 定期分析日志发现潜在的安全风险和性能瓶颈
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L15-L154)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L39-L49)
## 性能优化策略
在高并发场景下权限验证系统需要具备良好的性能表现系统通过多种优化策略确保了在高负载下的稳定性和响应速度
### 高并发性能调优
- 连接池优化合理配置数据库连接池大小避免连接耗尽
- 缓存分层采用多级缓存策略减少对后端存储的压力
- 批量操作支持批量权限检查减少单次请求的开销
- 异步处理将非关键操作异步化提升响应速度
### 性能监控指标
- 权限验证响应时间
- 缓存命中率
- 数据库查询次数
- 并发连接数
- 错误率
**Section sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L39-L49)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L0-L244)
## 扩展与安全加固
系统设计了灵活的扩展机制支持自定义权限验证逻辑和安全加固措施满足不同场景下的安全需求
### 自定义权限验证逻辑
- 自定义匹配器支持定义复杂的权限匹配规则
- 上下文感知基于请求上下文执行动态权限检查
- 多因素验证集成多种身份验证方式提升安全性
- 时间限制支持基于时间的权限控制
### 安全加固措施
- Token安全采用加密算法保护Token内容
- 防重放攻击通过时间戳和随机数防止Token重放
- 速率限制防止暴力破解和滥用
- 安全审计记录所有敏感操作便于事后追溯
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L15-L154)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L39-L49)

View File

@@ -0,0 +1,285 @@
# 会话管理
<cite>
**Referenced Files in This Document**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [sysUser_v1_user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go)
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [models.go](file://utility/config/models.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [sys_user_login.go](file://internal/model/sys_user_login.go)
</cite>
## 目录
1. [简介](#简介)
2. [认证流程](#认证流程)
3. [令牌管理](#令牌管理)
4. [认证中间件](#认证中间件)
5. [用户登出机制](#用户登出机制)
6. [安全策略](#安全策略)
7. [性能优化](#性能优化)
8. [总结](#总结)
## 简介
本文档详细阐述了kami_backend系统的会话管理机制包括用户身份验证令牌生成与验证会话控制和安全防护等核心功能系统采用JWTJSON Web Token作为主要的认证机制结合Redis缓存实现高效的会话管理会话管理模块主要由认证控制器令牌服务认证中间件和用户服务等组件构成共同保障系统的安全性和可用性
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
- [auth.go](file://internal/middleware/auth.go#L1-L155)
- [user_token.go](file://utility/token/user_token.go#L1-L135)
## 认证流程
系统的用户认证流程遵循标准的JWT认证模式通过用户名和密码进行身份验证并生成相应的访问令牌认证过程包括验证码验证用户信息查询密码比对和令牌生成等步骤
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "认证控制器"
participant Service as "用户服务"
participant Token as "令牌服务"
Client->>Controller : 提交登录请求(用户名、密码、验证码)
Controller->>Service : 验证验证码
Service-->>Controller : 验证结果
alt 验证失败
Controller-->>Client : 返回验证码错误
else 验证成功
Controller->>Service : 查询用户信息
Service-->>Controller : 返回用户数据
Controller->>Service : 验证密码
Service-->>Controller : 密码验证结果
alt 密码验证失败
Controller-->>Client : 返回用户名或密码错误
else 密码验证成功
Controller->>Token : 生成用户令牌
Token-->>Controller : 返回JWT令牌
Controller-->>Client : 返回登录成功响应(包含令牌)
end
end
```
**Diagram sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L767)
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L767)
## 令牌管理
### 令牌生成
系统使用JWT标准生成用户令牌令牌包含用户ID用户名签发时间过期时间等信息令牌生成过程由`GenerateUserToken`函数实现该函数根据配置的加密密钥对令牌进行签名并将令牌存储在Redis缓存中以支持令牌失效管理
```mermaid
flowchart TD
Start([开始]) --> GenerateClaims["生成令牌声明(Claims)"]
GenerateClaims --> SetClaims["设置用户ID、用户名、签发者、过期时间等"]
SetClaims --> SignToken["使用HS256算法签名令牌"]
SignToken --> StoreRedis["将令牌存储到Redis缓存"]
StoreRedis --> ReturnToken["返回JWT令牌"]
ReturnToken --> End([结束])
```
**Diagram sources**
- [user_token.go](file://utility/token/user_token.go#L1-L135)
### 令牌验证
令牌验证是会话管理的核心环节系统通过`ParseUserToken`函数解析和验证JWT令牌的有效性验证过程包括检查令牌签名过期时间以及从Redis中验证令牌是否存在
```mermaid
flowchart TD
Start([开始]) --> ExtractToken["从请求头提取令牌"]
ExtractToken --> ParseToken["解析JWT令牌"]
ParseToken --> ValidateSignature["验证令牌签名"]
ValidateSignature --> CheckExpired["检查令牌是否过期"]
CheckExpired --> QueryRedis["查询Redis缓存中的令牌"]
QueryRedis --> CompareToken["比较请求令牌与缓存令牌"]
CompareToken --> IsValid{"令牌有效?"}
IsValid --> |是| ReturnSuccess["返回验证成功"]
IsValid --> |否| ReturnFailure["返回验证失败"]
ReturnSuccess --> End([结束])
ReturnFailure --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L155)
- [user_token.go](file://utility/token/user_token.go#L1-L135)
### 令牌刷新
系统实现了智能的令牌刷新机制当令牌的使用时间超过最大刷新时间但未过期时系统会自动为用户生成新的令牌这一机制既保证了用户体验的连续性又增强了系统的安全性
```mermaid
classDiagram
class UserToken {
+string UserID
+string Username
+RegisteredClaims RegisteredClaims
+genToken(ctx context.Context) string, error
}
class TokenService {
+GenerateUserToken(ctx context.Context, userName, userID string) string, error
+ParseUserToken(ctx context.Context, transToken string) *UserToken, error
+RefreshUserToken(ctx context.Context, userToken UserToken) string, error
+DeleteTokenFromRedis(ctx context.Context, userID string) error
}
class TokenConfig {
+string ServerName
+string CacheKey
+int64 Timeout
+int64 MaxRefresh
+[]byte EncryptKey
+string CacheModel
}
TokenService --> UserToken : "使用"
TokenService --> TokenConfig : "读取配置"
```
**Diagram sources**
- [user_token.go](file://utility/token/user_token.go#L1-L135)
- [models.go](file://utility/config/models.go#L1-L61)
**Section sources**
- [user_token.go](file://utility/token/user_token.go#L1-L135)
- [models.go](file://utility/config/models.go#L1-L61)
## 认证中间件
认证中间件是系统安全的第一道防线负责拦截所有需要认证的请求验证令牌的有效性并在必要时进行令牌刷新中间件还支持白名单机制允许特定的公共接口无需认证即可访问
```mermaid
flowchart TD
Start([请求进入]) --> CheckWhiteList["检查是否在白名单"]
CheckWhiteList --> IsWhiteList{"在白名单?"}
IsWhiteList --> |是| PassThrough["直接通过"]
IsWhiteList --> |否| GetToken["从请求获取令牌"]
GetToken --> ValidateToken["验证令牌有效性"]
ValidateToken --> IsValid{"令牌有效?"}
IsValid --> |是| RefreshToken["检查是否需要刷新"]
IsValid --> |否| ReturnError["返回未授权"]
RefreshToken --> NeedRefresh{"需要刷新?"}
NeedRefresh --> |是| GenerateNewToken["生成新令牌"]
NeedRefresh --> |否| Continue["继续处理"]
GenerateNewToken --> SetHeader["设置refresh-token响应头"]
SetHeader --> Continue
Continue --> NextMiddleware["调用下一个中间件"]
ReturnError --> SendResponse["发送错误响应"]
PassThrough --> NextMiddleware
NextMiddleware --> End([处理完成])
SendResponse --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L155)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L155)
## 用户登出机制
### 登出流程
用户登出功能通过`UserLoginOut`控制器实现当用户发起登出请求时系统会解析请求中的令牌提取用户ID并从Redis缓存中删除对应的令牌从而实现令牌的立即失效
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "登出控制器"
participant Token as "令牌服务"
Client->>Controller : 发送登出请求(包含令牌)
Controller->>Token : 解析用户令牌
Token-->>Controller : 返回用户信息
Controller->>Token : 删除Redis中的令牌
Token-->>Controller : 删除结果
Controller-->>Client : 返回登出成功响应
```
**Diagram sources**
- [sysUser_v1_user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go#L1-L19)
- [user_token.go](file://utility/token/user_token.go#L1-L135)
### 会话清理
登出时的会话清理主要通过删除Redis缓存中的令牌来实现系统使用`DeleteTokenFromRedis`函数根据用户ID删除对应的令牌记录确保用户无法再使用旧的令牌进行认证
**Section sources**
- [sysUser_v1_user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go#L1-L19)
- [user_token.go](file://utility/token/user_token.go#L1-L135)
## 安全策略
### 令牌安全存储
系统采用多层安全措施保护令牌的安全
1. 使用HTTPS协议传输令牌防止中间人攻击
2. 令牌存储在Redis缓存中设置合理的过期时间
3. 使用强加密算法(HS256)对令牌进行签名
4. 敏感信息不存储在令牌中仅包含必要的用户标识
### 过期时间设置
令牌的过期时间通过配置文件进行管理系统支持灵活的过期策略
- 基础过期时间默认10天(可配置)
- 最大刷新时间默认5天(可配置)超过此时间后令牌不再自动刷新
- 令牌刷新机制在最大刷新时间和过期时间之间使用时自动刷新
### 防止令牌劫持
系统通过以下机制防止令牌劫持
1. 令牌绑定用户会话每次请求都验证令牌与用户的一致性
2. 支持令牌立即失效用户登出后旧令牌无法使用
3. 白名单机制限制敏感操作的访问路径
4. 请求头验证确保令牌来源的合法性
**Section sources**
- [models.go](file://utility/config/models.go#L1-L61)
- [user_token.go](file://utility/token/user_token.go#L1-L135)
- [auth.go](file://internal/middleware/auth.go#L1-L155)
## 性能优化
### 缓存策略
系统采用Redis作为令牌的缓存存储相比内存存储具有以下优势
- 支持分布式部署多实例间共享会话状态
- 数据持久化重启后会话状态不丢失
- 内置过期机制自动清理过期令牌
- 高性能读写满足高并发场景需求
### 并发处理
认证中间件设计考虑了高并发场景下的性能表现
- 无状态设计不依赖服务器本地存储
- 轻量级验证仅需一次Redis查询即可完成认证
- 支持异步刷新不影响主请求处理流程
- 白名单机制减少不必要的认证开销
### 资源管理
系统通过以下方式优化资源使用
- 合理设置令牌过期时间平衡安全性和用户体验
- 批量操作优化减少数据库查询次数
- 连接池管理有效利用数据库连接资源
- 日志分级避免过度日志影响性能
**Section sources**
- [user_token.go](file://utility/token/user_token.go#L1-L135)
- [auth.go](file://internal/middleware/auth.go#L1-L155)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L767)
## 总结
kami_backend的会话管理系统采用现代化的JWT认证机制结合Redis缓存实现了高效安全的用户会话管理系统具有以下特点
1. 安全性高采用标准JWT协议支持令牌刷新和立即失效
2. 性能优越基于Redis的缓存设计支持高并发访问
3. 灵活性好配置化的过期策略和白名单机制
4. 易于维护清晰的代码结构和模块化设计
该会话管理机制能够有效支持系统的安全需求为用户提供流畅的认证体验同时具备良好的扩展性和维护性

View File

@@ -0,0 +1,220 @@
# 双因素认证
<cite>
**本文档中引用的文件**
- [mfa.go](file://utility/mfa/mfa.go)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [sysUser_v1_totp_image_get.go](file://internal/controller/sysUser/sysUser_v1_totp_image_get.go)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sys_user.go](file://internal/service/sys_user.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档全面描述了kami_backend系统中基于时间的一次性密码TOTP双因素认证的实现机制文档涵盖TOTP密钥生成二维码展示验证码验证流程以及用户启用和禁用双因素认证的接口实现与安全考虑同时解释了MFA工具类的功能和集成方式包括TOTP验证过程中的时间同步和容错处理并提供双因素认证的安全最佳实践和用户操作指南
## 项目结构
kami_backend的双因素认证功能主要分布在`api/sysUser/v1``internal/controller/sysUser``utility/mfa`目录中`api`目录定义了TOTP相关的API接口`internal/controller/sysUser`实现了控制器逻辑`utility/mfa`提供了核心的MFA工具函数
```mermaid
graph TB
subgraph "API层"
A[totp.go]
end
subgraph "控制器层"
B[sysUser_v1_totp_set.go]
C[sysUser_v1_totp_image_get.go]
D[sysUser_v1_totp_status_get.go]
E[sysUser_v1_totp_reset.go]
end
subgraph "服务层"
F[sys_user.go]
end
subgraph "工具层"
G[mfa.go]
end
A --> B
A --> C
A --> D
A --> E
B --> F
C --> F
D --> F
E --> F
B --> G
C --> G
D --> G
E --> G
F --> G
```
**Diagram sources**
- [totp.go](file://api/sysUser/v1/totp.go)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [sysUser_v1_totp_image_get.go](file://internal/controller/sysUser/sysUser_v1_totp_image_get.go)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [mfa.go](file://utility/mfa/mfa.go)
**Section sources**
- [api/sysUser/v1](file://api/sysUser/v1)
- [internal/controller/sysUser](file://internal/controller/sysUser)
- [utility/mfa](file://utility/mfa)
## 核心组件
双因素认证的核心组件包括MFA工具类TOTP状态获取TOTP设置TOTP二维码获取和TOTP重置功能这些组件协同工作实现了完整的双因素认证流程
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [sysUser_v1_totp_image_get.go](file://internal/controller/sysUser/sysUser_v1_totp_image_get.go)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go)
## 架构概述
双因素认证的架构分为四层API层控制器层服务层和工具层API层定义了TOTP相关的接口控制器层处理业务逻辑服务层提供用户数据操作工具层实现TOTP的核心算法
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[工具层]
A --> |HTTP请求| B
B --> |调用| C
C --> |调用| D
D --> |返回| C
C --> |返回| B
B --> |响应| A
```
**Diagram sources**
- [totp.go](file://api/sysUser/v1/totp.go)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [mfa.go](file://utility/mfa/mfa.go)
## 详细组件分析
### MFA工具类分析
MFA工具类提供了TOTP密钥生成二维码生成和验证码验证的核心功能
```mermaid
classDiagram
class Otp {
+string Secret
+string QrImage
+string Key
}
class mfa {
+GetOtp(userId, username, key, secret) Otp
+ValidCode(code, secret) bool
}
mfa --> Otp : "返回"
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L10-L52)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
### TOTP设置流程分析
用户设置TOTP的流程包括验证密码和验证码然后保存TOTP密钥
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "TotpSet控制器"
participant Service as "SysUserService"
participant MFA as "MFA工具"
Client->>Controller : POST /user/totp/set
Controller->>Service : LoginOnlyLogin()
Service-->>Controller : 用户信息
Controller->>MFA : ValidCode(code, otpSecret)
MFA-->>Controller : 验证结果
alt 验证失败
Controller-->>Client : 验证码错误
else 验证成功
Controller->>Service : SetTotp()
Service-->>Controller : 成功
Controller-->>Client : 成功响应
end
```
**Diagram sources**
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L33)
- [sys_user.go](file://internal/service/sys_user.go#L100-L101)
**Section sources**
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L33)
### TOTP状态获取分析
获取TOTP状态的流程根据用户是否已启用TOTP返回不同信息
```mermaid
flowchart TD
Start([开始]) --> Auth["验证登录状态"]
Auth --> Check["检查OtpSecret是否为空"]
Check --> |为空| Generate["生成新OTP"]
Generate --> Return["返回二维码和密钥"]
Check --> |不为空| ReturnStatus["返回已启用状态"]
Return --> End([结束])
ReturnStatus --> End
```
**Diagram sources**
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L36)
**Section sources**
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L36)
## 依赖分析
双因素认证功能依赖于多个组件和外部库
```mermaid
graph TD
A[mfa.go] --> B[gotp]
A --> C[qrcode]
A --> D[grand]
B --> E[TOTP算法]
C --> F[二维码生成]
D --> G[随机字符串生成]
G1[sysUser控制器] --> A
G2[sys_user服务] --> A
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L33)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L33)
## 性能考虑
双因素认证的性能主要受二维码生成和TOTP验证算法的影响系统使用了高效的第三方库来处理这些计算密集型任务确保了良好的响应性能
## 故障排除指南
### 常见问题
1. **二维码无法扫描**检查生成的base64编码是否正确确保数据URI格式正确
2. **验证码验证失败**确认客户端和服务器时间同步检查TOTP时间窗口设置
3. **密钥生成失败**确保gotp库正确导入并可用
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L33)
## 结论
kami_backend的双因素认证系统通过分层架构实现了安全可靠的TOTP认证机制系统提供了完整的启用验证和重置功能结合了高效的第三方库来处理核心算法确保了良好的安全性和性能表现建议定期审查和更新MFA实现以应对不断变化的安全威胁

View File

@@ -0,0 +1,382 @@
# 用户认证管理
<cite>
**本文档引用的文件**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
- [v_1_sys_user.go](file://internal/model/entity/v_1_sys_user.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [base_user_info.go](file://internal/logic/base_user_info/user_info.go)
- [sys_auth.go](file://internal/logic/sys_auth/sysAuth.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录)如有必要
## 简介
本文档全面描述了kami_backend系统的用户认证管理机制包括用户登录登出会话管理双因素认证TOTP身份验证令牌的生成与验证登录日志记录和安全审计等核心功能文档详细阐述了系统如何通过JWT令牌Redis缓存和中间件实现安全的用户认证流程并提供了用户认证的最佳实践和常见问题的解决方案
## 项目结构
kami_backend的用户认证相关代码分布在多个目录中主要集中在`api``internal``utility`目录下认证逻辑主要由`internal/controller/sys_user_login``internal/controller/sysUser`控制器处理业务逻辑在`internal/logic/sys_user`中实现服务接口定义在`internal/service/sys_user.go`而工具函数则位于`utility/token``utility/mfa`包中
```mermaid
graph TD
subgraph "API层"
A[sys_user_login/v1/sys_user_login.go]
B[sysUser/v1/totp.go]
end
subgraph "控制器层"
C[sys_user_login/sys_user_login.go]
D[sysUser/sysUser.go]
end
subgraph "业务逻辑层"
E[sys_user/sys_user.go]
F[base_user_info/user_info.go]
G[sys_auth/sysAuth.go]
end
subgraph "服务层"
H[sys_user.go]
end
subgraph "数据访问层"
I[v_1_sys_user.go]
end
subgraph "工具层"
J[user_token.go]
K[mfa.go]
L[auth.go]
end
A --> C
B --> D
C --> E
D --> E
C --> F
D --> G
E --> H
F --> H
G --> H
H --> I
E --> J
E --> K
C --> L
D --> L
```
**图表来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [base_user_info.go](file://internal/logic/base_user_info/user_info.go)
- [sys_auth.go](file://internal/logic/sys_auth/sysAuth.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
**章节来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [base_user_info.go](file://internal/logic/base_user_info/user_info.go)
- [sys_auth.go](file://internal/logic/sys_auth/sysAuth.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
## 核心组件
用户认证系统的核心组件包括用户登录请求处理JWT令牌生成与验证双因素认证TOTP集成会话管理登录日志记录和权限验证中间件这些组件协同工作确保系统的安全性和可靠性
**章节来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
## 架构概述
kami_backend的用户认证架构采用分层设计从API接口到数据访问层每一层都有明确的职责认证流程始于API层的登录请求经过控制器层的处理调用业务逻辑层进行用户验证和令牌生成最终通过数据访问层与数据库交互
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Logic as "业务逻辑"
participant Service as "服务"
participant DAO as "数据访问"
participant DB as "数据库"
participant Redis as "Redis缓存"
Client->>API : 发送登录请求
API->>Controller : 调用UserLogin
Controller->>Logic : 验证验证码
Logic->>Logic : 验证用户名密码
alt 启用TOTP
Logic->>Logic : 验证TOTP验证码
end
Logic->>Service : 生成JWT令牌
Service->>Redis : 存储令牌
Service->>DB : 记录登录日志
Service-->>Controller : 返回令牌
Controller-->>API : 返回响应
API-->>Client : 返回登录结果
```
**图表来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [user_token.go](file://utility/token/user_token.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
## 详细组件分析
### 用户登录与认证分析
用户登录流程包括验证码验证用户名密码验证双因素认证如果启用和JWT令牌生成系统使用中间件进行请求认证确保只有经过验证的用户才能访问受保护的资源
#### 用户登录流程
```mermaid
flowchart TD
Start([开始]) --> ValidateCaptcha["验证验证码"]
ValidateCaptcha --> CaptchaValid{"验证码有效?"}
CaptchaValid --> |否| ReturnCaptchaError["返回验证码错误"]
CaptchaValid --> |是| ValidateCredentials["验证用户名密码"]
ValidateCredentials --> CredentialsValid{"凭证有效?"}
CredentialsValid --> |否| ReturnAuthError["返回认证错误"]
CredentialsValid --> |是| CheckTOTP["检查TOTP是否启用"]
CheckTOTP --> TOTPEnabled{"TOTP启用?"}
TOTPEnabled --> |否| GenerateToken["生成JWT令牌"]
TOTPEnabled --> |是| ValidateTOTP["验证TOTP验证码"]
ValidateTOTP --> TOTPValid{"TOTP有效?"}
TOTPValid --> |否| ReturnTOTPError["返回TOTP错误"]
TOTPValid --> |是| GenerateToken
GenerateToken --> StoreToken["存储令牌到Redis"]
StoreToken --> LogLogin["记录登录日志"]
LogLogin --> ReturnToken["返回令牌"]
ReturnCaptchaError --> End([结束])
ReturnAuthError --> End
ReturnTOTPError --> End
ReturnToken --> End
```
**图表来源**
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
**章节来源**
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
### 双因素认证TOTP分析
系统集成了基于时间的一次性密码TOTP作为双因素认证机制用户可以启用禁用和重置TOTP设置系统通过QR码提供配置信息
#### TOTP配置流程
```mermaid
classDiagram
class Otp {
+Secret string
+QrImage string
+Key string
}
class Mfa {
+GetOtp(userId, username, key, secret) Otp
+ValidCode(code, secret) bool
}
class TotpController {
-userService UserService
+TotpStatusGet(req) Res
+TotpSet(req) Res
+TotpImageGet(req) Res
+TotpReset(req) Res
}
class UserService {
+SetTotp(ctx, data, key, secret) error
+ResetTotp(ctx, data) error
}
Mfa --> Otp : "创建"
TotpController --> Mfa : "使用"
TotpController --> UserService : "调用"
UserService --> Mfa : "验证"
```
**图表来源**
- [mfa.go](file://utility/mfa/mfa.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
**章节来源**
- [mfa.go](file://utility/mfa/mfa.go)
- [totp.go](file://api/sysUser/v1/totp.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
### 会话管理分析
系统使用JWT令牌进行会话管理令牌存储在Redis中以实现分布式会话中间件负责验证令牌的有效性并在必要时进行令牌刷新
#### 会话管理流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Middleware as "认证中间件"
participant Token as "令牌服务"
participant Redis as "Redis"
Client->>Middleware : 发送请求
Middleware->>Token : 提取令牌
Token->>Redis : 检查令牌是否存在
Redis-->>Token : 返回检查结果
alt 令牌有效
Token->>Token : 验证JWT签名
Token->>Token : 检查过期时间
alt 需要刷新
Token->>Token : 生成新令牌
Token->>Redis : 存储新令牌
Token-->>Middleware : 返回刷新令牌
end
Middleware->>Client : 继续处理请求
else 令牌无效
Middleware->>Client : 返回未授权错误
end
```
**图表来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
**章节来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
## 依赖分析
用户认证系统涉及多个组件之间的依赖关系从API接口到数据访问层形成了一个完整的认证链条
```mermaid
graph TD
A[UserLoginReq] --> B[ControllerV1.UserLogin]
B --> C[service.Captcha.VerifyString]
B --> D[service.SysUser.GetAdminUserByUsernamePassword]
D --> E[service.SysUser.GetUserByUsername]
E --> F[dao.V1SysUser.Scan]
B --> G[mfa.ValidCode]
G --> H[gotp.NewDefaultTOTP]
B --> I[token.GenerateUserToken]
I --> J[token.genToken]
I --> K[cache.NewCache.Set]
L[LoginOrIframeAuth] --> M[whiteListAuth]
L --> N[loginAuth]
L --> O[iFrameAuth]
N --> P[token.ParseUserToken]
N --> Q[token.GetTokenFromRedis]
N --> R[token.RefreshUserToken]
S[ControllerV1.UserLoginOut] --> T[token.ParseUserToken]
S --> U[token.DeleteTokenFromRedis]
V[ControllerV1.TotpSet] --> W[service.SysAuth.LoginOnlyLogin]
V --> X[utils.EncryptPassword]
V --> Y[mfa.ValidCode]
V --> Z[service.SysUser.SetTotp]
Z --> AA[mfa.GetOtp]
Z --> AB[dao.V1SysUser.Update]
```
**图表来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
**章节来源**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
## 性能考虑
用户认证系统的性能主要受以下几个因素影响
1. **数据库查询性能**用户信息查询和登录日志记录需要优化数据库索引
2. **Redis缓存性能**令牌的存储和检索依赖Redis的性能需要确保Redis集群的高可用性
3. **密码哈希计算**密码加密使用双重MD5哈希虽然安全但计算成本较高
4. **JWT签名验证**每次请求都需要验证JWT签名增加了CPU开销
建议的优化措施包括
- 为用户表的用户名字段创建唯一索引
- 使用连接池管理数据库连接
- 监控Redis的内存使用和响应时间
- 考虑使用更高效的密码哈希算法如bcrypt
## 故障排除指南
### 常见认证问题及解决方案
1. **登录失败**
- 检查用户名和密码是否正确
- 确认用户账户状态是否正常未被禁用
- 如果启用了TOTP确保输入了正确的验证码
2. **令牌失效**
- 检查令牌是否过期
- 确认Redis中是否存在对应的令牌
- 检查时钟同步TOTP对时间敏感
3. **TOTP配置问题**
- 确保手机时间与服务器时间同步
- 重新生成QR码并重新扫描
- 检查密钥是否正确复制
4. **会话中断**
- 检查Redis连接是否正常
- 确认令牌刷新逻辑是否正常工作
- 查看系统日志中的错误信息
**章节来源**
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login.go)
- [user_token.go](file://utility/token/user_token.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
## 结论
kami_backend的用户认证管理系统设计完善采用了现代的安全实践包括JWT令牌Redis会话存储和双因素认证系统架构清晰各组件职责明确便于维护和扩展通过遵循本文档中的最佳实践可以确保系统的安全性和可靠性
## 附录
### API端点列表
| 端点 | 方法 | 描述 |
|------|------|------|
| /api/user/login | POST | 用户登录 |
| /api/user/logout | POST | 用户登出 |
| /api/user/totp/status | GET | 获取TOTP状态 |
| /api/user/totp/set | POST | 设置TOTP |
| /api/user/totp/image | GET | 获取TOTP图像 |
| /api/user/totp/reset | POST | 重置TOTP |
### 配置选项
| 配置项 | 描述 | 默认值 |
|-------|------|-------|
| token.timeout | 令牌超时时间 | 3600 |
| token.maxRefresh | 最大刷新时间 | 1800 |
| token.cacheModel | 缓存模型memory/redis | redis |
| token.cacheKey | 缓存键前缀 | kami_token |

View File

@@ -0,0 +1,295 @@
# 登录认证
<cite>
**本文档引用文件**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [sysAuth.go](file://internal/logic/sys_auth/sysAuth.go)
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [rate.go](file://utility/limiter/rate.go)
- [auth.go](file://internal/middleware/auth.go)
</cite>
## 目录
1. [简介](#简介)
2. [登录接口实现流程](#登录接口实现流程)
3. [密码加密存储机制](#密码加密存储机制)
4. [认证失败处理策略](#认证失败处理策略)
5. [参数验证与安全校验](#参数验证与安全校验)
6. [错误响应码设计](#错误响应码设计)
7. [安全防护措施](#安全防护措施)
8. [使用示例与集成指南](#使用示例与集成指南)
9. [常见问题诊断](#常见问题诊断)
## 简介
本文档详细解析kami_backend系统的用户登录认证机制系统采用多层安全验证机制包括用户名密码验证验证码校验TOTP双因素认证以及基于AES-CBC和MD5的加密算法保护用户凭证安全同时系统实现了基于内存和Redis的限流机制有效防止暴力破解攻击
**Section sources**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go#L1-L18)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
## 登录接口实现流程
用户登录接口通过多步骤验证确保安全性首先验证图形验证码然后查询用户信息并验证密码接着检查双因素认证状态最后生成访问令牌
```mermaid
sequenceDiagram
participant 客户端 as 客户端
participant 控制器 as sys_user_login控制器
participant 服务层 as SysUserService
participant 验证码服务 as CaptchaService
participant 令牌服务 as TokenService
客户端->>控制器 : POST /user/login (用户名,密码,验证码)
控制器->>验证码服务 : 验证验证码(VerifyKey,VerifyCode)
验证码服务-->>控制器 : 验证结果
alt 验证失败
控制器->>客户端 : 返回验证码错误
else 验证成功
控制器->>服务层 : 查询用户(用户名,密码)
服务层-->>控制器 : 用户信息
alt 用户不存在或密码错误
控制器->>客户端 : 返回用户名或密码错误
else 用户存在且密码正确
控制器->>控制器 : 检查TOTP状态
alt 需要TOTP验证
控制器->>控制器 : 验证TOTP码
alt TOTP验证失败
控制器->>客户端 : 返回二步验证错误
else TOTP验证成功
控制器->>令牌服务 : 生成用户令牌
令牌服务-->>控制器 : 令牌字符串
控制器->>客户端 : 返回令牌
end
else 不需要TOTP验证
控制器->>令牌服务 : 生成用户令牌
令牌服务-->>控制器 : 令牌字符串
控制器->>客户端 : 返回令牌
end
end
end
```
**Diagram sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
## 密码加密存储机制
系统采用MD5哈希算法对用户密码进行加密存储在密码验证过程中使用MD5算法对输入密码进行哈希处理然后与数据库中存储的哈希值进行比对
```mermaid
flowchart TD
A[用户输入密码] --> B[MD5哈希处理]
B --> C[生成32位小写十六进制字符串]
C --> D[与数据库存储的哈希值比对]
D --> E{比对结果}
E --> |匹配| F[密码验证成功]
E --> |不匹配| G[密码验证失败]
```
**Diagram sources**
- [md5.go](file://utility/verify/md5.go#L1-L30)
**Section sources**
- [md5.go](file://utility/verify/md5.go#L1-L30)
## 认证失败处理策略
系统对认证失败情况进行了分类处理每种情况返回特定的错误码和消息便于前端进行针对性处理
```mermaid
flowchart TD
A[认证失败] --> B{失败类型}
B --> |验证码错误| C[返回CodeNotAuthorized]
B --> |用户名或密码错误| D[返回ErrLoginPasswordOrUserError]
B --> |TOTP验证错误| E[返回CodeValidationFailed]
B --> |用户被禁用| F[返回CodeNotAuthorized]
B --> |生成令牌失败| G[返回CodeInternalError]
C --> H[提示: 验证码错误]
D --> I[提示: 用户名或密码错误]
E --> J[提示: 二步验证错误]
F --> K[提示: 用户已禁用]
G --> L[提示: 系统内部错误]
```
**Diagram sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
## 参数验证与安全校验
登录接口对所有输入参数进行严格验证确保数据完整性和安全性
### 请求参数验证
| 参数名 | 类型 | 必填 | 验证规则 | 错误提示 |
|-------|------|------|---------|---------|
| username | 字符串 | | 非空 | 用户名不能为空 |
| password | 字符串 | | 非空 | 密码不能为空 |
| verifyCode | 字符串 | | 非空 | 验证码不能为空 |
| verifyKey | 字符串 | | 非空 | 验证秘钥不能为空 |
| totpCode | 字符串 | | - | - |
### 安全校验流程
```mermaid
flowchart TD
A[接收登录请求] --> B[验证参数完整性]
B --> C[校验验证码]
C --> D[查询用户信息]
D --> E[验证密码]
E --> F[检查用户状态]
F --> G[验证TOTP(如启用)]
G --> H[生成访问令牌]
H --> I[返回成功响应]
C --> |验证码错误| J[返回错误响应]
D --> |用户不存在| J
E --> |密码错误| J
F --> |用户被禁用| J
G --> |TOTP错误| J
H --> |生成失败| J
```
**Diagram sources**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go#L1-L18)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
**Section sources**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go#L1-L18)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
## 错误响应码设计
系统采用标准化的错误响应码体系便于客户端进行错误处理
| 错误码 | HTTP状态码 | 错误类型 | 说明 |
|-------|-----------|---------|------|
| 401 | 401 | 认证失败 | 验证码错误或用户被禁用 |
| 400 | 400 | 输入验证失败 | 用户名或密码错误 |
| 400 | 400 | 验证失败 | TOTP二步验证错误 |
| 500 | 500 | 内部错误 | 生成令牌失败 |
| 401 | 401 | 令牌错误 | 令牌失效或格式错误 |
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
- [auth.go](file://internal/middleware/auth.go#L117-L153)
## 安全防护措施
系统实现了多层次的安全防护机制包括加密算法和限流策略
### 加密算法应用
系统使用AES-CBC模式进行数据加密传输确保敏感信息在传输过程中的安全性
```mermaid
classDiagram
class AesCBCUtil {
+aesCBCEncrypt(plaintext, key, iv) byte[]
+aesCBCDecrypt(ciphertext, key, iv) byte[]
+AesCBCEncryptWithBase64(text, key, iv) string
+AesCBCStdDecryptWithBase64(text, key, iv) byte[]
+AesCBCURLDecryptWithBase64(text, key, iv) byte[]
-paddingPKCS7(plaintext, blockSize) byte[]
-unPaddingPKCS7(s) byte[]
}
class Md5Util {
+GetMD5LOWER(s) string
+GetMD5Upper(s) string
+MapToString(m) string
}
AesCBCUtil --> Md5Util : "使用"
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L1-L90)
- [md5.go](file://utility/verify/md5.go#L1-L30)
### 限流机制
系统实现了基于内存的简单限流器防止暴力破解攻击
```mermaid
flowchart TD
A[接收请求] --> B[生成限流键]
B --> C[检查当前请求数]
C --> D{超过阈值?}
D --> |是| E[拒绝请求]
D --> |否| F[记录请求时间]
F --> G[允许请求]
C --> H[清理过期记录]
H --> C
classDef default fill:#f9f,stroke:#333,stroke-width:1px;
class A,B,C,D,E,F,G,H default;
```
**Diagram sources**
- [rate.go](file://utility/limiter/rate.go#L1-L70)
**Section sources**
- [rate.go](file://utility/limiter/rate.go#L1-L70)
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L1-L90)
- [md5.go](file://utility/verify/md5.go#L1-L30)
## 使用示例与集成指南
### 登录请求示例
```json
POST /user/login
Content-Type: application/json
{
"username": "admin",
"password": "password123",
"verifyCode": "abcd",
"verifyKey": "captcha_123456",
"totpCode": "123456"
}
```
### 成功响应
```json
{
"code": 0,
"message": "OK",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
### 集成注意事项
1. 必须先获取验证码并传递verifyKey
2. 生产环境必须启用TOTP双因素认证
3. 令牌需要在后续请求的Authorization头中传递
4. 实现自动刷新令牌机制以应对令牌过期
**Section sources**
- [sys_user_login.go](file://api/sys_user_login/v1/sys_user_login.go#L1-L18)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
## 常见问题诊断
### 常见问题及解决方案
| 问题现象 | 可能原因 | 解决方案 |
|--------|---------|---------|
| 验证码错误 | 验证码过期或输入错误 | 刷新验证码重新输入 |
| 用户名或密码错误 | 凭证不匹配或用户不存在 | 检查用户名密码确认用户状态 |
| 二步验证错误 | TOTP码错误或未同步 | 检查TOTP应用时间同步 |
| 用户已禁用 | 账户被管理员禁用 | 联系管理员启用账户 |
| 生成令牌失败 | 系统内部错误 | 检查服务状态重试登录 |
### 诊断流程
```mermaid
flowchart TD
A[登录失败] --> B{错误类型}
B --> |验证码错误| C[检查验证码有效期]
B --> |用户名密码错误| D[确认用户状态和凭证]
B --> |TOTP错误| E[检查TOTP应用和时间同步]
B --> |用户禁用| F[联系管理员]
B --> |内部错误| G[检查服务日志]
C --> H[重新获取验证码]
D --> I[重置密码或创建用户]
E --> J[重新配置TOTP]
F --> K[等待管理员处理]
G --> L[重启服务或联系技术支持]
```
**Diagram sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)

View File

@@ -0,0 +1,382 @@
# 系统认证逻辑
<cite>
**本文档引用的文件**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [auth.go](file://internal/middleware/auth.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [sys_role.go](file://internal/service/sys_role.go)
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go)
- [sysUser.go](file://internal/model/sys_user.go)
- [sys_role.go](file://internal/model/sys_role.go)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go)
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [sysUser.go](file://internal/controller/sysUser/sysUser.go)
- [user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go)
- [totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go)
</cite>
## 目录
1. [引言](#引言)
2. [RBAC权限控制系统](#rbac权限控制系统)
3. [TOTP双因素认证](#totp双因素认证)
4. [用户登录与会话管理](#用户登录与会话管理)
5. [权限验证中间件](#权限验证中间件)
6. [权限配置最佳实践](#权限配置最佳实践)
7. [安全审计建议](#安全审计建议)
8. [结论](#结论)
## 引言
kami_backend系统采用基于Casbin的RBAC基于角色的访问控制权限模型结合TOTP双因素认证机制构建了完整的系统认证体系该系统实现了用户角色权限规则和菜单权限的精细化管理确保了系统的安全性和可扩展性本文档详细阐述了认证业务逻辑的实现细节包括权限控制双因素认证会话管理等核心功能
## RBAC权限控制系统
kami_backend系统采用Casbin作为权限控制引擎实现了基于角色的访问控制RBAC模型该系统通过定义用户角色和权限之间的关系实现了灵活的权限管理机制
### RBAC模型配置
系统使用`rbac_model.conf`文件定义了RBAC模型的核心规则
```mermaid
classDiagram
class CasbinModel {
+request_definition : r = sub, obj, act
+policy_definition : p = sub, obj, act
+role_definition : g = _, _
+policy_effect : e = some(where (p.eft == allow))
+matchers : m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
}
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L13)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L13)
### 用户角色管理
系统通过`ISysRole`接口提供角色管理功能包括角色的创建编辑删除和权限分配角色与用户通过Casbin的分组策略Grouping Policy进行关联
```mermaid
classDiagram
class ISysRole {
+GetRoleListSearch(ctx, req) res, err
+GetRoleList(ctx) list, err
+AddRoleRule(ctx, ruleIds, roleId) err
+DelRoleRule(ctx, roleId) err
+AddRole(ctx, req) err
+Get(ctx, id) res, err
+GetFilteredNamedPolicy(ctx, id) gpSlice, err
+EditRole(ctx, req) err
+DeleteByIds(ctx, ids) err
}
```
**Diagram sources**
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
**Section sources**
- [sys_role.go](file://internal/service/sys_role.go#L14-L30)
- [sys_role.go](file://internal/model/sys_role.go#L1-L20)
### 权限规则与菜单管理
系统通过`ISysAuthRule`接口管理权限规则和菜单结构权限规则分为目录菜单和按钮三种类型通过树形结构组织
```mermaid
classDiagram
class ISysAuthRule {
+GetMenuListSearch(ctx, req) res, err
+GetIsMenuList(ctx) list, err
+GetMenuList(ctx) list, err
+GetIsButtonList(ctx) list, err
+Add(ctx, req) err
+BindRoleRule(ctx, ruleId, roleIds) err
+Get(ctx, id) rule, err
+GetMenuRoles(ctx, id) roleIds, err
+Update(ctx, req) err
+UpdateRoleRule(ctx, ruleId, roleIds) err
+GetMenuListTree(pid, list) tree
+DeleteMenuByIds(ctx, ids) err
+FindSonByParentId(list, pid) children
}
class SysAuthRule {
+CommonIntId
+Name string
+Title string
+MenuType uint
+Weigh int
+IsHide uint
+Path string
+IdAdmin int
+Component string
+Children []*SysAuthRule
}
ISysAuthRule --> SysAuthRule : "使用"
```
**Diagram sources**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L10)
**Section sources**
- [sys_auth_rule.go](file://internal/service/sys_auth_rule.go#L14-L34)
- [sys_auth_rule.go](file://internal/model/sys_auth_rule.go#L7-L40)
### 权限验证流程
当用户请求访问系统资源时权限验证流程如下
```mermaid
sequenceDiagram
participant User as "用户"
participant Middleware as "权限中间件"
participant Casbin as "Casbin引擎"
participant Database as "数据库"
User->>Middleware : 发起请求
Middleware->>Casbin : 获取用户角色
Casbin->>Database : 查询用户角色关联
Database-->>Casbin : 返回角色ID列表
Casbin->>Database : 查询角色权限规则
Database-->>Casbin : 返回权限规则
Casbin->>Middleware : 验证权限
Middleware->>User : 返回访问结果
Note over Middleware,Casbin : 基于Casbin的RBAC权限验证
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L766)
## TOTP双因素认证
系统集成了TOTP基于时间的一次性密码双因素认证机制增强了账户安全性TOTP实现基于HOTPHMAC-based One-time Password算法使用SHA-1哈希函数生成一次性密码
### TOTP实现原理
系统使用`gotp`库实现TOTP功能生成6位数字的一次性密码每30秒更新一次
```mermaid
classDiagram
class Otp {
+Secret string
+QrImage string
+Key string
}
class Mfa {
+GetOtp(userId, username, key, secret) otp, err
+ValidCode(code, secret) bool
}
Mfa --> Otp : "生成"
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
### TOTP流程
TOTP双因素认证的完整流程包括密钥生成二维码展示验证和重置
```mermaid
sequenceDiagram
participant User as "用户"
participant System as "系统"
participant Mfa as "MFA模块"
User->>System : 请求启用TOTP
System->>Mfa : 生成TOTP密钥
Mfa->>System : 返回密钥和二维码
System->>User : 展示二维码
User->>System : 扫描二维码并输入验证码
System->>Mfa : 验证验证码
Mfa->>System : 返回验证结果
System->>User : 启用/禁用TOTP
Note over System,Mfa : TOTP双因素认证流程
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L52)
- [totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L32)
- [totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go#L1-L26)
## 用户登录与会话管理
系统实现了完整的用户登录登出和会话管理机制确保用户会话的安全性和可靠性
### 登录流程
用户登录流程包括验证码验证身份认证和Token生成
```mermaid
sequenceDiagram
participant User as "用户"
participant Controller as "登录控制器"
participant Service as "用户服务"
participant Token as "Token服务"
User->>Controller : 提交登录请求
Controller->>Service : 验证验证码
Service->>Service : 验证用户名密码
Service->>Service : 验证TOTP(如果启用)
Service->>Token : 生成用户Token
Token->>Controller : 返回Token
Controller->>User : 返回登录结果
Note over Controller,Service : 用户登录流程
```
**Diagram sources**
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L766)
**Section sources**
- [sys_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L50)
### 会话管理
系统使用JWT Token进行会话管理Token存储在Redis中支持自动续签和强制失效
```mermaid
classDiagram
class UserToken {
+UserID string
+ID string
+Username string
+ExpireTime int64
}
class TokenService {
+GenerateUserToken(ctx, username, userId) tokenStr, err
+ParseUserToken(ctx, tokenStr) userToken, err
+RefreshUserToken(ctx, userToken) newToken, err
+GetTokenFromRedis(ctx, userId, tokenId) tokenStr, err
+DeleteTokenFromRedis(ctx, userId) err
}
TokenService --> UserToken : "使用"
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [sys_user.go](file://internal/logic/sys_user/sys_user.go#L1-L766)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
### 登出流程
用户登出时系统会从Redis中删除对应的Token使会话立即失效
```mermaid
sequenceDiagram
participant User as "用户"
participant Controller as "登出控制器"
participant Token as "Token服务"
User->>Controller : 发起登出请求
Controller->>Token : 解析Token
Token->>Controller : 返回用户信息
Controller->>Token : 删除Redis中的Token
Token->>Controller : 返回删除结果
Controller->>User : 返回登出成功
Note over Controller,Token : 用户登出流程
```
**Diagram sources**
- [user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go#L1-L18)
**Section sources**
- [user_login_out.go](file://internal/controller/sysUser/sysUser_v1_user_login_out.go#L1-L18)
## 权限验证中间件
系统通过中间件机制实现权限验证支持多种认证方式和白名单机制
### 中间件架构
权限验证中间件采用分层设计支持登录认证iframe认证和白名单认证
```mermaid
classDiagram
class AuthMiddleware {
+LoginOrIframeAuth(r)
+loginAuth(r) code
+iFrameAuth(r) code
+whiteListAuth(r) code
}
class TokenService {
+GetRequestToken(r) tokenStr
+ParseUserToken(ctx, tokenStr) userToken, err
+RefreshUserToken(ctx, userToken) newToken, err
}
class ConfigService {
+NewConfig(ctx) cfg, err
+GetFrontendSecret() frontendModel, err
}
class VerifyService {
+AesCBCURLDecryptWithBase64(tokenStr, key, iv) tokenByte, err
}
AuthMiddleware --> TokenService : "使用"
AuthMiddleware --> ConfigService : "使用"
AuthMiddleware --> VerifyService : "使用"
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
### 认证流程
权限验证中间件的执行流程如下
```mermaid
flowchart TD
Start([请求进入]) --> CheckWhiteList["检查白名单"]
CheckWhiteList --> IsWhiteList{"是否在白名单?"}
IsWhiteList --> |是| AllowAccess["允许访问"]
IsWhiteList --> |否| GetTokenFrom["获取Token来源"]
GetTokenFrom --> IsLogin{"来源为login?"}
IsLogin --> |是| LoginAuth["执行登录认证"]
IsLogin --> |否| IsIframe{"来源为iframe?"}
IsIframe --> |是| IFrameAuth["执行Iframe认证"]
IsIframe --> |否| ReturnError["返回来源不明错误"]
LoginAuth --> AuthResult{"认证成功?"}
IFrameAuth --> AuthResult
AuthResult --> |是| AllowAccess
AuthResult --> |否| ReturnAuthError["返回认证错误"]
AllowAccess --> End([继续处理])
ReturnAuthError --> End
ReturnError --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
## 权限配置最佳实践
### 角色设计原则
1. **最小权限原则**每个角色只分配完成其职责所需的最小权限
2. **职责分离**敏感操作应由不同角色共同完成避免权限过度集中
3. **层级化设计**建立角色层级结构便于权限继承和管理
### 权限规则配置
1. **细粒度控制**将权限细化到具体操作级别如创建读取更新删除
2. **命名规范**使用统一的命名规范`资源名/操作类型`
3. **定期审查**定期审查权限配置移除不再需要的权限
### 菜单管理
1. **动态加载**根据用户角色动态加载菜单避免信息泄露
2. **权限同步**菜单显示与后端权限验证保持同步
3. **用户体验**合理组织菜单结构提升用户体验
## 安全审计建议
### 认证安全
1. **密码策略**实施强密码策略包括长度复杂度和定期更换要求
2. **失败处理**对连续登录失败实施账户锁定或延迟机制
3. **会话保护**使用安全的Cookie属性HttpOnlySecure保护会话
### TOTP安全
1. **密钥保护**确保TOTP密钥在传输和存储过程中的安全性
2. **备份机制**提供恢复码或备用验证方式防止用户丢失设备
3. **防暴力破解**对TOTP验证尝试实施速率限制
### 权限审计
1. **操作日志**记录所有权限相关的操作包括角色分配权限变更等
2. **定期审查**定期审查用户权限分配确保符合最小权限原则
3. **异常检测**监控异常的权限使用模式及时发现潜在安全威胁
## 结论
kami_backend系统的认证业务逻辑通过RBAC权限控制TOTP双因素认证和会话管理机制构建了安全可靠的认证体系系统采用模块化设计各组件职责清晰便于维护和扩展通过遵循权限配置最佳实践和安全审计建议可以进一步提升系统的安全性和可靠性

View File

@@ -0,0 +1,279 @@
# Apple订单处理
<cite>
**本文档引用的文件**
- [order.go](file://api/card_info_apple/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [order.go](file://internal/logic/card_apple_order/order.go)
- [callback.go](file://internal/logic/card_apple_order/callback.go)
- [status.go](file://internal/logic/card_apple_order/status.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
- [card_apple.go](file://internal/consts/card_apple.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了Apple卡密订单处理系统的实现机制涵盖订单创建状态管理iTunes回调处理历史记录查询等核心功能系统通过严格的订单状态机管理充值流程确保交易的完整性和一致性文档深入分析了订单与Apple账户的关联机制充值金额验证流程幂等性保证和事务管理策略为开发者提供全面的技术参考
## 项目结构
Apple卡密订单处理功能主要分布在`api/card_info_apple``internal`目录下采用分层架构设计包含API接口业务逻辑数据访问等层次
```mermaid
graph TD
subgraph "API层"
A[api/card_info_apple/v1/order.go]
B[api/card_info_apple/v1/order_history.go]
C[api/card_info_apple/v1/config.go]
end
subgraph "控制器层"
D[internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go]
E[internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go]
F[internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go]
end
subgraph "服务层"
G[internal/service/card_apple_order.go]
end
subgraph "逻辑层"
H[internal/logic/card_apple_order/order.go]
I[internal/logic/card_apple_order/callback.go]
J[internal/logic/card_apple_order/status.go]
end
subgraph "数据访问层"
K[internal/dao/v_1_card_apple_recharge_info.go]
end
subgraph "模型层"
L[internal/model/card_apple_order.go]
end
A --> D
B --> D
C --> D
D --> G
E --> G
F --> G
G --> H
G --> I
G --> J
H --> K
I --> K
J --> K
H --> L
I --> L
J --> L
```
**图示来源**
- [order.go](file://api/card_info_apple/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [order.go](file://internal/logic/card_apple_order/order.go)
- [callback.go](file://internal/logic/card_apple_order/callback.go)
- [status.go](file://internal/logic/card_apple_order/status.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
**本节来源**
- [order.go](file://api/card_info_apple/v1/order.go)
- [order_history.go](file://api/card_info_apple/v1/order_history.go)
- [config.go](file://api/card_info_apple/v1/config.go)
## 核心组件
Apple卡密订单处理系统的核心组件包括订单提交处理器iTunes回调处理器订单状态管理器和充值历史查询服务这些组件协同工作确保订单从创建到完成的整个生命周期得到正确处理
**本节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [card_info_apple_v1_recharge_handler.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_handler.go)
- [card_info_apple_v1_recharge_history_list.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_history_list.go)
## 架构概览
系统采用典型的分层架构从API接口到数据存储各层职责分明API层定义了订单相关的REST接口控制器层处理HTTP请求并调用服务层服务层协调业务逻辑层完成具体操作最终由数据访问层与数据库交互
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "逻辑层"
participant DAO as "数据访问层"
participant DB as "数据库"
Client->>API : 提交充值订单
API->>Controller : 转发请求
Controller->>Service : 调用充值服务
Service->>Logic : 执行订单创建逻辑
Logic->>DAO : 检查订单幂等性
DAO->>DB : 查询订单是否存在
DB-->>DAO : 返回查询结果
DAO-->>Logic : 返回检查结果
Logic->>DAO : 创建新订单
DAO->>DB : 插入订单记录
DB-->>DAO : 返回插入结果
DAO-->>Logic : 返回创建结果
Logic-->>Service : 返回订单信息
Service-->>Controller : 返回处理结果
Controller-->>API : 返回响应
API-->>Client : 返回订单创建结果
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [order.go](file://internal/logic/card_apple_order/order.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
## 详细组件分析
### 订单创建分析
订单创建组件负责处理用户提交的Apple卡密充值请求验证输入参数检查订单幂等性并创建新的订单记录
```mermaid
flowchart TD
Start([开始]) --> ValidateInput["验证输入参数"]
ValidateInput --> CheckIdempotency["检查订单幂等性"]
CheckIdempotency --> OrderExists{"订单已存在?"}
OrderExists --> |是| ReturnExisting["返回现有订单"]
OrderExists --> |否| CreateOrder["创建新订单"]
CreateOrder --> SetStatus["设置初始状态为待处理"]
SetStatus --> SaveOrder["保存订单到数据库"]
SaveOrder --> Notify["触发后续处理流程"]
Notify --> End([结束])
```
**图示来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [order.go](file://internal/logic/card_apple_order/order.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
**本节来源**
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [order.go](file://internal/logic/card_apple_order/order.go)
### 回调处理分析
iTunes回调处理组件负责接收Apple服务器的充值结果通知验证回调数据的完整性更新订单状态并触发相应的业务逻辑
```mermaid
sequenceDiagram
participant Apple as "Apple服务器"
participant Callback as "回调接口"
participant Validator as "验证器"
participant Status as "状态管理器"
participant Notifier as "通知服务"
Apple->>Callback : 发送充值结果回调
Callback->>Validator : 验证回调签名
Validator-->>Callback : 验证结果
alt 验证成功
Callback->>Status : 更新订单状态
Status->>Status : 状态转换逻辑
Status-->>Callback : 状态更新结果
Callback->>Notifier : 触发通知
Notifier-->>Callback : 通知结果
Callback-->>Apple : 返回成功响应
else 验证失败
Callback-->>Apple : 返回失败响应
end
```
**图示来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [callback.go](file://internal/logic/card_apple_order/callback.go)
- [status.go](file://internal/logic/card_apple_order/status.go)
**本节来源**
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
- [callback.go](file://internal/logic/card_apple_order/callback.go)
### 状态机分析
订单状态机管理组件定义了订单的生命周期包括待处理处理中成功失败等状态的转换规则和触发条件
```mermaid
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中 : 开始处理
处理中 --> 成功 : 充值成功
处理中 --> 失败 : 充值失败
处理中 --> 超时 : 处理超时
成功 --> [*]
失败 --> [*]
超时 --> [*]
note right of 处理中
包含子状态 :
- 验证卡密
- 调用Apple API
- 等待回调
end note
```
**图示来源**
- [status.go](file://internal/logic/card_apple_order/status.go)
- [card_apple.go](file://internal/consts/card_apple.go)
**本节来源**
- [status.go](file://internal/logic/card_apple_order/status.go)
- [card_apple.go](file://internal/consts/card_apple.go)
## 依赖分析
Apple卡密订单处理系统依赖于多个内部组件和外部服务形成了复杂的依赖关系网络
```mermaid
graph LR
A[订单提交] --> B[幂等性检查]
A --> C[参数验证]
A --> D[订单创建]
D --> E[数据库]
F[iTunes回调] --> G[签名验证]
F --> H[状态更新]
H --> E
I[历史查询] --> J[数据库查询]
J --> E
K[配置管理] --> L[系统配置]
A --> K
F --> K
style E fill:#f9f,stroke:#333
style K fill:#bbf,stroke:#333
```
**图示来源**
- [go.mod](file://go.mod)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
**本节来源**
- [go.mod](file://go.mod)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
## 性能考虑
为确保系统在高并发场景下的稳定性和响应速度采用了多种性能优化策略通过Redis缓存频繁访问的配置数据和订单状态减少数据库查询压力使用连接池管理数据库连接提高资源利用率对关键路径进行异步处理避免阻塞主线程同时通过合理的索引设计和查询优化确保数据库操作的高效性
## 故障排除指南
### 重复订单处理
当系统检测到重复订单时会根据幂等性原则返回已有订单信息而非创建新订单检查`v_1_card_apple_recharge_info`表中的订单记录确认订单的唯一标识符是否正确生成
**本节来源**
- [order.go](file://internal/logic/card_apple_order/order.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/v_1_card_apple_recharge_info.go)
### 回调验证失败
回调验证失败通常由签名不匹配或时间戳过期引起检查系统时间是否同步验证Apple提供的公钥是否正确配置确认回调数据的完整性
**本节来源**
- [callback.go](file://internal/logic/card_apple_order/callback.go)
- [card_info_apple_v1_recharge_itunes_callback.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_itunes_callback.go)
## 结论
Apple卡密订单处理系统通过分层架构设计和严格的流程控制实现了高可靠性的充值服务系统具备完善的订单状态管理幂等性保证和错误处理机制能够有效应对各种异常情况通过持续的性能优化和监控确保了服务的稳定性和响应速度为用户提供流畅的充值体验

View File

@@ -0,0 +1,246 @@
# 京东兑换订单处理
<cite>
**本文档引用的文件**
- [consume.go](file://internal/logic/card_redeem_order/consume.go)
- [process.go](file://internal/logic/card_redeem_order/process.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
</cite>
## 目录
1. [简介](#简介)
2. [订单创建与处理流程](#订单创建与处理流程)
3. [回调验证与状态更新](#回调验证与状态更新)
4. [订单与京东账户关联机制](#订单与京东账户关联机制)
5. [兑换码消费逻辑](#兑换码消费逻辑)
6. [幂等性保证](#幂等性保证)
7. [异常处理与重试机制](#异常处理与重试机制)
8. [订单历史记录与统计](#订单历史记录与统计)
9. [性能优化建议](#性能优化建议)
10. [常见问题解决方案](#常见问题解决方案)
## 简介
本文档详细描述了京东卡密兑换订单的完整处理流程包括订单创建消费处理回调验证和状态更新等核心环节系统通过核销订单服务处理京东卡密兑换请求确保订单处理的可靠性与一致性文档涵盖了订单与京东账户的关联机制兑换码消费逻辑以及关键的幂等性保证措施同时详细说明了异常处理策略重试机制订单历史记录和统计功能为系统维护和问题排查提供全面指导
## 订单创建与处理流程
京东兑换订单的创建与处理遵循严格的流程控制当用户提交兑换请求时系统首先验证订单信息的完整性与合法性订单创建后状态被设置为"待处理"RedeemOrderPending并记录在订单历史中系统通过定时触发器定期扫描待处理订单队列一旦发现符合条件的订单即启动处理流程
订单处理的核心是`ConsumeOne`方法该方法在分布式锁的保护下执行确保同一时间只有一个实例处理特定类别的订单处理流程首先调用`GetEarlyWaitingOrder`从数据库中获取最早等待核销的订单然后通过`StartProcessOrder`方法将订单状态更新为"开始处理"RedeemOrderStart并记录操作历史此过程采用数据库事务保证原子性防止订单被重复处理
```mermaid
flowchart TD
Start([订单创建]) --> ValidateInput["验证订单信息"]
ValidateInput --> InputValid{"信息有效?"}
InputValid --> |否| ReturnError["返回错误"]
InputValid --> |是| CreateOrder["创建订单<br/>状态: 待处理"]
CreateOrder --> Trigger["触发器扫描订单"]
Trigger --> FindOrder["查找待处理订单"]
FindOrder --> HasOrder{"存在订单?"}
HasOrder --> |否| End1([等待新订单])
HasOrder --> |是| StartProcess["开始处理订单"]
StartProcess --> UpdateStatus["更新状态: 开始处理"]
UpdateStatus --> AllocateAccount["分配京东账户"]
AllocateAccount --> Consume["消费卡密"]
Consume --> Callback["回调验证"]
Callback --> UpdateFinalStatus["更新最终状态"]
UpdateFinalStatus --> End2([处理完成])
```
**图示来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
- [process.go](file://internal/logic/card_redeem_order/process.go#L25-L64)
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
- [process.go](file://internal/logic/card_redeem_order/process.go#L25-L64)
## 回调验证与状态更新
回调验证是确保订单处理结果准确性的关键环节系统通过`ProcessOrderCallback`方法处理各种状态的回调该方法根据不同的状态码更新订单的最终状态并记录详细的操作历史当兑换成功时订单状态更新为"充值成功"RedeemOrderSuccess当出现错误时根据错误类型设置相应的失败状态
状态更新过程严格遵循预定义的状态转换规则例如当收到"账号失效"RedeemOrderFailWithCKFail状态时系统不仅将订单状态设置为"待处理"以便重试还会将关联的京东账户标记为"禁用"防止后续订单继续使用该失效账户对于"今日充值次数已满"RedeemOrderFailWithDailyAccountLimited等临时性错误系统会将账户设置为"每日禁用"状态并在次日自动恢复
```mermaid
stateDiagram-v2
[*] --> Pending
Pending --> Processing : 开始处理
Processing --> Success : 充值成功
Processing --> Fail : 充值失败
Processing --> Pending : 临时错误<br/>退回重试
Success --> [*]
Fail --> [*]
Pending --> [*]
note right of Processing
处理中状态包含 :
- 分配京东账户
- 发送卡密
- 等待响应
end note
note left of Fail
失败原因包括 :
- 卡密类型错误
- 卡片不存在
- 卡密冻结
- 金额不一致
end note
```
**图示来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L121-L272)
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L111)
**本节来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L121-L272)
- [card_redeem.go](file://internal/consts/card_redeem.go#L95-L111)
## 订单与京东账户关联机制
系统通过精确的账户管理机制实现订单与京东账户的有效关联当处理订单时`GetAvailableAccount`方法会根据订单金额和类别筛选出可用的京东账户筛选条件包括账户状态必须为"正常"余额充足以及未达到当日充值限额等一旦找到合适的账户系统立即通过`AllocateAccountToOrder`方法将账户与订单绑定
账户分配过程采用预扣款机制确保账户余额在处理期间不会被其他订单使用系统首先记录预扣款操作历史然后更新订单信息`AccountId``AccountName`字段设置为所选账户的标识和名称这种设计不仅保证了账户资源的独占性还为后续的错误追踪和账务核对提供了完整的审计线索
```mermaid
classDiagram
class OrderInfo {
+string OrderNo
+string CardNo
+string GiftCardPwd
+float OrderAmount
+int Status
+string AccountId
+string AccountName
}
class AccountInfo {
+string Id
+string Name
+string Cookie
+int Status
+float Balance
+string Username
+string Nickname
}
class OrderService {
+AllocateAccountToOrder(ctx, account, order)
+GetAvailableAccount(ctx, category, amount)
}
OrderService --> OrderInfo : "处理"
OrderService --> AccountInfo : "查询"
OrderInfo --> AccountInfo : "关联"
```
**图示来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L112-L174)
- [process.go](file://internal/logic/card_redeem_order/process.go#L84-L120)
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L112-L174)
- [process.go](file://internal/logic/card_redeem_order/process.go#L84-L120)
## 兑换码消费逻辑
兑换码消费是订单处理的核心业务逻辑`BindCard`方法实现该方法通过京东API客户端向京东服务器发送卡密信息完成实际的兑换操作消费过程包含多个关键步骤首先验证卡号和卡密的格式是否符合规则然后检查订单金额是否在允许范围内最后执行绑定操作
系统对消费结果进行详细分类处理成功时记录实际充值金额并更新卡种信息失败时根据错误代码区分不同类型的失败原因特别地系统处理"金额不一致"的特殊情况当实际充值金额与订单金额不符时系统会区分是"已充值但金额不同"RedeemOrderSuccessWithDifferentAmount还是"未充值"RedeemOrderFailWithDifferentAmount并采取相应的后续处理策略
```mermaid
flowchart TD
Start([开始消费]) --> ValidateCard["验证卡号卡密"]
ValidateCard --> IsValid{"格式有效?"}
IsValid --> |否| FailRule["失败: 卡号不符合规则"]
IsValid --> |是| CheckAmount["检查金额范围"]
CheckAmount --> InRange{"金额符合?"}
InRange --> |否| FailAmount["失败: 金额超出范围"]
InRange --> |是| SendCard["发送卡密到京东"]
SendCard --> Response["接收京东响应"]
Response --> Success{"兑换成功?"}
Success --> |是| UpdateSuccess["更新成功状态<br/>记录实际金额"]
Success --> |否| HandleError["处理错误"]
HandleError --> ErrorType{"错误类型?"}
ErrorType --> |CK失效| UpdateCKFail["标记CK失效"]
ErrorType --> |已绑定| UpdateBindFail["标记已绑定"]
ErrorType --> |已过期| UpdateExpired["标记已过期"]
ErrorType --> |冻结| UpdateFrozen["标记冻结"]
UpdateSuccess --> End1([消费完成])
FailRule --> End2([消费失败])
FailAmount --> End3([消费失败])
UpdateCKFail --> End4([消费失败])
UpdateBindFail --> End5([消费失败])
UpdateExpired --> End6([消费失败])
UpdateFrozen --> End7([消费失败])
```
**图示来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L175-L212)
- [card_redeem.go](file://internal/consts/card_redeem.go#L120-L171)
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L175-L212)
- [card_redeem.go](file://internal/consts/card_redeem.go#L120-L171)
## 幂等性保证
系统通过多层次机制确保订单处理的幂等性防止重复处理导致的数据不一致首先订单处理过程使用分布式锁`gmlock.LockFunc`保护确保同一时间只有一个线程处理特定类别的订单其次数据库层面通过条件更新实现乐观锁`StartProcessOrder`方法在更新订单状态时会检查当前状态是否为"待处理"只有符合条件的订单才会被处理
此外系统通过`IsCardPassRepeated`方法检测卡号和卡密的重复使用防止同一卡密被多次兑换对于已经成功处理的订单即使再次进入处理流程也会因为状态检查而被忽略这种设计确保了即使在系统重启网络重试等异常情况下订单也只会被正确处理一次维护了数据的完整性和一致性
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
- [process.go](file://internal/logic/card_redeem_order/process.go#L25-L64)
## 异常处理与重试机制
系统设计了完善的异常处理与重试机制确保在各种故障情况下仍能可靠运行异常分为订单相关错误和账户相关错误两大类订单相关错误如卡密类型错误卡片不存在等属于永久性错误系统会直接标记订单失败而账户相关错误如CK失效充值过快等属于临时性错误系统会将订单状态重置为"待处理"并切换到其他可用账户进行重试
重试机制通过`callback_count`字段控制每个订单最多允许5次调度尝试超过限制后订单将被标记为"禁用"防止无限重试对于临时性错误系统还会更新账户状态如将频繁充值的账户标记为"充值速度过快"并在一段时间后自动恢复这种分级处理策略既保证了系统的可用性又避免了对异常账户的过度使用
```mermaid
flowchart TD
Start([异常发生]) --> ErrorType{"错误类型?"}
ErrorType --> |订单相关| Permanent["永久性错误"]
ErrorType --> |账户相关| Temporary["临时性错误"]
Permanent --> UpdateFail["更新订单状态: 失败"]
Permanent --> LogError["记录失败原因"]
Permanent --> End1([处理完成])
Temporary --> CheckCount["检查重试次数"]
CheckCount --> CountExceeded{"超过5次?"}
CountExceeded --> |是| DisableOrder["禁用订单"]
CountExceeded --> |否| ResetStatus["重置订单状态: 待处理"]
DisableOrder --> End2([处理完成])
ResetStatus --> UpdateAccount["更新账户状态"]
UpdateAccount --> SwitchAccount["切换到其他账户"]
SwitchAccount --> Retry["重新加入处理队列"]
Retry --> End3([等待重试])
style Permanent fill:#f9f,stroke:#333
style Temporary fill:#bbf,stroke:#333
```
**图示来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L177-L200)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
**本节来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L177-L200)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L77-L111)
## 订单历史记录与统计
系统通过详细的操作历史记录和统计功能提供完整的订单生命周期追踪每次订单状态变更都会通过`AddHistory`方法记录操作历史包括操作时间操作类型账户信息和备注等这些历史记录不仅用于审计追踪还为用户提供了透明的处理进度
统计功能通过`Summary``DailySummary`等方法实现支持按类别用户和日期范围查询订单汇总数据系统定期生成统计报表帮助运营人员监控业务状况订单历史与统计数据存储在独立的数据库表中通过索引优化查询性能确保在大数据量下仍能快速响应查询请求
**本节来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L121-L272)
- [service/card_redeem_order.go](file://internal/service/card_redeem_order.go#L70-L79)
## 性能优化建议
为确保系统在高并发场景下的稳定运行建议采取以下性能优化措施首先合理配置数据库连接池和Redis缓存减少数据库访问延迟其次优化订单查询的数据库索引特别是`status``category``created_at`等常用查询字段第三调整`TriggerConsumeWithContext`的并发度根据服务器性能平衡处理速度与资源消耗
此外建议定期清理历史订单数据将超过一定期限的订单归档到历史库保持主表的数据量在合理范围内对于频繁查询的统计信息可以采用预计算的方式定期生成汇总数据避免实时计算带来的性能压力最后监控系统的关键指标如订单处理延迟失败率和账户利用率及时发现并解决性能瓶颈
**本节来源**
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L240-L272)
- [process.go](file://internal/logic/card_redeem_order/process.go#L273-L328)
## 常见问题解决方案
针对常见的订单处理问题系统提供了相应的解决方案对于兑换失败的情况首先检查错误代码确定具体原因如果是卡密类型错误或卡片不存在应联系用户确认卡密信息如果是CK失效或频繁错误系统会自动切换账户重试对于状态不一致的问题可以通过查询订单历史记录追踪状态变更过程必要时手动调整订单状态
当出现大量订单积压时应检查京东账户池是否充足及时添加新的可用账户对于金额不一致的争议系统记录了实际充值金额可用于与用户核对定期检查系统日志特别是`glog.Error`记录的错误信息有助于及时发现和解决潜在问题通过这些措施可以有效提高订单处理的成功率和用户体验
**本节来源**
- [process.go](file://internal/logic/card_redeem_order/process.go#L121-L272)
- [consume.go](file://internal/logic/card_redeem_order/consume.go#L175-L212)

View File

@@ -0,0 +1,271 @@
# 天猫订单处理
<cite>
**本文档引用的文件**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了天猫游戏卡密订单处理系统的完整流程涵盖订单创建店铺订单处理工作区管理回调处理和状态变更机制重点解析了订单与天猫店铺的关联逻辑订单同步机制以及Agiso回调处理流程文档还深入说明了订单状态机的转换规则事务管理策略订单工作区的概念与使用场景并提供性能优化建议和常见问题解决方案
## 项目结构
天猫游戏卡密订单处理功能主要集中在`api/card_info_t_mall_game/v1`目录下包含订单回调同步和工作区等核心模块控制器逻辑位于`internal/controller/card_info_t_mall_game`目录数据模型定义在`internal/model`服务层实现位于`internal/service`目录定时同步任务由`utility/cron`目录下的组件负责
```mermaid
graph TD
subgraph "API接口层"
A[order.go]
B[callback.go]
C[sync.go]
D[workspace.go]
end
subgraph "控制器层"
E[card_info_t_mall_game_v1_t_mall_game_order_submit.go]
F[card_info_t_mall_game_v1_t_mall_game_agiso_callback.go]
end
subgraph "服务层"
G[card_t_mall_order.go]
end
subgraph "模型层"
H[card_t_mall_game_order.go]
I[card_t_mall_game_work_space.go]
end
subgraph "定时任务"
J[t_mall_game_data_sync.go]
end
A --> E
B --> F
E --> G
F --> G
G --> H
J --> G
G --> I
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
## 核心组件
天猫游戏卡密订单处理系统的核心组件包括订单管理回调处理数据同步和工作区统计订单管理负责订单的创建和状态维护回调处理模块接收来自Agiso平台的异步通知数据同步组件确保本地数据与天猫平台保持一致工作区统计提供订单处理的汇总信息
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
## 架构概述
系统采用分层架构设计从上至下分为API接口层控制器层服务层和数据模型层API接口层定义了外部可调用的HTTP端点控制器层处理请求参数验证和业务流程调度服务层实现核心业务逻辑数据模型层负责数据持久化操作定时任务组件独立运行定期从天猫平台同步订单数据
```mermaid
graph TD
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> Model[数据模型]
Service --> External[外部系统]
Cron[定时任务] --> Service
External --> Callback[回调接口]
Callback --> Controller
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style Model fill:#69f,stroke:#333
style External fill:#ff6,stroke:#333
style Cron fill:#9f6,stroke:#333
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
## 详细组件分析
### 订单创建分析
订单创建流程始于客户端提交订单请求经过参数验证后控制器调用服务层创建订单系统首先验证账户信息的有效性然后创建新的订单记录并返回订单号整个过程包含事务管理确保数据一致性
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "订单API"
participant Controller as "控制器"
participant Service as "服务层"
participant Model as "数据模型"
Client->>API : 提交订单请求
API->>Controller : 转发请求
Controller->>Service : 验证账户信息
Service->>Model : 查询账户数据
Model-->>Service : 返回账户信息
Service->>Service : 创建订单输入
Service->>Model : 保存订单记录
Model-->>Service : 返回订单号
Service-->>Controller : 返回结果
Controller-->>API : 返回响应
API-->>Client : 返回订单号和状态
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
### 回调处理分析
Agiso回调处理是系统的重要组成部分负责接收来自第三方平台的异步通知系统验证回调签名和参数后更新订单状态并触发后续业务流程手动回调功能允许运营人员处理异常情况
```mermaid
flowchart TD
Start([接收到回调]) --> ValidateSign["验证签名"]
ValidateSign --> SignValid{"签名有效?"}
SignValid --> |否| ReturnError["返回验证失败"]
SignValid --> |是| ParseJson["解析JSON数据"]
ParseJson --> ProcessData["处理回调数据"]
ProcessData --> UpdateOrder["更新订单状态"]
UpdateOrder --> TriggerEvent["触发后续事件"]
TriggerEvent --> ReturnSuccess["返回成功响应"]
ReturnError --> End([结束])
ReturnSuccess --> End
```
**图示来源**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
**章节来源**
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_agiso_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_agiso_callback.go)
### 工作区与统计分析
工作区组件提供订单处理的统计功能包括每日订单汇总和基本统计信息这些数据用于监控系统运行状况和业务绩效支持分页查询和条件过滤
```mermaid
classDiagram
class TMallGameDailyOrderSummaryReq {
+string channelName
+RechargeTMallGameCallBackType callbackType
+CommonPageReq commonPageReq
}
class TMAllGameSummaryListRecord {
+int count
+int succeedCount
+float64 succeedAmount
+float64 amount
+float64 rate
+string date
}
class TMallGameStatsReq {
+string channelName
}
class TMallGameStatsRes {
+int totalCount
+int totalSucceedCount
+float64 totalAmount
+float64 totalSucceedAmount
+float64 totalRate
+int todayCount
+int todaySucceedCount
+float64 todayAmount
+float64 todaySucceedAmount
+float64 todayRate
}
TMallGameDailyOrderSummaryReq --> TMAllGameSummaryListRecord : "包含"
TMallGameStatsReq --> TMallGameStatsRes : "返回"
```
**图示来源**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
- [card_t_mall_game_work_space.go](file://internal/model/card_t_mall_game_work_space.go)
**章节来源**
- [workspace.go](file://api/card_info_t_mall_game/v1/workspace.go)
## 依赖分析
系统各组件之间存在明确的依赖关系API接口层依赖控制器层控制器层依赖服务层服务层依赖数据模型层定时任务组件直接依赖服务层实现了数据同步功能这种分层依赖结构确保了系统的可维护性和可测试性
```mermaid
graph LR
A[API接口] --> B[控制器]
B --> C[服务层]
C --> D[数据模型]
E[定时任务] --> C
F[外部系统] --> B
style A fill:#bbf,stroke:#333
style B fill:#f96,stroke:#333
style C fill:#6f9,stroke:#333
style D fill:#69f,stroke:#333
style E fill:#9f6,stroke:#333
style F fill:#ff6,stroke:#333
```
**图示来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
**章节来源**
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_t_mall_order.go](file://internal/service/card_t_mall_order.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
## 性能考虑
为确保系统高性能运行建议优化数据库查询使用适当的索引合理配置缓存策略对于数据同步任务应选择业务低峰期执行并采用分批处理方式避免对系统造成过大压力监控系统应实时跟踪订单处理延迟和回调验证失败率等关键指标
## 故障排除指南
常见问题包括订单同步延迟和回调验证失败对于同步延迟应检查定时任务执行日志和网络连接状况回调验证失败通常由签名不匹配引起需核对密钥配置和时间戳同步情况系统提供了手动回调功能可用于处理异常订单
**章节来源**
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [callback.go](file://api/card_info_t_mall_game/v1/callback.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
## 结论
天猫游戏卡密订单处理系统通过清晰的分层架构和模块化设计实现了高效可靠的订单处理能力系统具备完整的订单生命周期管理安全的回调验证机制和准确的数据同步功能通过持续监控和优化系统能够满足高并发场景下的业务需求

View File

@@ -0,0 +1,283 @@
# 订单处理逻辑
<cite>
**本文档引用的文件**
- [order.go](file://api/order/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [order_info.go](file://internal/model/do/order_info.go)
- [v_1_order_info.go](file://internal/dao/v_1_order_info.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [sys_user_payment_record.go](file://internal/consts/sys_user_payment_record.go)
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [card_info_walmart_v1_order_summary_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_summary_list.go)
- [card_apple_order.go](file://internal/logic/card_apple_order/card_apple_order.go)
- [card_redeem_order.go](file://internal/logic/card_redeem_order/card_redeem_order.go)
- [utility/utils/tools.go](file://utility/utils/tools.go)
- [utility/cache/cache.go](file://utility/cache/cache.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了kami_backend系统中订单处理业务逻辑的实现重点涵盖卡密充值订单和兑换订单的全生命周期管理包括订单创建查询回调处理和状态变更流程文档还详细说明了订单与卡密账户支付渠道的关联机制以及订单历史记录统计和汇总的实现方式同时阐述了订单处理中的幂等性保证事务管理策略和错误重试机制并提供了完整的订单状态机描述
## 项目结构
kami_backend的订单处理相关代码分布在多个模块中主要集中在api/orderinternal/controller/order和各卡密类型模块中系统采用分层架构将API接口控制器业务逻辑和服务层分离确保代码的可维护性和可扩展性
```mermaid
graph TD
subgraph "API层"
OrderAPI[api/order/v1/order.go]
CardAPI[api/card_info_*/v1/*.go]
end
subgraph "控制器层"
OrderController[internal/controller/order]
CardController[internal/controller/card_info_*]
end
subgraph "服务层"
OrderService[internal/service/order]
CardService[internal/service/card_*]
end
subgraph "数据访问层"
DAO[internal/dao/v_1_order_info.go]
Model[internal/model/do/order_info.go]
end
OrderAPI --> OrderController
CardAPI --> CardController
OrderController --> OrderService
CardController --> CardService
OrderService --> DAO
CardService --> DAO
DAO --> Model
```
**图示来源**
- [order.go](file://api/order/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [v_1_order_info.go](file://internal/dao/v_1_order_info.go)
- [order_info.go](file://internal/model/do/order_info.go)
**本节来源**
- [order.go](file://api/order/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
## 核心组件
订单处理系统的核心组件包括订单创建服务状态管理器回调处理器统计服务和日志记录器这些组件协同工作确保订单从创建到完成的整个流程的可靠性和一致性
**本节来源**
- [order_info.go](file://internal/model/do/order_info.go)
- [v_1_order_info.go](file://internal/dao/v_1_order_info.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
## 架构概述
订单处理系统采用事件驱动的微服务架构各组件通过明确定义的接口进行通信系统设计注重可扩展性和容错性支持多种卡密类型和支付渠道
```mermaid
graph LR
Client[客户端] --> API[API网关]
API --> OrderController[订单控制器]
API --> CardController[卡密控制器]
OrderController --> OrderService[订单服务]
CardController --> CardService[卡密服务]
OrderService --> Database[(数据库)]
CardService --> ExternalAPI[外部API]
OrderService --> Cache[(缓存)]
CardService --> Cache
Database --> Analytics[分析服务]
Cache --> Analytics
```
**图示来源**
- [order.go](file://api/order/v1/order.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
## 详细组件分析
### 订单创建与处理
订单创建流程涉及多个验证步骤和状态转换确保数据的完整性和业务规则的执行
#### 订单状态机
```mermaid
stateDiagram-v2
[*] --> 待处理
待处理 --> 处理中 : 开始处理
处理中 --> 成功 : 处理完成
处理中 --> 失败 : 处理失败
处理中 --> 超时 : 超时未完成
成功 --> [*]
失败 --> [*]
超时 --> [*]
state "待处理" as pending {
[*] --> 接收
接收 --> 验证
验证 --> 排队
}
state "处理中" as processing {
[*] --> 分配资源
分配资源 --> 执行
执行 --> 等待回调
}
```
**图示来源**
- [order_info.go](file://internal/model/do/order_info.go)
- [sys_user_payment_record.go](file://internal/consts/sys_user_payment_record.go)
#### 订单创建流程
```mermaid
sequenceDiagram
participant Client as 客户端
participant API as API接口
participant Controller as 控制器
participant Service as 服务层
participant DAO as 数据访问层
Client->>API : 提交订单请求
API->>Controller : 转发请求
Controller->>Controller : 参数验证
Controller->>Service : 创建订单
Service->>Service : 幂等性检查
Service->>DAO : 保存订单
DAO-->>Service : 返回结果
Service-->>Controller : 返回订单信息
Controller-->>API : 返回响应
API-->>Client : 返回订单创建结果
```
**图示来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
**本节来源**
- [order_v1_order_form_create.go](file://internal/controller/order/order_v1_order_form_create.go)
- [card_info_apple_v1_recharge_submit.go](file://internal/controller/card_info_apple/card_info_apple_v1_recharge_submit.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
### 回调处理机制
回调处理是订单系统的关键环节负责接收外部系统的状态更新并相应地更新订单状态
```mermaid
sequenceDiagram
participant External as 外部系统
participant API as 回调API
participant Controller as 控制器
participant Service as 服务层
participant DAO as 数据访问层
External->>API : 发送状态更新
API->>Controller : 转发回调
Controller->>Controller : 签名验证
Controller->>Service : 处理回调
Service->>Service : 事务处理
Service->>DAO : 更新订单状态
DAO-->>Service : 返回结果
Service-->>Controller : 返回处理结果
Controller-->>API : 返回响应
API-->>External : 确认接收
```
**图示来源**
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
**本节来源**
- [card_info_jd_v1_order_callback.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
### 订单查询与统计
系统提供多种查询接口支持订单历史记录查询实时状态查询和统计汇总功能
```mermaid
flowchart TD
Start([开始]) --> Validate["验证查询参数"]
Validate --> CheckCache["检查缓存"]
CheckCache --> CacheHit{"缓存命中?"}
CacheHit --> |是| ReturnCache["返回缓存结果"]
CacheHit --> |否| QueryDB["查询数据库"]
QueryDB --> Process["处理查询结果"]
Process --> UpdateCache["更新缓存"]
UpdateCache --> ReturnResult["返回结果"]
ReturnCache --> End([结束])
ReturnResult --> End
```
**图示来源**
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
- [card_info_jd_v1_order_summary_list.go](file://internal/controller/card_info_jd/card_info_jd_v1_order_summary_list.go)
- [card_info_walmart_v1_order_summary_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_summary_list.go)
**本节来源**
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [order_v1_order_summary_get_list.go](file://internal/controller/order/order_v1_order_summary_get_list.go)
## 依赖分析
订单处理系统依赖于多个内部和外部组件这些依赖关系确保了系统的完整功能
```mermaid
graph TD
OrderSystem[订单系统] --> UserService[用户服务]
OrderSystem --> PaymentService[支付服务]
OrderSystem --> CardService[卡密服务]
OrderSystem --> CacheService[缓存服务]
OrderSystem --> Database[数据库]
OrderSystem --> ExternalAPI[外部API]
UserService --> AuthService[认证服务]
PaymentService --> ThirdParty[第三方支付]
CardService --> ExternalPlatform[外部平台]
CacheService --> Redis[(Redis)]
Database --> MySQL[(MySQL)]
```
**图示来源**
- [order.go](file://api/order/v1/order.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [utility/cache/cache.go](file://utility/cache/cache.go)
**本节来源**
- [order.go](file://api/order/v1/order.go)
- [card_apple_order.go](file://internal/service/card_apple_order.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
## 性能考虑
订单处理系统在设计时充分考虑了性能因素采用了多种优化策略来确保高并发场景下的稳定运行
- **缓存策略**使用Redis缓存频繁访问的订单数据减少数据库压力
- **批量处理**对大量订单操作采用批量处理方式提高处理效率
- **异步处理**非关键路径操作采用异步处理提升响应速度
- **连接池**数据库连接使用连接池管理避免频繁创建销毁连接
- **索引优化**在关键查询字段上建立适当索引加快查询速度
## 故障排除指南
当订单处理出现问题时可以按照以下步骤进行排查
1. **检查日志**查看系统日志和订单日志定位错误发生的具体位置
2. **验证状态**确认订单当前状态是否符合预期检查状态转换逻辑
3. **检查依赖**确认相关服务如支付卡密账户是否正常运行
4. **查看监控**检查系统监控指标如响应时间错误率等
5. **重现问题**尝试在测试环境重现问题便于调试
**本节来源**
- [order_v1_order_log_list.go](file://internal/controller/order/order_v1_order_log_list.go)
- [utility/monitor/monitor.go](file://utility/monitor/monitor.go)
## 结论
kami_backend的订单处理系统设计合理功能完整能够有效支持卡密充值和兑换业务系统通过清晰的分层架构完善的错误处理机制和性能优化策略确保了高可用性和可维护性未来可以进一步优化异步处理能力和监控告警系统提升整体系统稳定性

View File

@@ -0,0 +1,188 @@
# IP查询优化
<cite>
**本文档引用的文件**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
- [cache.go](file://utility/cache/cache.go)
- [consts.go](file://utility/integration/restriction/consts.go)
</cite>
## 目录
1. [引言](#引言)
2. [IP查询优化策略](#ip查询优化策略)
3. [IP检查接口实现流程](#ip检查接口实现流程)
4. [缓存穿透与缓存雪崩处理](#缓存穿透与缓存雪崩处理)
5. [查询性能监控与调优](#查询性能监控与调优)
6. [高并发场景下的性能建议](#高并发场景下的性能建议)
7. [结论](#结论)
## 引言
本文档详细阐述了kami_backend系统中IP查询的性能优化机制通过分析Redis缓存的使用第三方IP定位服务集成以及数据库查询优化技术全面介绍了系统如何高效处理IP查询请求文档重点说明了IP检查接口的实现流程包括如何快速判断IP是否在黑名单中以及如何应对缓存穿透和缓存雪崩等常见问题同时还提供了查询性能的监控指标和优化方法为高并发场景下的性能调优提供了实用建议
## IP查询优化策略
kami_backend系统采用了多层次的IP查询优化策略确保在高并发场景下仍能保持高效的查询性能
系统首先通过Redis缓存机制来优化IP查询性能`utility/cache/cache.go`文件中的`Cache`结构体实现了基于Redis的缓存适配器通过`SetAdapter(gcache.NewAdapterRedis(g.Redis()))`方法将缓存后端设置为Redis实现了分布式缓存支持这种设计使得IP查询结果可以在多个服务实例间共享大大减少了重复查询的开销
对于IP地理位置查询系统采用了多源集成策略`utility/integration/restriction/location.go`文件中定义了多个第三方IP定位服务提供商包括CSDNPCOnlineMeiTuVoDBIPQJQQIQIYI和IP66等系统通过`GetLocationByIP`函数实现随机选择策略从多个服务提供商中随机选择一个进行查询这不仅提高了查询成功率还避免了对单一服务的过度依赖
```mermaid
flowchart TD
A[IP查询请求] --> B{IP是否为内网IP?}
B --> |是| C[直接允许访问]
B --> |否| D{Redis缓存中是否存在?}
D --> |是| E[返回缓存结果]
D --> |否| F[选择第三方IP定位服务]
F --> G[并发查询多个服务]
G --> H[获取IP地理位置信息]
H --> I[存储到数据库]
I --> J[更新Redis缓存]
J --> K[返回查询结果]
```
**图示来源**
- [location.go](file://utility/integration/restriction/location.go#L29-L38)
- [cache.go](file://utility/cache/cache.go#L19-L21)
为了进一步提高查询效率系统还实现了查询结果的本地缓存当IP地址的地理位置信息被查询过一次后相关信息会被存储在`restrict_ip_record`数据库表中并在后续查询中优先从数据库读取避免了重复的网络请求
**本节来源**
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
- [cache.go](file://utility/cache/cache.go#L0-L126)
## IP检查接口实现流程
IP检查接口的实现流程设计精巧能够快速判断IP是否在黑名单中并根据商户配置的限制策略做出相应决策
接口的核心实现位于`internal/controller/restriction/restriction_v1_check_ip_allowed.go`文件中的`CheckIPAllowed`方法该方法接收包含IP地址设备ID订单号等信息的请求参数并返回IP是否被允许访问的结果
流程首先获取商户的限制策略然后按照优先级依次检查各种限制条件
1. 卡密限制检查当前卡密是否已被限制
2. 设备限制检查当前设备是否被禁用
3. 代理限制检查是否使用代理访问
4. IP限制检查IP地址是否在黑名单中
5. 内网IP处理根据配置决定是否限制内网IP
6. 区域限制检查IP所属省份是否在允许范围内
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 服务层
participant Database as 数据库
Client->>Controller : 发送IP检查请求
Controller->>Service : 获取商户限制策略
Service-->>Controller : 返回策略信息
Controller->>Service : 检查卡密限制
Service-->>Controller : 返回检查结果
alt 存在限制
Controller-->>Client : 返回禁止访问
else 无卡密限制
Controller->>Service : 检查设备限制
Service-->>Controller : 返回检查结果
alt 存在限制
Controller-->>Client : 返回禁止访问
else 无设备限制
Controller->>Service : 检查代理限制
Service-->>Controller : 返回检查结果
alt 使用代理
Controller-->>Client : 返回禁止访问
else 非代理访问
Controller->>Service : 检查IP黑名单
Service-->>Controller : 返回检查结果
alt 在黑名单
Controller-->>Client : 返回禁止访问
else 不在黑名单
Controller->>Service : 检查区域限制
Service-->>Controller : 返回检查结果
Controller-->>Client : 返回允许访问
end
end
end
end
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L17-L68)
值得注意的是系统在每次IP检查后都会记录检查结果无论IP是否被允许访问这一设计不仅为后续的统计分析提供了数据支持也便于追踪和审计IP访问行为
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
## 缓存穿透与缓存雪崩处理
kami_backend系统通过多种机制有效应对缓存穿透和缓存雪崩问题确保系统的稳定性和可靠性
对于缓存穿透问题系统采用了"空值缓存"策略当查询一个不存在的IP地址时系统仍然会将查询结果"未找到"缓存一段时间这样可以防止恶意用户通过构造大量不存在的IP地址来攻击数据库`internal/logic/restriction/ip_record.go`文件的`GetOrSetIPRecord`方法中系统首先尝试从数据库查询IP记录如果不存在则调用第三方服务获取IP信息并将结果存储到数据库和缓存中
```mermaid
flowchart TD
A[IP查询请求] --> B{Redis缓存中是否存在?}
B --> |是| C[返回缓存结果]
B --> |否| D{数据库中是否存在?}
D --> |是| E[获取数据库记录]
D --> |否| F[调用第三方IP定位服务]
F --> G{获取到IP信息?}
G --> |是| H[存储到数据库]
G --> |否| I[缓存空结果]
H --> J[更新Redis缓存]
I --> J
J --> K[返回查询结果]
```
**图示来源**
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L20-L53)
针对缓存雪崩问题系统采取了以下措施
1. **缓存过期时间随机化**不同IP记录的缓存过期时间存在一定随机性避免大量缓存同时失效
2. **多级缓存机制**结合Redis分布式缓存和本地缓存即使Redis出现故障仍能通过数据库提供基本服务
3. **服务降级策略**当第三方IP定位服务不可用时系统会自动切换到其他备用服务确保核心功能不受影响
此外系统还实现了查询重试机制`utility/integration/restriction/location.go`文件中`GetLocationByIP`函数使用了`retry.Retry`方法当某个IP定位服务失败时会自动重试其他服务最多尝试所有可用服务大大提高了查询成功率
**本节来源**
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L0-L54)
- [location.go](file://utility/integration/restriction/location.go#L29-L38)
## 查询性能监控与调优
系统提供了完善的查询性能监控机制帮助开发和运维人员及时发现和解决性能问题
`utility/cache/cache.go`文件中`Cache`结构体提供了`GetPrefixKeyNum`方法可以统计指定前缀的缓存键数量这一功能可用于监控不同类型的缓存使用情况例如统计IP相关缓存的数量帮助评估缓存的使用效率和内存占用
系统还集成了OpenTelemetry追踪功能通过`SaveTrace``GetTrace`方法实现请求的全链路追踪这使得开发人员可以清晰地看到每个IP查询请求的完整执行路径包括各个服务调用的时间消耗为性能分析和优化提供了有力支持
性能调优方面系统采用了以下策略
1. **数据库索引优化**`restrict_ip_record`表的`ip`字段上建立了唯一索引确保IP查询的高效性
2. **批量操作**对于频繁的IP查询系统支持批量查询接口减少网络往返次数
3. **连接池管理**合理配置数据库连接池大小避免因连接过多导致数据库性能下降
4. **异步处理**对于非关键路径的IP信息更新操作采用异步方式处理减少用户请求的响应时间
**本节来源**
- [cache.go](file://utility/cache/cache.go#L85-L125)
## 高并发场景下的性能建议
在高并发场景下IP查询性能的优化尤为重要基于kami_backend系统的实现提出以下性能调优建议
1. **缓存预热**在系统启动或高峰期前预先加载常用IP地址的查询结果到缓存中避免大量请求同时触发缓存未命中
2. **缓存分片**对于大规模部署可以考虑将IP缓存按地域或IP段进行分片分散Redis实例的压力
3. **读写分离**将IP查询读操作和IP记录更新写操作分离到不同的数据库实例提高并发处理能力
4. **限流保护**在API网关层面实施限流策略防止恶意用户通过大量IP查询请求耗尽系统资源
5. **监控告警**建立完善的监控体系实时监控IP查询的响应时间错误率和缓存命中率等关键指标设置合理的告警阈值
6. **容量规划**根据业务增长预测定期评估和调整Redis和数据库的容量确保系统有足够的资源应对流量增长
7. **服务弹性**采用微服务架构将IP查询服务独立部署便于根据负载情况动态扩缩容
8. **降级预案**制定详细的降级预案当第三方IP定位服务大面积不可用时能够快速切换到备用方案保证核心业务不受影响
**本节来源**
- [cache.go](file://utility/cache/cache.go#L0-L126)
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
## 结论
kami_backend系统的IP查询优化机制通过多层次的缓存策略多源IP定位服务集成和完善的错误处理机制实现了高效可靠的IP查询功能系统不仅能够快速判断IP是否在黑名单中还通过合理的架构设计有效应对了缓存穿透和缓存雪崩等常见问题在高并发场景下通过缓存预热读写分离限流保护等措施确保了系统的稳定性和性能未来可以进一步优化的方向包括引入布隆过滤器来更高效地处理缓存穿透问题以及利用机器学习算法预测IP查询热点实现更智能的缓存预热策略

View File

@@ -0,0 +1,291 @@
# IP记录管理
<cite>
**本文档引用文件**
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [v_1_restrict_ip_record.go](file://internal/dao/internal/v_1_restrict_ip_record.go)
- [restriction.go](file://internal/service/restriction.go)
- [model.go](file://internal/model/restriction.go)
- [cache.go](file://utility/cache/cache.go)
- [location.go](file://utility/integration/restriction/location.go)
</cite>
## 目录
1. [简介](#简介)
2. [数据结构设计](#数据结构设计)
3. [核心操作实现](#核心操作实现)
4. [Redis缓存集成](#redis缓存集成)
5. [IP记录与用户行为关联](#ip记录与用户行为关联)
6. [最佳实践](#最佳实践)
7. [结论](#结论)
## 简介
本文档详细阐述了kami_backend系统中IP记录管理的完整实现方案系统通过精细化的IP记录管理机制实现了对用户访问行为的全面追踪和安全控制IP记录系统不仅存储基本的IP地址信息还集成了地理位置识别访问模式分析和异常行为检测等功能为系统的安全防护提供了坚实的数据基础
## 数据结构设计
IP记录系统采用分层的数据结构设计包含数据库表结构数据访问对象DAO和业务模型三个层次
### 数据库表结构
IP记录的核心数据存储在`restrict_ip_record`数据库表中其字段定义如下
| 字段名 | 数据类型 | 说明 |
|--------|---------|------|
| id | BIGINT | 主键自增ID |
| ip | VARCHAR | IP地址 |
| ip_province | VARCHAR | IP地址所在省份或地区 |
| is_public | TINYINT | 是否是公共地址1:0: |
| raw_data | TEXT | 原始地理位置数据 |
| created_at | DATETIME | 创建时间 |
| updated_at | DATETIME | 更新时间 |
| deleted_at | DATETIME | 删除时间软删除 |
```mermaid
erDiagram
restrict_ip_record {
BIGINT id PK
VARCHAR ip
VARCHAR ip_province
TINYINT is_public
TEXT raw_data
DATETIME created_at
DATETIME updated_at
DATETIME deleted_at
}
```
**Diagram sources**
- [v_1_restrict_ip_record.go](file://internal/dao/internal/v_1_restrict_ip_record.go#L14-L19)
### 业务模型设计
在业务逻辑层IP记录通过`RestrictionIPRecordOutput`结构体进行封装该结构体继承了数据库实体并添加了业务相关的扩展字段
```mermaid
classDiagram
class RestrictionIPRecordOutput {
+g.Meta orm : "table : restrict_ip_record"
+V1RestrictIpRecord
+RawData Response
}
class V1RestrictIpRecord {
+uint Id
+string Ip
+string IpProvince
+bool IsPublic
}
class Response {
+string City
+string Isp
+string Province
+string Region
+string RawData
}
RestrictionIPRecordOutput --> V1RestrictIpRecord : "继承"
RestrictionIPRecordOutput --> Response : "包含"
```
**Diagram sources**
- [model.go](file://internal/model/restriction.go#L11-L17)
**Section sources**
- [model.go](file://internal/model/restriction.go#L11-L17)
- [v_1_restrict_ip_record.go](file://internal/dao/internal/v_1_restrict_ip_record.go#L14-L19)
## 核心操作实现
IP记录管理系统提供了完整的CRUD创建读取更新删除操作接口其中最核心的是IP记录的获取与创建逻辑
### IP记录创建与获取
系统通过`GetOrSetIPRecord`方法实现IP记录的获取或创建该方法采用"先查询后创建"的策略确保同一IP地址不会重复记录
```mermaid
flowchart TD
Start([开始]) --> TrimIP["清理IP地址空白字符"]
TrimIP --> QueryDB["查询数据库是否存在该IP记录"]
QueryDB --> RecordExists{"记录已存在?"}
RecordExists --> |是| ReturnRecord["返回现有记录"]
RecordExists --> |否| CheckPublicIP["检查是否为公共IP"]
CheckPublicIP --> |是| GetLocation["获取地理位置信息"]
CheckPublicIP --> |否| SetEmptyLocation["设置空地理位置"]
GetLocation --> InsertRecord["插入新IP记录到数据库"]
SetEmptyLocation --> InsertRecord
InsertRecord --> CreateOutput["创建输出模型"]
CreateOutput --> End([结束])
```
**Diagram sources**
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L20-L53)
**Section sources**
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L20-L53)
- [restriction.go](file://internal/service/restriction.go#L30-L32)
### 地理位置信息获取
系统通过集成多个第三方IP地理位置服务实现了高可用的地理位置查询功能当一个服务不可用时系统会自动尝试其他服务
```mermaid
sequenceDiagram
participant Service as "Restriction服务"
participant Location as "地理位置接口"
participant Impl1 as "PCOnline客户端"
participant Impl2 as "CSDN客户端"
participant Impl3 as "其他客户端"
Service->>Location : GetLocationByIP(ctx, ip)
Location->>Location : retry.Retry()
Location->>Impl1 : QueryLocationByIP(ctx, ip)
alt 成功且数据有效
Impl1-->>Location : 返回地理位置
Location-->>Service : 返回结果
else 失败或数据无效
Location->>Impl2 : QueryLocationByIP(ctx, ip)
alt 成功且数据有效
Impl2-->>Location : 返回地理位置
Location-->>Service : 返回结果
else 失败或数据无效
Location->>Impl3 : QueryLocationByIP(ctx, ip)
Impl3-->>Location : 返回地理位置
Location-->>Service : 返回结果
end
end
```
**Diagram sources**
- [location.go](file://utility/integration/restriction/location.go#L29-L38)
- [impl.go](file://utility/integration/restriction/impl.go#L0-L44)
**Section sources**
- [location.go](file://utility/integration/restriction/location.go#L29-L38)
- [consts.go](file://utility/integration/restriction/consts.go#L0-L23)
## Redis缓存集成
为了提高IP记录的读写性能系统集成了Redis缓存机制通过缓存适配器实现了数据库与缓存的协同工作
### 缓存初始化
系统在启动时初始化缓存实例并设置Redis作为底层存储适配器
```go
func NewCache() *Cache {
if cache == nil {
once.Do(func() {
cache = &Cache{
Cache: gcache.New(),
}
cache.SetAdapter(gcache.NewAdapterRedis(g.Redis()))
})
}
return cache
}
```
### 计数器缓存
系统提供了原子性的计数器操作用于统计特定键的访问次数
```mermaid
flowchart TD
Start([Incr方法开始]) --> GetCache["获取缓存值"]
GetCache --> IsNil{"缓存值为空?"}
IsNil --> |是| SetInitial["设置初始值为1"]
IsNil --> |否| UpdateValue["更新值为原值+1"]
SetInitial --> ReturnSuccess["返回成功"]
UpdateValue --> ReturnSuccess
ReturnSuccess --> End([方法结束])
```
**Diagram sources**
- [cache.go](file://utility/cache/cache.go#L63-L71)
**Section sources**
- [cache.go](file://utility/cache/cache.go#L41-L86)
## IP记录与用户行为关联
IP记录系统与用户行为分析紧密集成通过多维度的数据关联实现了对异常访问模式的精准追踪
### 设备与IP关联
系统通过`SaveDeviceInfo`方法将用户设备信息与IP地址进行关联建立完整的访问链路
```mermaid
classDiagram
class RestrictionDeviceInput {
+[]string IPs
+string RemoteIP
+string DeviceID
+string DeviceModel
+string UserAgent
}
class V1RestrictClientAccessRecord {
+int Id
+string VisitorId
+string DeviceModel
+string UserAgent
+bool IsUseProxy
}
class V1RestrictClientAccessIpRelation {
+int Id
+string Ip
+bool IsRemoteIp
+int RestrictIpRecordId
+int RestrictClientAccessRecordId
+string SessionId
}
RestrictionDeviceInput --> V1RestrictClientAccessRecord : "映射"
V1RestrictClientAccessRecord --> V1RestrictClientAccessIpRelation : "包含"
V1RestrictClientAccessIpRelation --> V1RestrictIpRecord : "关联"
```
**Diagram sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L44)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L31-L59)
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L44)
- [model.go](file://internal/model/restriction.go#L11-L17)
### 异常访问模式检测
系统通过分析IP记录与设备信息的关联关系可以检测出多种异常访问模式如代理使用IP伪装等
```mermaid
flowchart TD
Start([开始检测]) --> GetDeviceRecord["获取设备访问记录"]
GetDeviceRecord --> GetLastAccess["获取最后一次访问信息"]
GetLastAccess --> GetIPRelation["获取IP关联关系"]
GetIPRelation --> CountSameSession["统计同一会话中的IP数量"]
CountSameSession --> SingleIP{"只有一个IP?"}
SingleIP --> |是| NotUseProxy["未使用代理"]
SingleIP --> |否| UseProxy["使用代理"]
NotUseProxy --> End([检测结束])
UseProxy --> End
```
**Diagram sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L74-L112)
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L74-L112)
## 最佳实践
### 数据清理策略
建议定期清理过期的IP记录特别是那些长时间未再次访问的记录可以通过创建定时任务每月清理一次超过一年未更新的IP记录
### 存储优化
对于`raw_data`字段建议采用压缩存储的方式减少数据库存储空间占用同时`ip``ip_province`字段建立索引提高查询性能
### 性能监控
建立完善的性能监控体系重点关注以下几个指标
- IP记录查询响应时间
- 地理位置服务调用成功率
- Redis缓存命中率
- 数据库查询性能
可以通过集成OpenTelemetry等监控工具实现对IP记录管理系统的全面监控
### 安全考虑
- 对敏感的IP记录数据进行访问控制
- 定期备份IP记录数据
- 监控异常的IP访问模式及时发现潜在的安全威胁
- 对地理位置服务API调用进行限流防止被滥用
## 结论
kami_backend的IP记录管理系统通过精心设计的数据结构和高效的实现逻辑为系统的安全防护提供了强有力的支持系统不仅能够准确记录和追踪用户IP访问行为还能通过与设备信息的关联分析识别出复杂的异常访问模式结合Redis缓存的使用系统在保证数据准确性的同时也实现了高性能的读写操作通过遵循本文档提供的最佳实践可以进一步优化系统的性能和安全性为业务的稳定运行提供保障

View File

@@ -0,0 +1,440 @@
# IP限制机制
<cite>
**本文档引用文件**
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction_v1_block_order.go](file://internal/controller/restriction/restriction_v1_block_order.go)
- [v_1_restrict_ip_record.go](file://internal/model/entity/v_1_restrict_ip_record.go)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/model/entity/v_1_restrict_ip_order_access.go)
</cite>
## 目录
1. [简介](#简介)
2. [IP记录存储结构](#ip记录存储结构)
3. [黑白名单管理机制](#黑白名单管理机制)
4. [访问控制策略](#访问控制策略)
5. [配置方法与生效流程](#配置方法与生效流程)
6. [缓存机制与查询优化](#缓存机制与查询优化)
7. [查询接口说明](#查询接口说明)
8. [最佳实践与使用场景](#最佳实践与使用场景)
9. [与其他安全机制的集成](#与其他安全机制的集成)
## 简介
kami_backend系统的IP限制机制是一套完整的访问控制体系用于防止恶意爬虫异常登录等安全威胁该机制通过记录客户端IP地址设备信息和访问行为结合黑白名单策略和区域限制实现精细化的访问控制系统支持基于卡密设备IDIP地址和代理使用情况的多维度限制并与商户部署策略深度集成提供灵活的安全防护能力
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L1-L67)
## IP记录存储结构
IP限制机制采用三层数据模型来存储和管理IP相关信息
1. **IP基础记录表** (`restrict_ip_record`)存储IP地址的基本信息
- IP地址
- 所在省份/地区
- 是否为公共IP
- 原始地理位置数据
- 创建和更新时间戳
2. **客户端访问记录表** (`restrict_client_access_record`)存储设备级别的访问信息
- 访问ID设备ID
- 设备型号
- 用户代理User Agent
- 是否使用代理
3. **IP订单访问关联表** (`restrict_ip_order_access`)记录IP与订单的访问关系
- 关联IP记录ID
- 订单号
- 卡密
- 限制状态
- 限制策略
- 设备ID
当系统接收到新的IP访问时会自动调用`GetOrSetIPRecord`方法检查并创建IP记录对于公网IP系统会通过外部服务获取其地理位置信息并存储在`RawData`字段中
```mermaid
erDiagram
restrict_ip_record {
uint id PK
string ip UK
string ip_province
bool is_public
string raw_data
datetime created_at
datetime updated_at
datetime deleted_at
}
restrict_client_access_record {
uint id PK
string visitor_id UK
string device_model
string user_agent
bool is_use_proxy
datetime created_at
datetime updated_at
datetime deleted_at
}
restrict_ip_order_access {
uint id PK
int restrict_ip_id FK
string order_no
string card_pass
string ip
int status
string restrict_strategy
string device_id
datetime created_at
datetime updated_at
datetime deleted_at
}
restrict_ip_record ||--o{ restrict_ip_order_access : "被限制"
restrict_client_access_record ||--o{ restrict_ip_order_access : "关联"
```
**Diagram sources**
- [v_1_restrict_ip_record.go](file://internal/model/entity/v_1_restrict_ip_record.go#L11-L20)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go#L11-L20)
- [v_1_restrict_ip_order_access.go](file://internal/model/entity/v_1_restrict_ip_order_access.go#L11-L23)
**Section sources**
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go#L21-L23)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go#L21-L23)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go#L21-L23)
## 黑白名单管理机制
IP限制机制实现了基于多维度的黑白名单管理支持以下几种限制类型
1. **卡密限制**当某个卡密被标记为受限时所有使用该卡密的请求都将被阻止
2. **设备限制**特定设备ID被禁止访问系统
3. **IP限制**特定IP地址被加入黑名单
4. **代理限制**检测到使用代理的请求将被阻止
5. **内网IP限制**可选择是否限制内网IP访问
6. **区域限制**仅允许或禁止特定省份/地区的访问
系统通过`IsRestrictExistByCardPass``IsRestrictDevice``IsRestrictExistByIP`等方法检查各种限制条件的存在当检测到违规行为时系统会自动将相关信息记录到`restrict_ip_order_access`表中并设置相应的限制状态
```mermaid
flowchart TD
A[新请求到达] --> B{检查卡密限制?}
B --> |是| C{卡密已被限制?}
C --> |是| D[拒绝访问]
C --> |否| E{检查设备限制?}
B --> |否| E
E --> |是| F{设备已被限制?}
F --> |是| D
F --> |否| G{检查代理使用?}
E --> |否| G
G --> |是| H{使用代理?}
H --> |是| D
H --> |否| I{检查IP限制?}
G --> |否| I
I --> |是| J{IP已被限制?}
J --> |是| D
J --> |否| K[允许访问]
I --> |否| K
```
**Diagram sources**
- [restriction.go](file://internal/service/restriction.go#L35-L65)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
**Section sources**
- [restriction.go](file://internal/service/restriction.go#L35-L65)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
## 访问控制策略
访问控制策略由商户部署配置决定系统在处理每个请求时都会根据预设策略进行判断控制流程如下
1. 系统首先获取当前商户部署的限制策略
2. 按照优先级依次检查各项限制条件
3. 任何一项限制条件触发都将导致访问被拒绝
4. 如果所有限制条件都未触发则允许访问
策略检查的优先级顺序为
1. 卡密限制
2. 设备限制
3. 代理使用检测
4. IP限制
5. 内网IP特殊处理
6. 区域限制
对于内网IP系统提供了特殊的处理逻辑如果策略中未启用内网IP限制则自动允许所有内网IP访问这有助于开发和测试环境的便利性
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 限制服务
participant DB as 数据库
Client->>Controller : 发送请求(IP,设备ID,卡密)
Controller->>Service : 获取商户限制策略
Service-->>Controller : 返回策略
Controller->>Service : 检查卡密限制
Service-->>Controller : 检查结果
alt 卡密受限
Controller->>Client : 拒绝访问
else
Controller->>Service : 检查设备限制
Service-->>Controller : 检查结果
alt 设备受限
Controller->>Client : 拒绝访问
else
Controller->>Service : 检查代理使用
Service-->>Controller : 检查结果
alt 使用代理
Controller->>Client : 拒绝访问
else
Controller->>Service : 检查IP限制
Service-->>Controller : 检查结果
alt IP受限
Controller->>Client : 拒绝访问
else
Controller->>Client : 允许访问
end
end
end
end
Controller->>Service : 记录限制结果
```
**Diagram sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L35-L65)
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
## 配置方法与生效流程
### 配置方法
IP限制的配置主要通过商户部署策略进行包含以下可配置项
- `IsRestrictCardPass`: 是否启用卡密限制
- `IsRestrictDevice`: 是否启用设备限制
- `IsRestrictAgent`: 是否启用代理检测
- `IsRestrictIp`: 是否启用IP限制
- `IsRestrictInternalIp`: 是否限制内网IP
- `RestrictArea`: 允许访问的省份/地区列表
### 生效流程
1. **请求接收**系统接收到包含IP设备ID卡密等信息的请求
2. **策略获取**从商户部署配置中获取当前的限制策略
3. **逐项检查**按照预设顺序检查各项限制条件
4. **结果记录**无论允许或拒绝都将结果记录到数据库
5. **响应返回**向客户端返回访问结果
系统使用事务性操作确保数据一致性在检查过程中如果发现需要限制的情况会立即终止后续检查并返回拒绝结果
```mermaid
flowchart TD
A[接收请求] --> B[获取商户策略]
B --> C[检查卡密限制]
C --> D{卡密受限?}
D --> |是| E[记录拒绝]
D --> |否| F[检查设备限制]
F --> G{设备受限?}
G --> |是| E
G --> |否| H[检查代理使用]
H --> I{使用代理?}
I --> |是| E
I --> |否| J[检查IP限制]
J --> K{IP受限?}
K --> |是| E
K --> |否| L[检查内网IP]
L --> M{内网IP且不禁用?}
M --> |是| N[记录允许]
M --> |否| O[检查区域限制]
O --> P{在允许区域?}
P --> |是| N
P --> |否| E
E --> Q[返回拒绝]
N --> R[返回允许]
```
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L35-L65)
## 缓存机制与查询优化
### 缓存机制
系统虽然没有显式的缓存层但通过以下方式实现高效的查询性能
1. **数据库索引优化**在关键字段上建立索引包括IP地址设备ID卡密等
2. **连接池管理**使用数据库连接池减少连接开销
3. **对象复用**通过GoFrame框架的ORM功能复用数据库查询对象
### 查询优化
1. **IP记录查询优化**
- 使用`GetOrSetIPRecord`方法实现查询和创建的一体化
- 对已存在的IP记录直接返回避免重复查询
- 对公网IP才进行地理位置查询减少外部服务调用
2. **设备关联查询优化**
- 使用会话IDSessionId批量关联IP和设备信息
- 通过事务确保数据一致性
- 提供`CheckIsDeviceUseProxy`方法快速判断代理使用情况
3. **批量查询支持**
- 提供`GetRestrictRecordByCardPass``GetRestrictRecordByIP`方法支持按卡密或IP批量查询限制记录
- 使用ORM的Scan功能直接映射到结构体减少数据转换开销
系统通过合理的数据库设计和查询逻辑确保在大规模IP数据情况下仍能保持快速的查询性能
**Section sources**
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L1-L55)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L114)
- [restriction.go](file://internal/service/restriction.go#L35-L65)
## 查询接口说明
系统提供了多个查询接口用于IP限制相关的数据检索
### 主要查询接口
1. **IP记录查询**
- 方法`GetOrSetIPRecord`
- 功能获取或创建IP记录
- 参数IP地址
- 返回IP记录信息及地理位置数据
2. **限制存在性检查**
- 方法`IsRestrictExistByCardPass`
- 功能检查指定卡密是否存在限制记录
- 参数卡密
- 返回布尔值
- 方法`IsRestrictExistByIP`
- 功能检查指定IP是否存在限制记录
- 参数IP地址
- 返回布尔值
3. **记录批量查询**
- 方法`GetRestrictRecordByCardPass`
- 功能获取指定卡密的所有限制记录
- 参数卡密
- 返回限制记录列表
- 方法`GetRestrictRecordByIP`
- 功能获取指定IP的所有限制记录
- 参数IP地址
- 返回包含IP记录的限制记录列表
4. **区域检查**
- 方法`CheckIPIsAllowed`
- 功能检查IP是否在允许的区域内
- 参数IP地址允许区域列表
- 返回是否允许访问
这些接口通过服务层统一暴露控制器可以直接调用确保了接口的一致性和安全性
**Section sources**
- [restriction.go](file://internal/service/restriction.go#L35-L65)
- [ip_record.go](file://internal/logic/restriction/ip_record.go#L1-L55)
## 最佳实践与使用场景
### 最佳实践
1. **合理配置限制策略**根据业务需求选择合适的限制维度避免过度限制影响正常用户
2. **定期清理过期记录**设置适当的数据保留策略定期清理不再需要的限制记录
3. **监控限制触发情况**建立监控系统及时发现异常的限制触发模式
4. **灰度发布新策略**新限制策略应先在小范围用户中测试确认无误后再全面推广
### 使用场景示例
#### 防止恶意爬虫
通过启用IP限制和代理检测可以有效识别和阻止爬虫行为
- 检测到使用代理的请求自动限制
- 对短时间内频繁访问的IP进行限制
- 结合设备ID识别伪装的爬虫
#### 限制异常登录
保护用户账户安全
- 对多次登录失败的IP进行临时限制
- 检测异地登录行为要求额外验证
- 限制同一账号在多设备上的并发登录
#### 区域访问控制
满足业务合规要求
- 仅允许特定省份的用户访问服务
- 阻止来自高风险地区的访问
- 为不同地区用户提供差异化服务
#### 卡密安全保护
防止卡密滥用
- 一个卡密只能在有限的设备上使用
- 检测卡密的异常使用模式
- 对疑似泄露的卡密立即限制
这些场景展示了IP限制机制在实际业务中的灵活应用通过组合不同的限制维度可以构建多层次的安全防护体系
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L35-L65)
## 与其他安全机制的集成
IP限制机制与系统的其他安全组件紧密集成形成完整的安全防护体系
### 与登录频率限制的集成
1. **协同工作模式**
- 登录频率限制检测到异常登录行为
- 触发IP限制机制将相关IP加入黑名单
- 后续来自该IP的所有请求都被阻止
2. **数据共享**
- 共用设备ID和IP地址信息
- 登录日志作为IP限制的决策依据
- 限制结果反馈给登录系统用于风险评估
### 与商户部署策略的集成
1. **策略驱动**
- 商户可以自定义IP限制策略
- 不同商户可以有不同的安全要求
- 策略变更实时生效
2. **差异化服务**
- 高风险商户启用更严格的限制
- 信任商户可以放宽某些限制条件
- 根据商户等级动态调整安全策略
### 与设备指纹的集成
1. **设备识别**
- 结合User Agent和设备型号生成设备指纹
- 识别伪装的设备和浏览器
- 检测自动化工具的使用
2. **行为分析**
- 跟踪设备的访问模式
- 识别异常的行为特征
- 提前预警潜在的安全威胁
这种深度集成使得IP限制不仅仅是简单的IP黑名单而是成为智能安全决策系统的重要组成部分能够根据上下文信息做出更精准的访问控制决策
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L1-L70)
- [restriction.go](file://internal/service/restriction.go#L35-L65)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L114)

View File

@@ -0,0 +1,229 @@
# IP限制策略
<cite>
**本文档引用文件**
- [restriction.go](file://api/restriction/restriction.go)
- [restriction.go](file://internal/controller/restriction/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/consts/restriction.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [model.go](file://internal/model/restriction.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [rate.go](file://utility/limiter/rate.go)
</cite>
## 目录
1. [简介](#简介)
2. [IP限制策略配置机制](#ip限制策略配置机制)
3. [策略生效流程与优先级规则](#策略生效流程与优先级规则)
4. [与其他安全策略的协同工作](#与其他安全策略的协同工作)
5. [动态策略调整机制](#动态策略调整机制)
6. [业务场景配置示例与最佳实践](#业务场景配置示例与最佳实践)
## 简介
本文档详细阐述kami_backend系统的IP限制策略涵盖黑白名单机制封禁时长设置例外规则配置策略优先级与地域限制等安全策略的协同机制以及基于系统负载或安全事件的动态调整能力通过本策略系统可有效防止恶意访问异常请求和资源滥用保障服务稳定性和数据安全性
## IP限制策略配置机制
### 黑白名单定义
系统通过数据库表`restrict_ip_order_access`实现IP黑白名单机制当IP被标记为限制状态`RestrictStatus_Disable`即进入黑名单反之则为白名单黑白名单的判定基于以下字段
- `ip`: 被限制的IP地址
- `status`: 状态值0表示启用白名单1表示禁用黑名单
- `cardPass`: 关联卡密实现基于卡密的IP限制
- `deviceId`: 设备ID支持设备级封禁
黑白名单记录通过`AddToRestrictIP`接口写入`V1RestrictIpOrderAccess` DAO操作数据库
**Section sources**
- [restriction.go](file://internal/service/restriction.go#L31-L31)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go#L21-L23)
- [v_1_restrict_ip_order_access.go](file://internal/model/entity/v_1_restrict_ip_order_access.go#L11-L23)
### 封禁时长设置
系统当前采用永久封禁机制封禁状态一旦设置将持续有效直至手动解除封禁记录存储在`restrict_ip_order_access`表中通过`status`字段控制未来可通过扩展`expire_at`字段实现临时封禁功能
封禁操作由`SetCurrentOrderDisable`方法执行支持事务处理确保订单状态与IP限制状态的一致性
**Section sources**
- [restriction.go](file://internal/logic/restriction/restriction.go#L64-L74)
- [restriction.go](file://internal/service/restriction.go#L27-L27)
### 例外规则配置
系统支持多种例外规则配置允许特定IP或场景绕过限制
1. **内网IP例外**`IsRestrictInternalIp`为false时内网IPRFC1918自动放行
2. **策略开关控制**通过`MerchantDeployInfo`中的`IsRestrictCardPass``IsRestrictDevice`等布尔字段控制不同维度的限制是否启用
3. **区域白名单**通过`RestrictArea`字段配置允许访问的省份列表非列表内IP将被拒绝
例外规则在`CheckIPAllowed`逻辑中统一处理确保按优先级顺序执行
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L35-L55)
## 策略生效流程与优先级规则
### 策略生效流程
IP限制策略的生效流程如下
1. 接收客户端请求获取IP设备ID卡密等信息
2. 查询商户部署策略`MerchantDeployInfo`
3. 按优先级依次检查各项限制条件
4. 记录本次检查结果到`restrict_ip_order_access`
5. 返回是否允许访问的结果
```mermaid
flowchart TD
Start([开始]) --> GetStrategy["获取商户限制策略"]
GetStrategy --> CheckCardPass{"卡密限制启用?"}
CheckCardPass --> |是| CheckCardPassExist["检查卡密是否存在限制记录"]
CheckCardPassExist --> |存在| ReturnFalse["返回拒绝"]
CheckCardPass --> |否| CheckDevice{"设备限制启用?"}
CheckDevice --> |是| CheckDeviceExist["检查设备是否存在限制记录"]
CheckDeviceExist --> |存在| ReturnFalse
CheckDevice --> |否| CheckAgent{"代理限制启用?"}
CheckAgent --> |是| CheckProxy["检查是否使用代理"]
CheckProxy --> |是| ReturnFalse
CheckAgent --> |否| CheckPublicIP{"是否公网IP?"}
CheckPublicIP --> |是| CheckIPIsExist["检查IP是否存在限制记录"]
CheckIPIsExist --> |存在| ReturnFalse
CheckPublicIP --> |否| CheckInternalIP{"内网IP限制启用?"}
CheckInternalIP --> |否| ReturnTrue["返回允许"]
CheckInternalIP --> |是| CheckArea{"区域限制配置?"}
CheckArea --> |是| CheckAreaAllowed["检查IP所在省份是否在允许列表"]
CheckAreaAllowed --> |是| ReturnTrue
CheckAreaAllowed --> |否| ReturnFalse
CheckArea --> |否| ReturnTrue
ReturnTrue --> End([结束])
ReturnFalse --> End
```
**Diagram sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L15-L68)
### 优先级规则
策略检查遵循严格的优先级顺序
1. 卡密级限制最高优先级
2. 设备级限制
3. 代理检测限制
4. IP级限制
5. 内网IP例外规则
6. 地域限制最低优先级
此优先级设计确保了更精细的控制策略优先于通用策略避免例外情况被错误拦截
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L30-L55)
## 与其他安全策略的协同工作
### 与地域限制的协同
IP限制策略与地域限制通过`CheckIPIsAllowed`方法协同工作系统首先通过IP地理位置服务获取IP所在省份然后与配置的`RestrictArea`列表进行比对若IP省份不在允许列表中则判定为不允许访问
地域判断支持中英文自动转换使用拼音库将中文省份名转换为英文进行匹配确保国际化环境下的准确性
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "RestrictionController"
participant Service as "RestrictionService"
participant DAO as "V1RestrictIpRecordDAO"
Client->>Controller : CheckIPAllowed(IP, OrderNo)
Controller->>Service : GetRestrictStrategy(MerchantDeployID)
Service-->>Controller : Strategy
Controller->>Service : CheckIPIsAllowed(IP, Strategy.RestrictArea)
Service->>Service : IsInProvince(IP, RestrictArea)
Service->>DAO : Query IP Record
DAO-->>Service : IP Province
Service->>Service : Compare with RestrictArea
Service-->>Controller : IsAllowed
Controller->>Service : AddToRestrictIP(Result)
Controller-->>Client : Response
```
**Diagram sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L50-L53)
- [restriction.go](file://internal/logic/restriction/restriction.go#L98-L128)
### 与设备指纹的协同
系统通过`deviceId`实现设备级限制与IP限制形成多维度防护`IsRestrictDevice`启用时即使IP变化只要设备ID被封禁访问仍会被拒绝设备信息由`RestrictionDeviceInput`结构体收集包含设备型号UserAgent等特征
**Section sources**
- [restriction.go](file://internal/model/restriction.go#L6-L14)
- [restriction.go](file://internal/logic/restriction/restriction.go#L168-L173)
## 动态策略调整机制
### 基于系统负载的调整
虽然当前代码未直接实现基于系统负载的动态调整但系统架构支持通过外部监控模块集成实现可通过`SimpleLimiter`限流器位于`utility/limiter/rate.go`作为基础组件当系统负载过高时动态收紧IP限制策略
- 临时启用内网IP限制
- 缩小允许访问的地域范围
- 降低请求频率阈值
```mermaid
classDiagram
class SimpleLimiter {
+Cap int
+Expire int
+rate []*simpleRateNode
+Allow(key string) bool
+checkAvailable() void
}
class Type {
+CardInfoJdAccountCookieChecker Type
+CardInfoRedeemAccountCookieChecker Type
}
SimpleLimiter --> Type : "使用"
```
**Diagram sources**
- [rate.go](file://utility/limiter/rate.go#L12-L70)
### 基于安全事件的调整
系统可通过分析`restrict_ip_record`表中的异常访问模式自动触发安全响应例如当检测到某个IP在短时间内频繁尝试不同卡密时可自动调用`AddToRestrictIP`将其加入黑名单
安全事件响应可通过定时任务或实时流处理系统实现结合`GetRestrictRecordByIP``IsRestrictExistByIP`等查询接口进行模式识别
**Section sources**
- [restriction.go](file://internal/service/restriction.go#L45-L47)
- [restriction.go](file://internal/logic/restriction/restriction.go#L148-L158)
## 业务场景配置示例与最佳实践
### 高安全性业务场景
对于金融支付等高安全性要求的业务推荐配置
```json
{
"IsRestrictCardPass": true,
"IsRestrictDevice": true,
"IsRestrictAgent": true,
"IsRestrictIp": true,
"IsRestrictInternalIp": true,
"RestrictArea": ["北京", "上海", "广东"]
}
```
此配置实现卡密设备代理IP四重验证并限制仅允许特定省份访问
### 开放性业务场景
对于需要广泛访问的开放平台推荐配置
```json
{
"IsRestrictCardPass": true,
"IsRestrictDevice": false,
"IsRestrictAgent": false,
"IsRestrictIp": false,
"IsRestrictInternalIp": false,
"RestrictArea": []
}
```
此配置仅对卡密进行限制允许任意设备IP和地域访问适合公开API服务
### 最佳实践指南
1. **分阶段实施**先启用卡密限制再逐步增加其他维度限制
2. **监控与审计**定期分析`restrict_ip_order_access`识别误封情况
3. **例外管理**为运维测试预留白名单IP段
4. **性能考虑**避免过度复杂的限制规则影响请求处理性能
5. **用户通知**当用户被限制时提供清晰的错误信息和申诉渠道
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L15-L68)
- [restriction.go](file://internal/logic/restriction/restriction.go#L46-L62)

View File

@@ -0,0 +1,321 @@
# 地域限制机制
<cite>
**本文档引用文件**
- [province.go](file://api/restriction/v1/province.go)
- [collection.go](file://api/restriction/v1/collection.go)
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
- [consts.go](file://utility/integration/restriction/consts.go)
- [impl.go](file://utility/integration/restriction/impl.go)
- [models.go](file://utility/integration/restriction/models.go)
</cite>
## 目录
1. [引言](#引言)
2. [核心数据结构与接口定义](#核心数据结构与接口定义)
3. [地理位置查询机制](#地理位置查询机制)
4. [省份限制规则配置与管理](#省份限制规则配置与管理)
5. [地域限制查询接口](#地域限制查询接口)
6. [IP地址解析与匹配流程](#ip地址解析与匹配流程)
7. [生效流程与执行逻辑](#生效流程与执行逻辑)
8. [与其他风控措施的协同机制](#与其他风控措施的协同机制)
9. [最佳实践与应用场景](#最佳实践与应用场景)
10. [总结](#总结)
## 引言
地域限制机制是kami_backend系统中用于实现基于地理位置访问控制的核心风控模块该机制通过解析用户IP地址获取其地理位置信息并依据预设的省份限制规则判断是否允许访问特定服务本机制广泛应用于区域化服务控制合规性要求满足等场景有效防止跨区域非法操作提升系统安全性和业务合规性
## 核心数据结构与接口定义
### 请求与响应结构
系统定义了标准化的API请求与响应结构用于地域限制相关操作
```mermaid
classDiagram
class QueryAllProvinceReq {
+string path : /restriction/location/getAllProvince
+string method : GET
+string summary : 获取所有的地理位置
}
class QueryAllProvinceRes {
+[]string List
}
class CheckIPAllowedReq {
+string Ip
+string DeviceId
+uint MerchantDeployID
+string OrderNo
+string CardPass
}
class CheckIPAllowedRes {
+bool IsAllowed
}
QueryAllProvinceReq --> QueryAllProvinceRes : "响应"
CheckIPAllowedReq --> CheckIPAllowedRes : "响应"
```
**图示来源**
- [province.go](file://api/restriction/v1/province.go#L1-L28)
**本节来源**
- [province.go](file://api/restriction/v1/province.go#L1-L28)
## 地理位置查询机制
### 多源IP定位服务
系统集成多个第三方IP地理位置查询服务确保定位结果的准确性与可靠性采用随机轮询策略调用不同服务商接口并在失败时自动重试
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Service as "GetLocationByIP"
participant Provider as "第三方服务商"
Client->>Service : QueryLocationByIP(ctx, ip)
Service->>Service : 随机选择实现
loop 所有服务商
Service->>Provider : 调用QueryLocationByIP
Provider-->>Service : 返回地理位置
alt 城市信息存在
Service-->>Client : 返回结果
break 成功
end
end
alt 所有调用失败
Service-->>Client : 抛出“ip location not found”错误
end
```
**图示来源**
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
- [impl.go](file://utility/integration/restriction/impl.go#L0-L239)
**本节来源**
- [location.go](file://utility/integration/restriction/location.go#L0-L38)
- [impl.go](file://utility/integration/restriction/impl.go#L0-L239)
### 支持的服务商列表
系统当前支持以下IP地理位置查询服务商
- CSDN
- PCOnline
- OlTools
- IdCd
- MeiTu
- Vo
- DBIP
- QJQQ
- IQIYI
- IP66
每个服务商通过独立的客户端实现`Location`接口统一由工厂模式管理
## 省份限制规则配置与管理
### 全国省份列表
系统内置完整的中国省级行政区划列表包含34个省级单位涵盖大陆港澳台及海外特殊标识
```go
var AllProvinceList = []string{
"北京市", "天津市", "河北省", "山西省", "内蒙古自治区",
"辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省",
"浙江省", "安徽省", "福建省", "江西省", "山东省",
"河南省", "湖北省", "湖南省", "广东省", "广西壮族自治区",
"海南省", "重庆市", "四川省", "贵州省", "云南省",
"西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏回族自治区",
"新疆维吾尔自治区", "香港特别行政区", "澳门特别行政区", "台湾省", "海外",
}
```
**本节来源**
- [consts.go](file://utility/integration/restriction/consts.go#L0-L24)
### 限制策略配置
省份限制规则作为商户部署策略的一部分进行配置`MerchantDeployInfo`服务管理限制策略包含以下字段
- `IsRestrictIp`: 是否启用IP地域限制
- `RestrictArea`: 限制的省份列表
- `IsRestrictInternalIp`: 是否限制内网IP
- 其他关联风控规则设备卡密代理等
## 地域限制查询接口
### 获取全部省份接口
提供RESTful API供前端或外部系统获取系统支持的所有省份列表
```mermaid
flowchart TD
A[HTTP GET请求] --> B[/restriction/location/getAllProvince]
B --> C{调用QueryAllProvince}
C --> D[service.Restriction().GetAllProvince(ctx)]
D --> E[返回省份列表]
E --> F[HTTP 200 OK + 省份数组]
```
**图示来源**
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go#L0-L15)
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
**本节来源**
- [restriction_v1_query_all_province.go](file://internal/controller/restriction/restriction_v1_query_all_province.go#L0-L15)
### 检查IP是否允许接口
核心接口用于在业务流程中实时判断某IP是否被允许访问
```mermaid
flowchart TD
A[HTTP GET请求] --> B[/restriction/location/checkIPAllowed]
B --> C{调用CheckIPAllowed}
C --> D[获取商户部署限制策略]
D --> E{策略存在?}
E --> |否| F[返回内部错误]
E --> |是| G{各项限制条件检查}
G --> H[卡密限制]
G --> I[设备限制]
G --> J[代理限制]
G --> K[IP黑名单]
G --> L[内网IP处理]
G --> M[省份区域限制]
H --> N{是否触发限制?}
I --> N
J --> N
K --> N
L --> N
M --> N
N --> |是| O[IsAllowed = false]
N --> |否| P[IsAllowed = true]
P --> Q[记录访问日志]
O --> Q
Q --> R[返回响应]
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
## IP地址解析与匹配流程
### IP地理位置解析流程
系统通过`GetLocationByIP`函数获取IP对应的地理位置信息该函数会
1. 随机选择一个服务商客户端
2. 发起HTTP请求查询IP信息
3. 解析返回数据并标准化为统一`Response`结构
4. 若城市为空则视为查询失败并重试其他服务商
### 中英文省份匹配
为兼容可能返回英文省份名称的服务商系统实现拼音转换匹配机制
```go
// 当IP返回英文省份时
if validator.IsAlpha(ipRecord.IpProvince) {
ipRecord.IpProvince = gstr.ToLower(ipRecord.IpProvince)
// 将待查省份转为拼音小写
slice.ForEach(provinceCopier, func(index int, item string) {
provinceCopier[index] = gstr.ToLower(pinyin.NewDict().Convert(item, "").None())
})
// 将全部省份列表转为拼音小写
slice.ForEachConcurrent(allProvinceListCopier, func(index int, item string) {
allProvinceListCopier[index] = gstr.ToLower(pinyin.NewDict().Convert(item, "").None())
}, 5)
}
```
**本节来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L85-L112)
### 海外地区特殊处理
系统对海外这一特殊区域进行专门判断
- 若限制规则包含海外
- 且IP所在省份不在中国34个省级单位内
- 则判定为属于限制区域返回`true`
## 生效流程与执行逻辑
### 完整判断流程
当调用`CheckIPIsAllowed`系统执行以下逻辑
1. 调用`IsInProvince`判断IP是否在指定省份内
2. **不在**指定省份内`IsAllowed = true`白名单逻辑
3. 否则`IsAllowed = false`
### 访问记录持久化
每次检查后系统通过`defer`机制自动记录本次访问结果到数据库
- 写入`v1_restrict_ip_order_access`
- 关联IP记录设备ID订单号卡密等信息
- 更新订单封单状态
该机制确保所有访问行为可追溯便于后续审计与分析
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
## 与其他风控措施的协同机制
### 综合风控策略执行
地域限制并非孤立运行而是作为综合风控策略的一部分与其他限制条件共同决策
```mermaid
graph TD
A[开始检查] --> B{卡密限制启用?}
B --> |是| C{卡密已限制?}
C --> |是| D[拒绝访问]
B --> |否| E{设备限制启用?}
E --> |是| F{设备已限制?}
F --> |是| D
E --> |否| G{代理限制启用?}
G --> |是| H{使用代理?}
H --> |是| D
G --> |否| I{IP限制启用?}
I --> |是| J{IP在黑名单?}
J --> |是| D
I --> |否| K{内网IP?}
K --> |是| L{限制内网IP?}
L --> |否| M[允许访问]
K --> |否| N{省份限制启用?}
N --> |是| O{IP在允许区域?}
O --> |是| M
O --> |否| D
N --> |否| M
D --> P[记录日志]
M --> P
P --> Q[返回结果]
```
**图示来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
**本节来源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L0-L69)
### 协同工作特点
- **短路判断**任一条件触发即拒绝提高效率
- **统一入口**所有风控由`CheckIPAllowed`统一调度
- **数据联动**共享限制状态与访问记录
- **策略可配置**各风控开关独立配置灵活组合
## 最佳实践与应用场景
### 区域化服务控制
- **场景**某商户仅允许江苏省内用户购买
- **配置**`RestrictArea = ["江苏省"]`, `IsRestrictIp = true`
- **效果**非江苏IP用户提交订单时被拒绝
### 合规性要求满足
- **场景**金融类产品需遵守属地监管要求
- **配置**按监管区域设置允许省份列表
- **效果**确保服务仅对合规区域用户提供
### 防止跨区套利
- **场景**不同地区定价策略不同防止用户跨区购买
- **配置**结合卡密限制与地域限制
- **效果**同一卡密只能在固定区域使用
### 内网访问策略
- **场景**测试环境允许内网访问生产环境严格限制
- **配置**`IsRestrictInternalIp = false`
- **效果**内网IP自动放行无需配置具体省份
## 总结
kami_backend的地域限制机制通过多源IP定位灵活的省份规则配置高效的匹配算法以及与其他风控措施的深度协同构建了一套完整可靠的基于地理位置的访问控制系统该机制不仅满足了基本的区域访问控制需求还通过精细化的策略配置支持了多样化的业务场景为系统的安全性与合规性提供了有力保障

View File

@@ -0,0 +1,73 @@
# 设备ID匹配算法
<cite>
**本文档引用的文件**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/model/restriction.go)
- [v_1_restrict_client_access_record.go](file://internal/model/do/v_1_restrict_client_access_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/model/do/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go)
</cite>
## 目录
1. [简介](#简介)
2. [设备ID匹配实现逻辑](#设备id匹配实现逻辑)
3. [性能优化策略](#性能优化策略)
4. [匹配结果判定与置信度评估](#匹配结果判定与置信度评估)
5. [匹配失败处理与异常应对](#匹配失败处理与异常应对)
6. [算法评估方法](#算法评估方法)
7. [结论](#结论)
## 简介
本系统中的设备ID匹配算法主要用于识别和管理用户访问设备通过收集和分析设备IDIP地址用户代理等信息实现对设备行为的监控与限制该机制在防止滥用保障系统安全方面发挥关键作用设备信息的采集与匹配贯穿于用户请求处理流程中结合数据库持久化与逻辑判断形成完整的设备识别体系
## 设备ID匹配实现逻辑
设备ID匹配主要通过精确匹配方式实现系统在用户请求时收集设备ID设备型号UserAgent及IP列表等信息并进行持久化存储匹配过程涉及设备信息的保存与查询两个核心环节系统首先将设备ID作为访问标识VisitorId记录到`restrict_client_access_record`表中同时关联IP访问记录当需要判断某设备是否受限时系统会查询`restrict_ip_order_access`表中是否存在该设备ID的禁用状态记录
设备信息的采集由控制器`restriction_v1_user_info_collection.go`处理接收到前端传入的设备信息后经由服务层调用逻辑层方法进行存储匹配逻辑主要体现在`IsRestrictDevice`方法中该方法通过查询数据库中是否存在指定设备ID且状态为禁用的记录来判断设备是否受限
**本节内容来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L33)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
## 性能优化策略
系统在设备ID匹配过程中采用了事务处理和批量操作等优化策略在保存设备信息时使用数据库事务确保设备访问记录和IP关联关系的一致性写入对于IP关联的存储系统采用循环批量插入的方式将多个IP地址与同一访问会话关联提高写入效率
虽然当前实现中未明确使用布隆过滤器或哈希索引等高级数据结构但通过数据库层面的索引优化如对`visitor_id``ip`字段建立索引来加速查询操作`GetOrSetAccessRecord`方法中通过先查询后插入的逻辑避免了重复数据的产生减少了不必要的数据库写入
**本节内容来源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
## 匹配结果判定与置信度评估
匹配结果的判定基于数据库中是否存在禁用状态的记录`IsRestrictDevice`方法返回布尔值表示设备是否被限制该判定逻辑简单直接置信度较高因为其依赖于明确的数据库记录而非概率性算法
系统通过`CheckIsDeviceUseProxy`方法进一步评估设备行为的可信度该方法通过分析设备使用代理的情况来判断访问的真实性如果设备在使用特定IP访问时被识别为使用代理则可能被视为可疑行为这种基于行为模式的分析为设备识别提供了额外的置信度评估维度
**本节内容来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L154-L172)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L89-L113)
## 匹配失败处理与异常应对
系统对匹配过程中的异常情况进行了妥善处理在数据库操作中使用`utils.HandleNoRowsError`方法处理查询无结果的情况避免因空指针异常导致服务中断事务机制确保了数据操作的原子性即使在部分操作失败时也能回滚到一致状态
对于设备信息采集过程中的潜在问题如IP列表为空或设备ID缺失系统通过结构体字段的默认值和空值检查来保证程序的健壮性`SaveDeviceInfo`方法中任何一步操作失败都会导致整个事务回滚防止产生不完整或错误的数据记录
**本节内容来源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
- [restriction.go](file://internal/logic/restriction/restriction.go#L0-L173)
## 算法评估方法
设备ID匹配算法的准确率可通过统计实际受限设备与系统识别出的受限设备之间的吻合度来评估误判率则可通过分析被错误标记为受限的正常设备数量来计算由于系统采用精确匹配而非模糊匹配或相似度计算理论上误判率应接近于零除非存在数据录入错误或业务逻辑变更
可以通过定期审计`restrict_ip_order_access`表中的记录验证设备限制策略的执行效果同时监控`CheckIsDeviceUseProxy`方法的返回结果分布可以评估代理检测算法的有效性这些评估指标应结合业务场景的实际需求进行综合考量
**本节内容来源**
- [restriction.go](file://internal/logic/restriction/restriction.go#L154-L172)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L89-L113)
## 结论
kami_backend系统的设备ID匹配算法以精确匹配为核心通过采集设备IDIP地址等信息并持久化存储实现了对设备行为的有效监控系统采用事务处理保证数据一致性通过合理的数据库查询实现高效的设备状态判定尽管未采用复杂的模糊匹配或相似度计算算法但其设计简洁可靠能够满足当前业务场景下的设备识别需求未来可考虑引入更高级的设备指纹技术以提高识别精度

View File

@@ -0,0 +1,242 @@
# 设备ID存储策略
<cite>
**本文档中引用的文件**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [restriction.go](file://internal/model/restriction.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [cache.go](file://utility/cache/cache.go)
- [consts.go](file://utility/cache/consts.go)
</cite>
## 目录
1. [简介](#简介)
2. [数据库表结构设计](#数据库表结构设计)
3. [设备ID与其他限制条件的关联关系](#设备id与其他限制条件的关联关系)
4. [性能优化措施](#性能优化措施)
5. [存储容量规划与数据清理策略](#存储容量规划与数据清理策略)
6. [数据安全性与访问控制](#数据安全性与访问控制)
7. [结论](#结论)
## 简介
本系统通过设备ID记录机制实现对用户访问行为的追踪与限制管理设备ID作为核心标识与IP地址用户代理等信息共同构成访问控制策略的基础系统采用数据库持久化存储结合Redis缓存的方式确保数据的高可用性和访问效率设备信息在用户每次请求时被采集并记录用于后续的风险识别反欺诈分析和访问权限控制
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L1-L33)
## 数据库表结构设计
### 设备访问记录表 (restrict_client_access_record)
该表用于存储设备的基本访问信息是设备ID存储的核心表
| 字段名 | 类型 | 是否主键 | 允许为空 | 默认值 | 说明 |
|--------|------|----------|----------|--------|------|
| id | int64 | | | 自增 | 主键ID |
| visitor_id | varchar(255) | | | | 设备ID唯一标识客户端设备 |
| device_model | varchar(255) | | | null | 设备型号 |
| user_agent | text | | | null | 用户代理字符串 |
| is_use_proxy | tinyint(1) | | | 0 | 是否使用代理0:, 1: |
| created_at | datetime | | | 当前时间 | 创建时间 |
| updated_at | datetime | | | null | 更新时间 |
| deleted_at | datetime | | | null | 软删除时间戳 |
```mermaid
erDiagram
restrict_client_access_record {
int64 id PK
varchar255 visitor_id
varchar255 device_model
text user_agent
tinyint1 is_use_proxy
datetime created_at
datetime updated_at
datetime deleted_at
}
```
**Diagram sources**
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L33-L73)
### 设备IP关联表 (restrict_client_access_ip_relation)
该表用于记录设备与IP地址的关联关系支持多IP追踪
| 字段名 | 类型 | 是否主键 | 允许为空 | 默认值 | 说明 |
|--------|------|----------|----------|--------|------|
| id | int64 | | | 自增 | 主键ID |
| ip | varchar(45) | | | | IP地址支持IPv4/IPv6 |
| is_remote_ip | tinyint(1) | | | 0 | 是否为远程真实IP0:代理IP, 1:真实IP |
| restrict_ip_record_id | int64 | | | | 外键指向IP记录表 |
| restrict_client_access_record_id | int64 | | | | 外键指向设备访问记录表 |
| session_id | varchar(64) | | | | 会话ID用于关联同一次访问的多个IP |
```mermaid
erDiagram
restrict_client_access_ip_relation {
int64 id PK
varchar45 ip
tinyint1 is_remote_ip
int64 restrict_ip_record_id FK
int64 restrict_client_access_record_id FK
varchar64 session_id
}
```
**Diagram sources**
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go#L33-L73)
### 索引策略
为确保查询性能系统在关键字段上建立了索引
```sql
-- 设备ID索引高频查询
CREATE INDEX idx_visitor_id ON restrict_client_access_record(visitor_id);
-- IP地址索引用于IP限制检查
CREATE INDEX idx_ip ON restrict_client_access_ip_relation(ip);
-- 复合索引(用于会话关联查询)
CREATE INDEX idx_session_access ON restrict_client_access_ip_relation(session_id, restrict_client_access_record_id);
-- 创建时间索引(用于数据清理)
CREATE INDEX idx_created_at ON restrict_client_access_record(created_at);
```
**Section sources**
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L33-L73)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go#L33-L73)
## 设备ID与其他限制条件的关联关系
### 与IP地址的关联
系统通过`restrict_client_access_ip_relation`表建立设备ID与IP地址的多对多关系当用户访问时系统会记录所有相关的IP地址包括代理链中的多个IP和真实的远程IP通过`is_remote_ip`字段区分真实IP和代理IP并通过`session_id`将同一次访问的所有IP关联起来
```mermaid
flowchart TD
A[客户端请求] --> B{获取IP列表}
B --> C[遍历所有IP]
C --> D[保存IP记录]
D --> E[创建IP关联关系]
E --> F[标记真实IP]
F --> G[生成会话ID关联]
G --> H[完成设备信息存储]
```
**Diagram sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
### 与用户行为的关联
设备ID与用户行为通过访问记录进行关联系统在`SaveDeviceInfo`方法中将设备ID设备型号UserAgent等信息与访问行为绑定当需要判断设备是否受限时系统会查询`restrict_client_access_record`表中该设备ID的状态
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 限制服务
participant DB as 数据库
Client->>Controller : 提交设备信息
Controller->>Service : SaveDeviceInfo()
Service->>DB : 开启事务
Service->>DB : 查询或创建访问记录
Service->>DB : 插入IP关联记录
DB-->>Service : 返回结果
Service-->>Controller : 返回成功
Controller-->>Client : 响应结果
```
**Diagram sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
- [restriction.go](file://internal/logic/restriction/restriction.go#L17-L35)
### 存储周期
设备访问记录的存储周期由系统配置决定目前采用软删除机制已删除的记录保留在数据库中通过`deleted_at`字段标记删除时间历史数据清理任务会定期清理超过保留周期的记录
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L33-L73)
## 性能优化措施
### 分表策略
当前系统未实现分表策略所有设备记录存储在单表中考虑到未来数据量增长建议实施按时间分表策略如按月或按季度创建新表以提高查询性能和管理效率
### 缓存机制
系统采用Redis作为缓存层但设备ID记录本身未直接缓存缓存主要用于存储频繁访问的配置信息和临时状态对于设备ID的查询系统依赖数据库索引进行快速检索
```mermaid
flowchart LR
A[应用层] --> B{查询设备信息}
B --> C[数据库查询]
C --> D[使用索引扫描]
D --> E[返回结果]
E --> A
```
**Diagram sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
### 数据归档方案
系统目前未实现自动数据归档功能建议建立定期归档机制将超过一定时间如6个月的历史访问记录迁移到归档数据库或数据仓库中以减少主库压力归档数据可用于离线分析和审计
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L1-L44)
## 存储容量规划与数据清理策略
### 存储容量估算
根据当前业务规模单条设备访问记录约占用500字节存储空间按日均10万次访问计算年存储量约为18.25GB建议初始分配50GB存储空间并设置监控告警
### 数据清理策略
系统采用软删除+定期清理的策略
1. 正常业务中通过`deleted_at`字段标记删除记录
2. 后台任务定期执行物理删除清理超过保留周期建议90天的记录
3. 清理任务在低峰期执行避免影响业务性能
```go
// 伪代码:数据清理逻辑
func CleanExpiredRecords(ctx context.Context) {
expireTime := time.Now().AddDate(0, 0, -90) // 90天前
_, err := dao.V1RestrictClientAccessRecord.Ctx(ctx).
Where("created_at < ?", expireTime).
Delete()
if err != nil {
log.Error(ctx, "清理过期设备记录失败:", err)
}
}
```
**Section sources**
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L33-L73)
## 数据安全性与访问控制
### 数据加密
设备ID等敏感信息在传输过程中采用HTTPS加密存储层面数据库连接使用加密通道但设备ID本身未进行加密存储建议对设备ID进行哈希处理后再存储以增强数据安全性
### 访问控制
系统通过RBAC基于角色的访问控制模型管理数据访问权限访问控制策略定义在`rbac_model.conf`文件中通过Casbin实现细粒度的权限控制
```mermaid
graph TD
A[用户] --> B{权限检查}
B --> C[拥有访问权限?]
C --> |是| D[允许访问设备数据]
C --> |否| E[拒绝访问]
D --> F[记录访问日志]
E --> F
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L13)
### 安全审计
所有对设备数据的访问和修改操作都会被记录在系统日志中关键操作如设备禁用IP限制等都有详细的审计日志便于事后追溯和分析
**Section sources**
- [restriction.go](file://internal/logic/restriction/restriction.go#L139-L172)
## 结论
kami_backend系统的设备ID存储策略通过`restrict_client_access_record``restrict_client_access_ip_relation`两张表实现了设备信息的完整记录系统能够有效关联设备IDIP地址和其他访问信息为访问控制和风险识别提供数据支持虽然当前架构满足基本需求但在大规模场景下建议引入分表缓存和数据归档等优化措施并加强数据加密和访问控制以提升系统性能和安全性

View File

@@ -0,0 +1,268 @@
# 设备ID采集机制
<cite>
**本文档引用的文件**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go)
- [utils.go](file://utility/utils/utils.go)
- [v_1_restrict_client_access_record.go](file://internal/model/do/v_1_restrict_client_access_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/model/do/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go)
</cite>
## 目录
1. [简介](#简介)
2. [采集接口实现原理](#采集接口实现原理)
3. [数据传输格式与安全保护](#数据传输格式与安全保护)
4. [设备信息标准化处理](#设备信息标准化处理)
5. [隐私合规与数据最小化](#隐私合规与数据最小化)
6. [异常处理与降级策略](#异常处理与降级策略)
7. [数据库设计](#数据库设计)
## 简介
kami_backend系统实现了完整的设备ID采集机制用于收集和分析客户端设备信息该机制通过HTTP请求采集设备指纹浏览器特征和网络信息为系统安全用户行为分析和反欺诈提供基础数据支持采集过程注重隐私保护和数据最小化原则确保符合相关法律法规要求
## 采集接口实现原理
设备ID采集通过RESTful API接口实现客户端在初始化时发送加密的设备信息到服务器服务器端通过`restriction_v1_user_info_collection.go`中的`UserInfoCollection`方法处理采集请求
采集流程如下
1. 客户端收集设备信息并加密传输
2. 服务器解密并验证数据完整性
3. 提取HTTP请求中的实际IP地址
4. 比较采集IP与请求IP判断是否使用代理
5. 将设备信息存储到数据库
```mermaid
sequenceDiagram
participant Client as 客户端
participant Server as 服务器
participant DB as 数据库
Client->>Server : POST /v1/userInfoCollection
Server->>Server : 解密请求数据
Server->>Server : 验证签名完整性
Server->>Server : 获取客户端真实IP
Server->>Server : 检测代理使用情况
Server->>DB : 存储设备信息
DB-->>Server : 存储结果
Server-->>Client : 返回响应
```
**图示来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L31-L59)
**本节来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
## 数据传输格式与安全保护
### 数据传输格式
客户端采集的数据采用JSON格式并通过AES-CBC加密后进行Base64编码传输传输的数据结构包含以下字段
| 字段 | 类型 | 描述 |
|------|------|------|
| ips | 字符串数组 | 客户端采集到的所有IP地址 |
| deviceId | 字符串 | 设备唯一标识ID |
| deviceModel | 字符串 | 设备型号信息 |
| userAgent | 字符串 | 浏览器用户代理字符串 |
| sign | 字符串 | 数据签名用于验证完整性 |
### 安全保护措施
系统采用多层安全保护机制确保数据传输和存储的安全性
1. **传输加密**使用AES-CBC算法对敏感数据进行加密
2. **数据完整性验证**通过MD5签名验证数据未被篡改
3. **身份验证**结合设备ID和IP地址进行访问控制
4. **防重放攻击**通过会话ID和时间戳机制防止重放攻击
```mermaid
flowchart TD
A[原始设备数据] --> B[JSON序列化]
B --> C[MD5签名生成]
C --> D[添加签名字段]
D --> E[AES-CBC加密]
E --> F[Base64编码]
F --> G[HTTP传输]
G --> H[Base64解码]
H --> I[AES-CBC解密]
I --> J[JSON反序列化]
J --> K[签名验证]
K --> L[数据存储]
```
**图示来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L33)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L44)
**本节来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
## 设备信息标准化处理
### 特征提取
系统对采集到的设备信息进行标准化处理和特征提取主要包括
1. **IP地址分析**区分公网IP和私网IP识别IPv4和IPv6地址
2. **设备模型归类**将设备型号归类为PC移动设备等类别
3. **浏览器特征提取**从User-Agent中提取浏览器类型版本和操作系统信息
4. **代理检测**通过比较采集IP和请求IP判断是否使用代理或VPN
### 数据标准化
采集到的原始数据经过以下标准化处理
```mermaid
classDiagram
class RestrictionDeviceInput {
+[]string IPs
+string RemoteIP
+string DeviceID
+string DeviceModel
+string UserAgent
}
class V1RestrictClientAccessRecord {
+int Id
+string VisitorId
+string DeviceModel
+string UserAgent
+bool IsUseProxy
+*gtime.Time CreatedAt
+*gtime.Time UpdatedAt
+*gtime.Time DeletedAt
}
class V1RestrictClientAccessIpRelation {
+int Id
+string Ip
+bool IsRemoteIp
+int RestrictIpRecordId
+int RestrictClientAccessRecordId
+string SessionId
+*gtime.Time CreatedAt
+*gtime.Time UpdatedAt
+*gtime.Time DeletedAt
}
RestrictionDeviceInput --> V1RestrictClientAccessRecord : "转换"
RestrictionDeviceInput --> V1RestrictClientAccessIpRelation : "关联"
```
**图示来源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L44)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go#L0-L21)
**本节来源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
- [utils.go](file://utility/utils/utils.go#L0-L65)
## 隐私合规与数据最小化
### 隐私合规考虑
系统在设备信息采集过程中严格遵守隐私保护原则
1. **知情同意**在采集前明确告知用户并获取同意
2. **数据最小化**仅采集业务必需的最少信息
3. **目的限制**采集的数据仅用于安全验证和反欺诈等合法目的
4. **存储期限**设置合理的数据保留期限定期清理过期数据
### 数据最小化实现
系统通过以下方式实现数据最小化原则
- 仅采集必要的设备标识信息不收集个人身份信息
- 对IP地址进行适当脱敏处理
- 限制数据访问权限仅授权人员可访问
- 定期审计数据使用情况确保合规性
**本节来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
## 异常处理与降级策略
### 异常情况处理
系统对采集过程中的各种异常情况进行妥善处理
1. **解密失败**返回验证失败错误记录日志供分析
2. **签名验证失败**拒绝请求防止数据篡改
3. **数据解析失败**返回格式错误提示客户端重新发送
4. **数据库存储失败**返回服务器错误触发重试机制
### 降级策略
当设备采集服务出现故障时系统采用以下降级策略
1. **服务降级**暂时关闭非关键的设备信息采集功能
2. **缓存使用**使用最近一次成功的设备信息作为备用
3. **异步处理**将采集请求加入队列后续重试处理
4. **监控告警**实时监控采集成功率异常时及时告警
```mermaid
flowchart TD
A[采集请求] --> B{服务是否正常?}
B --> |是| C[正常处理]
B --> |否| D[启用降级策略]
D --> E[使用缓存数据]
E --> F[记录降级日志]
F --> G[发送监控告警]
C --> H[返回成功]
D --> H
H --> I[客户端处理]
```
**图示来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L31-L59)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L44)
**本节来源**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L0-L113)
## 数据库设计
### 数据表结构
设备ID采集机制涉及两个核心数据表
#### 访问记录表 (restrict_client_access_record)
存储设备的基本访问信息包括设备ID设备型号User-Agent和代理使用情况
```mermaid
erDiagram
V1RestrictClientAccessRecord {
int id PK
string visitor_id
string device_model
string user_agent
bool is_use_proxy
datetime created_at
datetime updated_at
datetime deleted_at
}
```
#### IP关联表 (restrict_client_access_ip_relation)
存储IP地址与访问记录的关联关系用于分析设备的网络访问模式
```mermaid
erDiagram
V1RestrictClientAccessIpRelation {
int id PK
string ip
bool is_remote_ip
int restrict_ip_record_id FK
int restrict_client_access_record_id FK
string session_id
datetime created_at
datetime updated_at
datetime deleted_at
}
V1RestrictClientAccessRecord ||--o{ V1RestrictClientAccessIpRelation : "包含"
```
**图示来源**
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L33-L73)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go#L0-L95)
**本节来源**
- [v_1_restrict_client_access_record.go](file://internal/dao/internal/v_1_restrict_client_access_record.go#L0-L93)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/internal/v_1_restrict_client_access_ip_relation.go#L0-L95)
- [v_1_restrict_client_access_record.go](file://internal/model/do/v_1_restrict_client_access_record.go#L0-L23)
- [v_1_restrict_client_access_ip_relation.go](file://internal/model/do/v_1_restrict_client_access_ip_relation.go#L0-L24)
- [v_1_restrict_client_access_record.go](file://internal/model/entity/v_1_restrict_client_access_record.go#L0-L21)

View File

@@ -0,0 +1,329 @@
# 设备ID限制机制
<cite>
**本文档引用的文件**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://api/merchant/v1/model.go)
- [v_1_merchant_deploy_info.go](file://internal/model/do/v_1_merchant_deploy_info.go)
- [v_1_restrict_client_access_record.go](file://internal/model/do/v_1_restrict_client_access_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/model/do/v_1_restrict_client_access_ip_relation.go)
- [restriction.go](file://internal/model/restriction.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
</cite>
## 目录
1. [简介](#简介)
2. [设备ID限制机制概述](#设备id限制机制概述)
3. [设备ID记录的采集与存储](#设备id记录的采集与存储)
4. [设备限制规则的配置与生效](#设备限制规则的配置与生效)
5. [设备ID匹配与验证机制](#设备id匹配与验证机制)
6. [设备伪装检测与代理识别](#设备伪装检测与代理识别)
7. [设备ID生成与隐私保护](#设备id生成与隐私保护)
8. [最佳实践与应用场景](#最佳实践与应用场景)
9. [与用户认证系统的集成](#与用户认证系统的集成)
10. [总结](#总结)
## 简介
本文档详细阐述了kami_backend系统中设备ID限制机制的实现原理和工作流程该机制通过采集存储和匹配设备标识信息实现了基于设备级别的访问控制有效防止多开设备级滥用等安全问题文档深入分析了设备ID的采集存储匹配和验证全过程以及与用户认证系统的集成方式
## 设备ID限制机制概述
设备ID限制机制是kami_backend系统中重要的安全控制组件旨在通过设备标识实现精细化的访问控制该机制允许系统管理员根据业务需求配置不同的设备限制策略包括是否限制设备是否检测代理是否限制卡密等当用户请求系统服务时系统会采集设备相关信息与预设的限制规则进行匹配从而决定是否允许访问
设备ID限制机制的核心功能包括
- 设备信息的采集与加密传输
- 设备ID的存储与管理
- 设备限制规则的配置与查询
- 设备匹配与访问控制决策
- 代理检测与设备伪装识别
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L17-L69)
- [model.go](file://api/merchant/v1/model.go#L75-L92)
## 设备ID记录的采集与存储
设备ID记录的采集与存储是设备限制机制的基础涉及前端信息采集后端接收处理和数据库持久化三个主要环节
### 信息采集流程
系统通过前端JavaScript代码采集设备信息包括IP地址列表设备ID设备型号和用户代理字符串采集到的信息经过AES-CBC加密和Base64编码后通过API接口发送到后端服务器
### 后端处理流程
后端通过`UserInfoCollection`控制器接收加密数据执行以下处理步骤
1. 使用预设密钥解密数据
2. 验证数据签名确保完整性
3. 提取设备相关信息
4. 调用服务层存储设备信息
### 数据库存储结构
设备信息存储在两个主要数据库表中
**设备访问记录表 (restrict_client_access_record)**
| 字段 | 类型 | 描述 |
|------|------|------|
| id | uint | 主键ID |
| visitor_id | string | 访问ID设备ID |
| device_model | string | 设备型号 |
| user_agent | string | 用户浏览器代理 |
| is_use_proxy | bool | 是否使用代理 |
**设备IP关联表 (restrict_client_access_ip_relation)**
| 字段 | 类型 | 描述 |
|------|------|------|
| id | uint | 主键ID |
| ip | string | IP地址 |
| is_remote_ip | bool | 是否为远程IP |
| restrict_ip_record_id | int | 限制IP详情ID |
| restrict_client_access_record_id | int | 设备访问记录ID |
| session_id | string | 会话ID |
```mermaid
erDiagram
restrict_client_access_record {
uint id PK
string visitor_id UK
string device_model
string user_agent
bool is_use_proxy
timestamp created_at
timestamp updated_at
timestamp deleted_at
}
restrict_client_access_ip_relation {
uint id PK
string ip
bool is_remote_ip
int restrict_ip_record_id FK
int restrict_client_access_record_id FK
string session_id
timestamp created_at
timestamp updated_at
timestamp deleted_at
}
restrict_client_access_record ||--o{ restrict_client_access_ip_relation : "1:N"
```
**Diagram sources**
- [v_1_restrict_client_access_record.go](file://internal/model/do/v_1_restrict_client_access_record.go#L12-L22)
- [v_1_restrict_client_access_ip_relation.go](file://internal/model/do/v_1_restrict_client_access_ip_relation.go#L12-L23)
**Section sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L0-L60)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L17-L42)
## 设备限制规则的配置与生效
设备限制规则的配置与生效流程是实现灵活访问控制的关键涉及规则定义策略配置和实时验证三个阶段
### 规则配置参数
设备限制规则通过商户部署配置进行定义主要参数包括
| 参数 | 类型 | 描述 |
|------|------|------|
| isRestrictDevice | bool | 是否限制设备 |
| isRestrictAgent | bool | 是否检测代理 |
| isRestrictCardPass | bool | 是否限制卡密 |
| isRestrictIp | bool | 是否限制IP |
| isRestrictInternalIp | bool | 是否限制局域网IP |
| restrictArea | []string | 限制地区列表 |
### 规则生效流程
当用户发起请求时系统按照以下流程验证设备限制规则
```mermaid
flowchart TD
A[用户请求] --> B{获取限制策略}
B --> C{是否限制卡密?}
C --> |是| D{卡密是否存在限制?}
D --> |是| E[拒绝访问]
C --> |否| F{是否限制设备?}
F --> |是| G{设备是否被禁用?}
G --> |是| E
F --> |否| H{是否检测代理?}
H --> |是| I{是否使用代理?}
I --> |是| E
H --> |否| J{是否限制IP?}
J --> |是| K{IP是否存在限制?}
K --> |是| E
J --> |否| L[允许访问]
E --> M[返回拒绝]
L --> N[返回允许]
```
**Diagram sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L17-L69)
- [model.go](file://api/merchant/v1/model.go#L75-L92)
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L17-L69)
- [v_1_merchant_deploy_info.go](file://internal/model/do/v_1_merchant_deploy_info.go#L12-L43)
## 设备ID匹配与验证机制
设备ID匹配与验证机制是设备限制功能的核心负责判断特定设备是否被限制访问系统资源
### 设备ID匹配流程
系统通过`IsRestrictDevice`方法实现设备ID匹配其工作原理如下
1. 接收设备ID作为输入参数
2. `restrict_ip_order_access`表中查询该设备ID的记录
3. 检查是否存在状态为"禁用"的记录
4. 如果存在禁用记录返回true设备被限制
5. 如果不存在禁用记录返回false设备未被限制
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant Database as "数据库"
Client->>Controller : 发送设备ID验证请求
Controller->>Service : 调用IsRestrictDevice(deviceId)
Service->>Database : 查询restrict_ip_order_access表
Database-->>Service : 返回匹配记录
Service-->>Controller : 返回是否限制结果
Controller-->>Client : 返回验证结果
```
**Diagram sources**
- [restriction.go](file://internal/logic/restriction/restriction.go#L164-L172)
- [restriction.go](file://internal/service/restriction.go#L18-L49)
**Section sources**
- [restriction.go](file://internal/logic/restriction/restriction.go#L164-L172)
- [restriction.go](file://internal/service/restriction.go#L48-L48)
## 设备伪装检测与代理识别
设备伪装检测与代理识别机制用于防范用户通过技术手段绕过设备限制提高系统的安全性
### 代理识别原理
系统通过比较采集的IP地址列表与实际请求IP地址来识别代理使用情况
1. 前端采集用户所有可见的IP地址
2. 后端获取实际请求的客户端IP地址
3. 比较两个IP地址是否一致
4. 如果不一致判断为使用代理
### 会话关联检测
系统还通过会话关联机制增强代理检测的准确性
1. 为每次设备访问生成唯一的会话ID
2. 记录该会话下所有IP地址的访问情况
3. 分析同一会话中IP地址的变化模式
4. 根据IP地址出现频率判断是否为代理
```mermaid
flowchart TD
A[采集IP列表] --> B[获取实际请求IP]
B --> C{IP是否匹配?}
C --> |是| D[未使用代理]
C --> |否| E[标记为代理]
E --> F[记录会话信息]
F --> G[分析IP访问模式]
G --> H[确认代理状态]
```
**Section sources**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go#L83-L112)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L50-L55)
## 设备ID生成与隐私保护
设备ID生成与隐私保护机制确保了用户隐私的同时又能有效实现设备级别的识别和控制
### 设备ID生成策略
系统采用客户端生成设备ID的策略具体实现方式如下
1. 前端JavaScript代码生成唯一设备标识
2. 设备ID基于设备硬件特征浏览器指纹等信息生成
3. 生成的设备ID在设备本地存储确保持久性
4. 设备ID在不同会话间保持一致
### 隐私保护措施
为保护用户隐私系统采取了多项安全措施
- **数据加密传输**所有设备信息通过AES-CBC加密后传输
- **数据完整性验证**使用MD5签名验证数据完整性
- **最小化数据采集**仅采集必要的设备识别信息
- **数据访问控制**严格限制设备信息的访问权限
```mermaid
flowchart TD
A[设备信息采集] --> B[数据加密]
B --> C[签名生成]
C --> D[数据传输]
D --> E[后端接收]
E --> F[解密验证]
F --> G[存储处理]
```
**Section sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L35-L59)
- [restriction.go](file://internal/model/restriction.go#L11-L17)
## 最佳实践与应用场景
设备ID限制机制在多种业务场景中发挥着重要作用以下是最佳实践和典型应用场景
### 防止多开场景
通过设备ID限制可以有效防止用户在同一设备上运行多个实例
1. 配置`isRestrictDevice=true`
2. 系统检测到同一设备ID的多次访问
3. 对重复访问进行限制或警告
4. 维护系统资源的公平使用
### 设备级访问控制
实现基于设备级别的精细化访问控制
- 为特定设备分配访问权限
- 限制高风险设备的访问
- 实现设备白名单/黑名单管理
- 监控异常设备的访问行为
### 安全审计与监控
利用设备ID记录进行安全审计
- 追踪设备访问历史
- 分析异常访问模式
- 识别潜在的安全威胁
- 生成设备访问报告
## 与用户认证系统的集成
设备ID限制机制与用户认证系统紧密集成共同构建多层次的安全防护体系
### 集成架构
设备限制功能作为认证流程的补充验证层
```mermaid
flowchart TD
A[用户登录] --> B[身份认证]
B --> C{认证成功?}
C --> |是| D[设备ID验证]
D --> E{设备是否受限?}
E --> |是| F[拒绝访问]
E --> |否| G[授予访问权限]
C --> |否| H[拒绝登录]
```
### 协同工作机制
设备限制与用户认证的协同工作流程
1. 用户提交登录凭证
2. 系统验证用户名和密码
3. 认证成功后采集设备信息
4. 验证设备ID是否被限制
5. 综合判断是否授予访问权限
**Section sources**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go#L17-L69)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go#L35-L59)
## 总结
设备ID限制机制是kami_backend系统中重要的安全控制组件通过采集存储和匹配设备标识信息实现了基于设备级别的精细化访问控制该机制有效防止了多开设备级滥用等安全问题增强了系统的整体安全性
核心优势包括
- 灵活的限制规则配置
- 可靠的设备识别能力
- 强大的代理检测功能
- 完善的隐私保护措施
- 与用户认证系统的无缝集成
通过合理配置和使用设备ID限制机制可以有效提升系统的安全性和稳定性为用户提供更可靠的服务体验

View File

@@ -0,0 +1,209 @@
# 设备ID隐私保护
<cite>
**本文档引用的文件**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [user_info.go](file://internal/model/user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
- [sys_user_login.go](file://internal/model/sys_user_login.go)
- [v_1_sys_user_login_log.go](file://internal/dao/v_1_sys_user_login_log.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
</cite>
## 目录
1. [引言](#引言)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 引言
本文档详细阐述了kami_backend系统中设备ID的隐私保护机制重点介绍设备ID的加密存储脱敏处理匿名化技术数据最小化原则访问控制策略审计日志机制合规性实现以及数据泄露应急响应预案确保系统符合GDPR等隐私法规要求
## 项目结构
kami_backend项目采用分层架构设计主要包含API接口层内部控制器层服务层数据访问层和工具层设备ID隐私保护相关功能主要分布在utility/verify工具模块和用户信息处理相关模块中
```mermaid
graph TB
subgraph "工具层"
Verify[utility/verify]
Config[utility/config]
Utils[utility/utils]
end
subgraph "数据访问层"
DAO[internal/dao]
Model[internal/model]
end
subgraph "服务层"
Service[internal/service]
end
subgraph "控制器层"
Controller[internal/controller]
end
subgraph "API层"
API[api]
end
Verify --> Service
Config --> Service
Utils --> Service
DAO --> Service
Service --> Controller
Controller --> API
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [user_info.go](file://internal/model/user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [user_info.go](file://internal/model/user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
## 核心组件
设备ID隐私保护的核心组件包括加密算法实现用户信息模型数据访问对象和服务逻辑加密算法主要由utility/verify模块提供用户信息处理由base_user_info服务和相关DAO组件完成
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
- [user_info.go](file://internal/model/user_info.go)
## 架构概述
系统采用分层安全架构保护设备ID隐私设备ID在存储前经过加密处理访问时实施严格的权限控制并记录完整的审计日志系统遵循数据最小化原则仅收集必要的用户信息
```mermaid
graph TB
Client[客户端] --> |原始设备ID| Encryption[加密模块]
Encryption --> |加密设备ID| Storage[数据存储]
Storage --> |加密设备ID| AccessControl[访问控制]
AccessControl --> |授权访问| Service[业务服务]
Service --> |审计日志| Logging[日志系统]
Logging --> |日志记录| Audit[审计系统]
subgraph "安全机制"
Encryption
AccessControl
Logging
end
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [sys_user_login.go](file://internal/model/sys_user_login.go)
- [v_1_sys_user_login_log.go](file://internal/dao/v_1_sys_user_login_log.go)
## 详细组件分析
### 加密算法组件分析
系统使用AES-ECB和MD5算法对设备ID进行加密处理AES-ECB用于设备ID的加密存储MD5用于设备ID的哈希处理
#### 加密算法类图
```mermaid
classDiagram
class AESEncryptor {
+string key
+encrypt(plaintext string) string
+decrypt(ciphertext string) string
}
class MD5Hasher {
+hash(data string) string
+verify(data string, hash string) bool
}
class DeviceIDProcessor {
-encryptor AESEncryptor
-hasher MD5Hasher
+encryptDeviceID(rawID string) string
+hashDeviceID(rawID string) string
+decryptDeviceID(encryptedID string) string
}
DeviceIDProcessor --> AESEncryptor : "使用"
DeviceIDProcessor --> MD5Hasher : "使用"
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
### 用户信息处理组件分析
用户信息处理组件负责设备ID的收集存储和访问控制系统在用户信息收集时实施数据最小化原则仅收集必要的设备信息
#### 用户信息处理流程
```mermaid
flowchart TD
Start([开始]) --> Collect["收集设备ID"]
Collect --> Validate["验证设备ID格式"]
Validate --> FormatValid{"格式有效?"}
FormatValid --> |否| ReturnError["返回错误"]
FormatValid --> |是| Encrypt["AES加密设备ID"]
Encrypt --> Hash["MD5哈希设备ID"]
Hash --> Store["存储加密和哈希值"]
Store --> Log["记录审计日志"]
Log --> End([结束])
ReturnError --> End
```
**Diagram sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
**Section sources**
- [restriction_v1_user_info_collection.go](file://internal/controller/restriction/restriction_v1_user_info_collection.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
## 依赖分析
设备ID隐私保护功能依赖于加密工具数据访问层和配置管理模块各组件之间保持低耦合确保系统的可维护性和安全性
```mermaid
graph LR
A[设备ID隐私保护] --> B[utility/verify]
A --> C[internal/dao]
A --> D[internal/service]
A --> E[utility/config]
B --> F[加密算法]
C --> G[数据持久化]
D --> H[业务逻辑]
E --> I[配置管理]
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [base_user_info.go](file://internal/service/base_user_info.go)
- [v_1_user_info.go](file://internal/dao/v_1_user_info.go)
## 性能考虑
设备ID加密处理对系统性能有一定影响但通过优化算法实现和缓存机制将性能影响控制在可接受范围内AES加密和MD5哈希操作的时间复杂度均为O(n)其中n为设备ID长度
## 故障排除指南
当设备ID隐私保护功能出现异常时应检查加密密钥配置数据库连接状态和权限设置查看相关日志文件可帮助定位问题
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [sys_user_login.go](file://internal/model/sys_user_login.go)
- [v_1_sys_user_login_log.go](file://internal/dao/v_1_sys_user_login_log.go)
## 结论
kami_backend系统通过AES-ECB和MD5加密算法严格的访问控制完整的审计日志和数据最小化原则实现了设备ID的全面隐私保护系统设计符合GDPR等隐私法规要求能够有效防止数据泄露保障用户隐私安全

View File

@@ -0,0 +1,301 @@
# 风控限制逻辑
<cite>
**本文档引用的文件**
- [restriction.go](file://internal/service/restriction.go)
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [restriction.go](file://internal/model/restriction.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
- [restriction.go](file://internal/consts/restriction.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细阐述了kami_backend系统中风控限制业务逻辑的实现机制重点分析了IP访问限制地域限制和设备ID限制的实现方式以及限制规则的配置查询和生效流程文档还解释了限制记录的存储结构查询优化策略和性能优化方案包括缓存机制和快速查询算法同时提供了限制规则配置的最佳实践和常见使用场景示例并描述了限制逻辑与其他安全机制的集成方式
## 项目结构
kami_backend的风控限制功能主要分布在`internal`目录下的多个子模块中核心逻辑位于`internal/logic/restriction`包中服务接口定义在`internal/service`包中数据访问对象DAO位于`internal/dao`包中模型定义在`internal/model`包中控制器层位于`internal/controller/restriction`包中处理外部请求此外限制相关的常量定义在`internal/consts`包中IP地理位置查询集成在`utility/integration/restriction`包中
```mermaid
graph TB
subgraph "控制器层"
Controller[restriction_v1_check_ip_allowed.go]
end
subgraph "服务层"
Service[restriction.go]
end
subgraph "业务逻辑层"
Logic[restriction.go]
DeviceLogic[device_id_record.go]
IPLLogic[ip_record.go]
end
subgraph "数据访问层"
DAO[v_1_restrict_*.go]
end
subgraph "模型层"
Model[restriction.go]
end
subgraph "集成层"
Integration[location.go]
end
Controller --> Service
Service --> Logic
Logic --> DAO
Logic --> Model
Logic --> Integration
DeviceLogic --> DAO
IPLLogic --> DAO
```
**图源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [restriction.go](file://internal/model/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
**节源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [restriction.go](file://internal/model/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
## 核心组件
风控限制系统的核心组件包括IP记录管理设备ID管理访问限制检查和限制记录存储系统通过`IRestriction`接口定义了所有限制相关的服务方法具体实现位于`sRestriction`结构体中主要功能包括存储设备信息检查IP是否允许访问获取或设置IP记录判断设备是否使用代理将IP加入限制列表等系统还集成了多个第三方IP地理位置查询服务以提高IP定位的准确性和可靠性
**节源**
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
## 架构概述
风控限制系统的架构采用典型的分层设计包括控制器层服务层业务逻辑层数据访问层和模型层控制器层接收外部请求并调用服务层接口服务层定义了统一的接口规范业务逻辑层实现了具体的限制检查逻辑数据访问层负责与数据库交互模型层定义了数据结构系统还通过集成层与外部IP地理位置查询服务通信整个系统通过GoFrame框架的依赖注入机制进行组件管理确保了代码的可测试性和可维护性
```mermaid
graph TD
A[客户端] --> B[控制器]
B --> C[服务接口]
C --> D[业务逻辑]
D --> E[数据访问]
E --> F[数据库]
D --> G[外部服务]
G --> H[IP地理位置查询]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#f96,stroke:#333
style D fill:#9f9,stroke:#333
style E fill:#99f,stroke:#333
style F fill:#f99,stroke:#333
style G fill:#ff9,stroke:#333
style H fill:#9ff,stroke:#333
```
**图源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [v_1_restrict_client_access_ip_relation.go](file://internal/dao/v_1_restrict_client_access_ip_relation.go)
- [v_1_restrict_client_access_record.go](file://internal/dao/v_1_restrict_client_access_record.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
- [v_1_restrict_ip_record.go](file://internal/dao/v_1_restrict_ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
## 详细组件分析
### IP访问限制分析
IP访问限制功能通过`CheckIPIsAllowed`方法实现该方法首先调用`IsInProvince`判断IP是否位于允许的省份列表中如果IP不在允许的省份列表中则认为是允许访问的系统通过`GetOrSetIPRecord`方法获取或创建IP记录如果IP是公网IP则会调用外部服务获取其地理位置信息IP记录包括IP地址省份信息是否为公网IP以及原始响应数据
```mermaid
flowchart TD
Start([开始]) --> CheckPublicIP["检查是否为公网IP"]
CheckPublicIP --> |是| GetLocation["获取IP地理位置"]
CheckPublicIP --> |否| ReturnAllowed["返回允许"]
GetLocation --> StoreRecord["存储IP记录"]
StoreRecord --> CheckProvince["检查是否在允许省份"]
CheckProvince --> |不在| ReturnAllowed
CheckProvince --> |在| ReturnNotAllowed["返回不允许"]
style Start fill:#f9f,stroke:#333
style ReturnAllowed fill:#9f9,stroke:#333
style ReturnNotAllowed fill:#f99,stroke:#333
```
**图源**
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
**节源**
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
### 设备ID限制分析
设备ID限制功能通过`SaveDeviceInfo``CheckIsDeviceUseProxy`方法实现`SaveDeviceInfo`方法存储设备信息包括设备ID设备型号用户代理字符串以及IP地址列表系统通过比较远程IP和IP列表来判断是否使用代理`CheckIsDeviceUseProxy`方法检查特定设备ID和IP组合是否使用代理通过查询访问记录和IP关联关系来确定
```mermaid
classDiagram
class sRestriction {
+SaveDeviceInfo(ctx, input)
+SaveDeviceIPRelation(ctx, ip, isRemoteIP, accessId, sessionId, tx)
+GetOrSetAccessRecord(ctx, input, tx)
+CheckIsDeviceUseProxy(ctx, deviceId, ip)
}
class RestrictionDeviceInput {
+IPs[] string
+RemoteIP string
+DeviceID string
+DeviceModel string
+UserAgent string
}
class V1RestrictClientAccessRecord {
+Id int
+VisitorId string
+DeviceModel string
+UserAgent string
+IsUseProxy bool
}
class V1RestrictClientAccessIpRelation {
+Id int
+Ip string
+IsRemoteIp bool
+RestrictIpRecordId uint
+RestrictClientAccessRecordId int
+SessionId string
}
sRestriction --> RestrictionDeviceInput : "使用"
sRestriction --> V1RestrictClientAccessRecord : "操作"
sRestriction --> V1RestrictClientAccessIpRelation : "操作"
```
**图源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/model/restriction.go)
**节源**
- [device_id_record.go](file://internal/logic/restriction/device_id_record.go)
- [restriction.go](file://internal/model/restriction.go)
### 限制规则配置分析
限制规则配置通过`AddToRestrictIP`方法实现该方法将IP加入限制列表系统首先获取或创建IP记录然后在`restrict_ip_order_access`表中插入新的限制记录限制记录包括IP地址状态限制策略设备ID订单号和卡密等信息系统还通过事务确保数据一致性并在限制状态变化时更新订单摘要
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Service as "服务层"
participant Logic as "业务逻辑"
participant DAO as "数据访问"
participant DB as "数据库"
Client->>Controller : 检查IP是否允许
Controller->>Service : 调用CheckIPAllowed
Service->>Logic : 执行限制检查逻辑
Logic->>DAO : 查询限制策略
DAO->>DB : 执行数据库查询
DB-->>DAO : 返回查询结果
DAO-->>Logic : 返回策略数据
Logic->>Logic : 执行各项限制检查
Logic-->>Service : 返回检查结果
Service-->>Controller : 返回结果
Controller-->>Client : 返回是否允许
```
**图源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
**节源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [v_1_restrict_ip_order_access.go](file://internal/dao/v_1_restrict_ip_order_access.go)
## 依赖分析
风控限制系统依赖于多个内部和外部组件内部依赖包括数据库访问组件DAO模型组件常量组件和工具组件外部依赖包括IP地理位置查询服务系统集成了多个第三方服务以提高查询的可靠性和准确性系统还依赖于GoFrame框架提供的事务管理日志记录和错误处理功能各组件之间的依赖关系清晰通过接口定义和依赖注入实现松耦合
```mermaid
graph TD
A[风控限制系统] --> B[数据库]
A --> C[IP地理位置服务]
A --> D[GoFrame框架]
A --> E[商户部署信息]
A --> F[订单摘要]
B --> G[MySQL]
C --> H[CSDN]
C --> I[PCOnline]
C --> J[OlTools]
C --> K[IdCd]
C --> L[MeiTu]
C --> M[Vo]
C --> N[DBIP]
C --> O[QJQQ]
C --> P[IQIYI]
C --> Q[IP66n]
style A fill:#f96,stroke:#333
style B fill:#99f,stroke:#333
style C fill:#ff9,stroke:#333
style D fill:#9f9,stroke:#333
style E fill:#bbf,stroke:#333
style F fill:#f99,stroke:#333
```
**图源**
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
**节源**
- [restriction.go](file://internal/service/restriction.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
## 性能考虑
风控限制系统在性能方面进行了多项优化首先系统通过数据库索引优化查询性能在关键字段上建立了索引其次系统采用事务批量处理操作减少数据库交互次数对于IP地理位置查询系统实现了重试机制和多个服务提供商的轮询以提高查询成功率和响应速度此外系统通过缓存常用数据和预加载配置信息来减少重复计算和数据库查询
**节源**
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [ip_record.go](file://internal/logic/restriction/ip_record.go)
- [location.go](file://utility/integration/restriction/location.go)
## 故障排除指南
在使用风控限制功能时可能遇到以下常见问题IP地理位置查询失败数据库连接异常限制规则不生效等对于IP地理位置查询失败可以检查网络连接和第三方服务状态系统会自动重试其他服务提供商对于数据库连接异常需要检查数据库配置和连接池设置对于限制规则不生效需要检查商户部署策略配置和限制逻辑的执行顺序系统日志记录了详细的执行过程可用于问题排查
**节源**
- [restriction_v1_check_ip_allowed.go](file://internal/controller/restriction/restriction_v1_check_ip_allowed.go)
- [restriction.go](file://internal/logic/restriction/restriction.go)
- [location.go](file://utility/integration/restriction/location.go)
## 结论
kami_backend的风控限制系统实现了全面的IP访问限制地域限制和设备ID限制功能系统架构清晰组件职责明确通过分层设计和接口抽象实现了良好的可维护性和可扩展性系统集成了多个第三方IP地理位置查询服务提高了IP定位的准确性和可靠性在性能方面系统通过索引优化事务批量处理和重试机制等手段确保了高效稳定的运行未来可以考虑引入缓存机制进一步优化性能并增加更多的限制维度以满足复杂的业务需求

View File

@@ -0,0 +1,269 @@
# 中间件与拦截器
<cite>
**Referenced Files in This Document**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
- [code.go](file://internal/errHandler/code.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细介绍了kami_backend项目中的中间件和拦截器系统重点分析了认证中间件(auth.go)和错误处理中间件(error_handler.go)的实现文档描述了这些中间件如何在请求处理流程中实现用户身份验证授权检查以及统一的API响应格式化通过深入分析中间件的实现细节配置选项和使用模式为开发者提供了创建自定义中间件的指南和最佳实践
## 项目结构
kami_backend项目的中间件系统主要位于`internal/middleware`目录下包含两个核心文件`auth.go``error_handler.go`这些中间件与`utility`目录下的工具模块如tokenconfigverify紧密协作共同构成了系统的安全和错误处理基础设施
```mermaid
graph TD
subgraph "中间件层"
A[auth.go]
B[error_handler.go]
end
subgraph "工具层"
C[token]
D[config]
E[verify]
F[cache]
end
A --> C
A --> D
A --> E
B --> F
C --> D
C --> F
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
**Section sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
## 核心组件
kami_backend的中间件系统由两个核心组件构成认证中间件和错误处理中间件认证中间件负责处理用户身份验证和授权检查支持多种认证方式错误处理中间件则负责统一处理和格式化API响应确保系统返回一致的错误信息格式
**Section sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
## 架构概述
kami_backend的中间件系统采用分层架构设计将认证逻辑与错误处理逻辑分离认证中间件实现了灵活的认证策略支持白名单登录认证和iFrame认证三种模式错误处理中间件则作为统一的错误捕获和响应层确保所有API调用返回标准化的响应格式
```mermaid
graph TB
Client[客户端] --> AuthMiddleware[认证中间件]
AuthMiddleware --> BusinessLogic[业务逻辑]
BusinessLogic --> ErrorHandler[错误处理中间件]
ErrorHandler --> Client
subgraph "认证策略"
WhiteList[白名单认证]
LoginAuth[登录认证]
IFrameAuth[iFrame认证]
end
AuthMiddleware --> WhiteList
AuthMiddleware --> LoginAuth
AuthMiddleware --> IFrameAuth
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
## 详细组件分析
### 认证中间件分析
认证中间件是kami_backend安全体系的核心实现了多模式的身份验证机制该中间件通过`LoginOrIframeAuth`函数协调不同的认证策略根据请求头中的`tokenFrom`字段选择适当的认证方式
#### 认证流程类图
```mermaid
classDiagram
class AuthMiddleware {
+LoginOrIframeAuth(r *ghttp.Request)
+whiteListAuth(r *ghttp.Request) gcode.Code
+loginAuth(r *ghttp.Request) gcode.Code
+iFrameAuth(r *ghttp.Request) gcode.Code
}
class TokenUtil {
+GetRequestToken(r *ghttp.Request) string
+ParseUserToken(ctx context.Context, tokenStr string) (*UserToken, error)
+RefreshUserToken(ctx context.Context, userToken UserToken) (string, error)
+GetTokenFromRedis(ctx context.Context, userID string, uuid string) (string, error)
}
class ConfigUtil {
+NewConfig(ctx context.Context) *Config
+GetTokenOptions() (TokenOptions, error)
+GetFrontendSecret() (SecretModel, error)
}
class CacheUtil {
+Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
+Get(ctx context.Context, key string) (*gvar.Var, error)
+Remove(ctx context.Context, key string) error
}
AuthMiddleware --> TokenUtil : "使用"
AuthMiddleware --> ConfigUtil : "使用"
TokenUtil --> CacheUtil : "使用"
TokenUtil --> ConfigUtil : "使用"
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
#### 认证流程序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant AuthMiddleware as "认证中间件"
participant TokenUtil as "Token工具"
participant ConfigUtil as "配置工具"
participant Cache as "缓存系统"
Client->>AuthMiddleware : 发送API请求
AuthMiddleware->>AuthMiddleware : 检查白名单
alt 在白名单中
AuthMiddleware-->>Client : 直接放行
else 需要认证
AuthMiddleware->>AuthMiddleware : 检查tokenFrom头
alt tokenFrom=login
AuthMiddleware->>TokenUtil : GetRequestToken()
TokenUtil-->>AuthMiddleware : 返回Token
AuthMiddleware->>TokenUtil : ParseUserToken()
TokenUtil-->>AuthMiddleware : 返回用户Token信息
AuthMiddleware->>Cache : GetTokenFromRedis()
Cache-->>AuthMiddleware : 返回缓存的Token
AuthMiddleware->>TokenUtil : RefreshUserToken()
TokenUtil-->>AuthMiddleware : 返回新Token
AuthMiddleware->>Client : 设置refresh-token头
AuthMiddleware-->>Client : 放行请求
else tokenFrom=iframe
AuthMiddleware->>TokenUtil : GetRequestToken()
TokenUtil-->>AuthMiddleware : 返回Token
AuthMiddleware->>ConfigUtil : GetFrontendSecret()
ConfigUtil-->>AuthMiddleware : 返回密钥和IV
AuthMiddleware->>Verify : AesCBCURLDecryptWithBase64()
Verify-->>AuthMiddleware : 解密Token
AuthMiddleware->>AuthMiddleware : 验证Token时效性
AuthMiddleware-->>Client : 放行请求
else 未知来源
AuthMiddleware-->>Client : 返回"token来源不明"错误
end
end
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
#### 白名单认证流程
```mermaid
flowchart TD
Start([开始]) --> CheckPath["检查请求路径"]
CheckPath --> IsInWhiteList{"路径在白名单中?"}
IsInWhiteList --> |是| ReturnOK["返回CodeOK"]
IsInWhiteList --> |否| ReturnNotAuthorized["返回CodeNotAuthorized"]
ReturnOK --> End([结束])
ReturnNotAuthorized --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L22-L51)
### 错误处理中间件分析
错误处理中间件负责捕获和格式化API响应确保系统返回一致的错误信息格式该中间件在请求处理链的末端执行能够捕获业务逻辑层抛出的任何错误并将其转换为标准化的JSON响应
#### 错误处理流程
```mermaid
flowchart TD
Start([开始]) --> NextMiddleware["执行后续中间件"]
NextMiddleware --> GetError["获取错误信息"]
GetError --> GetResponse["获取响应数据"]
GetError --> GetCode["获取错误码"]
GetCode --> IsNil{"错误码为空?"}
IsNil --> |是| SetNilCode["设置为CodeNil"]
IsNil --> |否| UseErrorCode["使用实际错误码"]
SetNilCode --> CheckError["检查是否有错误"]
UseErrorCode --> CheckError
CheckError --> HasError{"存在错误?"}
HasError --> |是| IsCritical{"是CodeNil或CodeInternalPanic?"}
HasError --> |否| End([结束])
IsCritical --> |是| SetStatus200["设置状态码为200"]
IsCritical --> |否| End
SetStatus200 --> ClearBuffer["清空缓冲区"]
ClearBuffer --> WriteJson["写入JSON响应"]
WriteJson --> End
```
**Diagram sources**
- [error_handler.go](file://internal/middleware/error_handler.go#L8-L27)
## 依赖分析
kami_backend的中间件系统依赖于多个核心模块形成了一个紧密耦合但职责分明的架构认证中间件依赖于tokenconfig和verify模块来实现完整的认证功能而错误处理中间件则依赖于GoFrame框架的错误处理机制
```mermaid
graph TD
AuthMiddleware[auth.go] --> Token[user_token.go]
AuthMiddleware --> Config[config.go]
AuthMiddleware --> Verify[verify.go]
Token --> Cache[cache.go]
Token --> Config
ErrorMiddleware[error_handler.go] --> GFError[gerror]
ErrorMiddleware --> GFCode[gcode]
ErrorMiddleware --> GFHttp[ghttp]
subgraph "utility"
Token
Config
Verify
Cache
end
subgraph "internal/middleware"
AuthMiddleware
ErrorMiddleware
end
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
**Section sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
## 性能考虑
中间件系统的性能主要受Token验证和缓存操作的影响认证中间件通过Redis缓存Token信息避免了重复的JWT解析和验证操作提高了认证效率同时白名单机制避免了对公开API的不必要的认证检查进一步优化了性能
## 故障排除指南
当遇到中间件相关问题时可以参考以下常见问题和解决方案
1. **Token验证失败**检查`tokenFrom`头是否正确设置确认Token格式是否正确
2. **认证超时**检查配置中的Token超时设置确认Redis缓存是否正常工作
3. **错误响应格式不一致**确保所有业务逻辑都使用标准的错误码系统
4. **iFrame认证失败**检查前端密钥和IV配置是否正确确认Token加密方式是否匹配
**Section sources**
- [auth.go](file://internal/middleware/auth.go)
- [error_handler.go](file://internal/middleware/error_handler.go)
- [code.go](file://internal/errHandler/code.go)
## 结论
kami_backend的中间件系统设计合理实现了安全性和可维护性的平衡认证中间件通过灵活的策略支持多种认证方式而错误处理中间件则确保了API响应的一致性建议在开发新功能时遵循现有的中间件模式确保系统的整体一致性和安全性

View File

@@ -0,0 +1,200 @@
# 外部集成
<cite>
**本文档中引用的文件**
- [main.go](file://main.go)
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [api.go](file://utility/integration/redeem/jd/api.go)
- [api.go](file://utility/integration/redeem/ctrip/api.go)
- [api.go](file://utility/integration/redeem/walmart/api.go)
- [api.go](file://utility/integration/tmall/api/api.go)
</cite>
## 目录
1. [简介](#简介)
2. [电商平台API集成](#电商平台api集成)
3. [OpenTelemetry集成](#opentelemetry集成)
4. [Casbin权限系统集成](#casbin权限系统集成)
5. [故障排除指南](#故障排除指南)
6. [结论](#结论)
## 简介
本文档详细说明了kami_backend系统的外部集成机制涵盖第三方电商平台API集成OpenTelemetry可观测性系统集成以及Casbin权限控制系统的实现文档旨在为开发人员提供全面的技术指导包括集成架构配置选项使用模式和技术决策
## 电商平台API集成
kami_backend通过`utility/integration`包实现了与多个电商平台的集成包括京东天猫Ctrip和沃尔玛等每个平台都有独立的子包遵循统一的设计模式和接口规范
### 京东集成
京东集成位于`utility/integration/redeem/jd`目录下通过`Client`结构体封装API调用该集成支持账户管理订单提交和状态查询等核心功能
**Section sources**
- [api.go](file://utility/integration/redeem/jd/api.go#L1-L5)
### Ctrip集成
Ctrip集成位于`utility/integration/redeem/ctrip`目录下提供完整的API客户端实现集成包括服务接口定义数据模型和业务逻辑处理
**Section sources**
- [api.go](file://utility/integration/redeem/ctrip/api.go#L1-L5)
### 沃尔玛集成
沃尔玛集成位于`utility/integration/redeem/walmart`目录下通过`Client`结构体提供统一的访问接口该集成支持多账户管理和订单生命周期跟踪
**Section sources**
- [api.go](file://utility/integration/redeem/walmart/api.go#L1-L5)
### 天猫集成
天猫集成位于`utility/integration/tmall`目录下采用单例模式通过`NewClient()`函数获取客户端实例集成包含API调用OAuth认证和定时任务同步功能
```mermaid
classDiagram
class InnerClient {
+NewClient() *InnerClient
}
class api {
+NewClient()
}
class topsdk {
+topclient
+abilities
}
InnerClient --> api : "实现"
InnerClient --> topsdk : "依赖"
```
**Diagram sources**
- [api.go](file://utility/integration/tmall/api/api.go#L1-L20)
**Section sources**
- [api.go](file://utility/integration/tmall/api/api.go#L1-L20)
## OpenTelemetry集成
OpenTelemetry集成在`utility/otel`包中实现提供统一的可观测性解决方案包括链路追踪指标收集和日志导出
### 配置结构
`Config`结构体定义了OpenTelemetry的配置参数包括服务名称收集器URL安全设置和采样率等默认配置通过`DefaultConfig()`函数提供
```mermaid
classDiagram
class Config {
+ServiceName string
+CollectorURL string
+Insecure bool
+Compressor string
+Headers map[string]string
+Timeout time.Duration
+SampleRate float64
+Enable bool
+ResourceAttrs []attribute.KeyValue
+Validate() error
+Clone() *Config
}
class Manager {
+NewOTelManager(config *Config) (*Manager, error)
+Shutdown(ctx context.Context) error
+GetConfig() *Config
+GetResource() *resource.Resource
+IsTracingEnabled() bool
+IsLoggingEnabled() bool
+CreateTracer(name string) oteltrace.Tracer
+CreateLogger(name string) otellog.Logger
}
Config --> Manager : "配置"
```
**Diagram sources**
- [config.go](file://utility/otel/config.go#L1-L68)
- [manager.go](file://utility/otel/manager.go#L1-L258)
**Section sources**
- [config.go](file://utility/otel/config.go#L1-L68)
- [manager.go](file://utility/otel/manager.go#L1-L258)
### 初始化流程
系统启动时在`main.go`中调用`otel.InitWithConfig()`函数初始化OpenTelemetry该函数创建`Manager`实例并配置追踪日志和指标组件
```mermaid
sequenceDiagram
participant Main as main.go
participant Otel as otel/utils.go
participant Manager as otel/manager.go
Main->>Otel : InitWithConfig(config)
Otel->>Manager : NewOTelManager(config)
Manager->>Manager : Validate配置
Manager->>Manager : 创建资源
Manager->>Manager : initTracing()
Manager->>Manager : initLogging()
Manager-->>Otel : 返回Manager
Otel-->>Main : nil
```
**Diagram sources**
- [main.go](file://main.go#L1-L50)
- [utils.go](file://utility/otel/utils.go#L22-L33)
- [manager.go](file://utility/otel/manager.go#L35-L86)
**Section sources**
- [main.go](file://main.go#L1-L50)
- [utils.go](file://utility/otel/utils.go#L1-L50)
## Casbin权限系统集成
Casbin权限系统基于RBAC模型实现配置文件位于`resource/casbin/rbac_model.conf`系统通过`g`规则定义角色继承关系实现灵活的权限控制
### RBAC模型配置
模型定义了请求策略角色和匹配器四个核心部分请求定义为`sub, obj, act`三元组策略定义了具体的权限规则角色定义支持层级继承
```mermaid
erDiagram
USER ||--o{ ROLE : "拥有"
ROLE ||--o{ POLICY : "关联"
USER {
string username
string role
}
ROLE {
string name
string parent
}
POLICY {
string subject
string object
string action
string effect
}
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 故障排除指南
### OpenTelemetry初始化失败
当OpenTelemetry初始化失败时检查配置参数是否正确特别是`ServiceName``CollectorURL`不能为空确保网络连接正常收集器服务可访问
**Section sources**
- [config.go](file://utility/otel/config.go#L40-L52)
- [manager.go](file://utility/otel/manager.go#L50-L55)
### 电商平台API调用失败
检查API客户端配置是否正确验证认证信息和端点URL查看日志中的详细错误信息确认网络连接和防火墙设置
**Section sources**
- [api.go](file://utility/integration/redeem/jd/api.go#L1-L5)
- [api.go](file://utility/integration/tmall/api/api.go#L1-L20)
### 权限验证失败
确认用户角色分配正确检查`sys_casbin_rule`表中的策略规则验证请求的`sub, obj, act`三元组是否与策略匹配
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 结论
kami_backend的外部集成设计遵循模块化和可扩展原则通过清晰的包结构和接口定义实现了与多个第三方服务的无缝集成OpenTelemetry提供了全面的可观测性支持Casbin实现了灵活的权限控制为系统的稳定运行和安全管理提供了坚实基础

View File

@@ -0,0 +1,272 @@
# 权限系统集成
<cite>
**本文档引用的文件**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [sys_casbin_rule.go](file://internal/dao/v_1_sys_casbin_rule.go)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
- [sys_auth_rule.go](file://api/sys_auth_rule/v1/sys_auth_rule.go)
- [sys_role.go](file://api/sys_role/v1/sys_role.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend权限系统的集成实现重点介绍基于Casbin的RBAC基于角色的访问控制模型的配置和实现机制文档涵盖rbac_model.conf文件的结构和语法规则权限验证的实现方式以及动态更新权限策略的方法同时解释了技术决策背后的原因包括为何选择Casbin作为权限框架性能优化策略和安全性考虑
## 项目结构
kami_backend的权限系统主要由Casbin模型配置服务层接口数据访问对象和实体模型组成系统通过RBAC模型实现细粒度的访问控制将用户角色权限和资源进行有效关联
```mermaid
graph TB
subgraph "权限配置"
Model[rbac_model.conf]
end
subgraph "服务层"
Service[sys_casbin.go]
end
subgraph "数据层"
DAO[v_1_sys_casbin_rule.go]
Entity[v_1_sys_casbin_rule.go]
end
Model --> Service
Service --> DAO
DAO --> Entity
```
**图示来源**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
**章节来源**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
## 核心组件
权限系统的核心组件包括Casbin模型定义策略存储机制和权限验证服务系统通过ICasbin接口提供统一的权限管理功能包括策略的加载保存添加和删除操作权限规则存储在sys_casbin_rule数据库表中通过GORM进行数据持久化操作
**章节来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
## 架构概述
权限系统采用分层架构设计从上到下分为接口层服务层和数据层接口层定义了权限管理所需的所有方法服务层实现了具体的业务逻辑数据层负责与数据库交互
```mermaid
graph TD
A[API请求] --> B[权限验证中间件]
B --> C[Casbin Enforcer]
C --> D[策略匹配器]
D --> E[数据库策略存储]
E --> F[sys_casbin_rule表]
G[策略管理API] --> H[ICasbin接口]
H --> I[策略操作实现]
I --> E
```
**图示来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
## 详细组件分析
### RBAC模型配置分析
Casbin的RBAC模型配置文件定义了权限系统的底层逻辑结构包括请求定义策略定义角色定义策略效果和匹配器
#### 模型配置结构
```mermaid
classDiagram
class RBACModel {
+request_definition : r = sub, obj, act
+policy_definition : p = sub, obj, act
+role_definition : g = _, _
+policy_effect : e = some(where (p.eft == allow))
+matchers : m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
}
class Request {
+sub : subject
+obj : object
+act : action
}
class Policy {
+sub : subject
+obj : object
+act : action
}
RBACModel --> Request : "包含"
RBACModel --> Policy : "包含"
```
**图示来源**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
#### 配置部分详解
- **[request_definition]**: 定义了权限检查请求的格式包含主体(sub)对象(obj)和动作(act)三个要素
- **[policy_definition]**: 定义了策略规则的格式与请求定义保持一致便于匹配
- **[role_definition]**: 定义了角色继承关系g(_, _)表示角色之间的层级关系
- **[policy_effect]**: 定义了策略生效的条件some(where (p.eft == allow))表示只要有一条允许策略就通过
- **[matchers]**: 定义了策略匹配逻辑检查主体的角色请求对象和动作是否与策略匹配
**章节来源**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
### 权限服务实现分析
权限服务实现了ICasbin接口提供了完整的策略管理功能
#### 服务接口与实现
```mermaid
classDiagram
class ICasbin {
<<interface>>
+CasbinEnforcer(ctx) : *SyncedEnforcer, error
+SavePolicy(model) : error
+LoadPolicy(model) : error
+AddPolicy(sec, pType, rule) : error
+RemovePolicy(sec, pType, rule) : error
+AddPolicies(sec, pType, rules) : error
+RemovePolicies(sec, ptype, rules) : error
+RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues) : error
}
class sCasbin {
-Enforcer : *SyncedEnforcer
-EnforcerErr : error
-Ctx : context.Context
+CasbinEnforcer(ctx) : *SyncedEnforcer, error
+SavePolicy(model) : error
+LoadPolicy(model) : error
+AddPolicy(sec, pType, rule) : error
+RemovePolicy(sec, pType, rule) : error
+AddPolicies(sec, pType, rules) : error
+RemovePolicies(sec, ptype, rules) : error
+RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues) : error
}
ICasbin <|-- sCasbin
```
**图示来源**
- [sys_casbin.go](file://internal/service/sys_casbin.go)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
#### 权限验证流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Middleware as "权限中间件"
participant Enforcer as "Casbin Enforcer"
participant DB as "数据库"
Client->>Middleware : 发送API请求
Middleware->>Enforcer : 调用enforcer.Enforce()
Enforcer->>DB : 加载策略规则
DB-->>Enforcer : 返回策略数据
Enforcer->>Enforcer : 执行匹配器逻辑
Enforcer-->>Middleware : 返回验证结果
alt 验证通过
Middleware->>Client : 继续处理请求
else 验证失败
Middleware->>Client : 返回403错误
end
```
**图示来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [middleware/auth.go](file://internal/middleware/auth.go)
**章节来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
### 数据模型分析
权限系统的数据模型定义了策略在数据库中的存储结构
#### 数据实体关系
```mermaid
erDiagram
SYS_CASBIN_RULE {
string ptype PK
string v0
string v1
string v2
string v3
string v4
string v5
}
SYS_CASBIN_RULE ||--o{ SYS_ROLE : "角色策略"
SYS_CASBIN_RULE ||--o{ SYS_USER : "用户策略"
SYS_CASBIN_RULE ||--o{ AUTH_RULE : "权限规则"
```
**图示来源**
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
- [v_1_sys_role.go](file://internal/model/entity/v_1_sys_role.go)
#### 策略存储格式
- **ptype**: 策略类型'p'表示权限策略'g'表示角色继承策略
- **v0**: 第一个值对于'p'类型是主体对于'g'类型是用户
- **v1**: 第二个值对于'p'类型是对象对于'g'类型是角色
- **v2**: 第三个值动作
- **v3-v5**: 额外的参数值
**章节来源**
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
## 依赖分析
权限系统依赖于多个核心组件和外部库形成了完整的权限管理生态
```mermaid
graph TD
A[Casbin库] --> B[Casbin Enforcer]
B --> C[权限服务]
C --> D[DAO层]
D --> E[数据库]
F[API控制器] --> C
G[中间件] --> C
H[配置系统] --> C
style A fill:#f9f,stroke:#333
style E fill:#bbf,stroke:#333
```
**图示来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [go.mod](file://go.mod)
**章节来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [go.mod](file://go.mod)
## 性能考虑
权限系统在设计时考虑了多项性能优化策略确保在高并发场景下的响应速度和系统稳定性
1. **同步Enforcer**: 使用casbin.SyncedEnforcer而非普通Enforcer确保多goroutine环境下的线程安全
2. **策略缓存**: Casbin内置策略缓存机制减少重复的数据库查询
3. **批量操作**: 提供AddPolicies和RemovePolicies方法支持批量策略操作减少数据库交互次数
4. **延迟初始化**: Enforcer实例采用once.Do进行延迟初始化避免启动时的性能开销
## 故障排除指南
### 常见问题及解决方案
| 问题现象 | 可能原因 | 解决方案 |
|--------|--------|--------|
| 权限不生效 | 策略未正确加载 | 调用LoadPolicy重新加载策略 |
| 角色继承错误 | g规则定义不正确 | 检查v0和v1字段的角色继承关系 |
| 策略冲突 | 存在相互矛盾的策略 | 检查策略效果配置和匹配顺序 |
| 性能下降 | 策略数量过多 | 考虑策略分组或优化匹配器逻辑 |
| 动态更新失败 | 事务处理异常 | 检查数据库连接和事务完整性 |
**章节来源**
- [sys_casbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [v_1_sys_casbin_rule.go](file://internal/model/entity/v_1_sys_casbin_rule.go)
## 结论
kami_backend的权限系统基于Casbin框架实现了灵活可靠的RBAC模型通过清晰的分层架构和标准化的接口设计系统能够有效管理复杂的权限关系模型配置文件的结构化设计使得权限规则易于理解和维护而完整的API支持则确保了策略的动态管理能力整体设计兼顾了安全性性能和可扩展性为系统的稳定运行提供了有力保障

View File

@@ -0,0 +1,299 @@
# Ctrip平台集成
<cite>
**本文档引用文件**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
- [card_info_c_trip_v1_account_list.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_list.go)
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go)
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go)
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go)
- [card_info_c_trip_v1_redeem_config_set.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_set.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
- [redeem.go](file://utility/integration/redeem/redeem.go)
- [account.go](file://api/card_info_c_trip/v1/account.go)
- [order.go](file://api/card_info_c_trip/v1/order.go)
- [config.go](file://api/card_info_c_trip/v1/config.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend如何通过redeem/ctrip包集成Ctrip API涵盖Ctrip账户管理卡密兑换订单回调等功能的实现机制文档重点阐述了Ctrip客户端的认证方式API调用模式异步回调处理和错误处理策略并提供具体的代码示例展示核心功能的调用方式
## 项目结构
Ctrip平台集成主要位于`api/card_info_c_trip``internal/controller/card_info_c_trip`目录下通过v1版本的API接口提供服务核心功能包括账户管理订单处理和配置管理通过`utility/integration/redeem/ctrip`包与Ctrip API进行交互
```mermaid
graph TB
subgraph "API层"
AccountAPI["/cardInfo/cTrip/account/*"]
OrderAPI["/cardInfo/cTrip/order/*"]
ConfigAPI["/cardInfo/cTrip/config/*"]
end
subgraph "控制器层"
AccountController["card_info_c_trip_v1_account_*.go"]
OrderController["card_info_c_trip_v1_order_*.go"]
ConfigController["card_info_c_trip_v1_redeem_config_*.go"]
end
subgraph "服务层"
RedeemOrderService["CardRedeemOrder()"]
RedeemAccountService["CardRedeemAccount()"]
SysConfigDictService["SysConfigDict()"]
end
subgraph "集成层"
CtripClient["utility/integration/redeem/ctrip/service.go"]
end
AccountAPI --> AccountController
OrderAPI --> OrderController
ConfigAPI --> ConfigController
AccountController --> RedeemAccountService
OrderController --> RedeemOrderService
ConfigController --> SysConfigDictService
RedeemOrderService --> CtripClient
RedeemAccountService --> CtripClient
```
**图示来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
## 核心组件
系统通过`card_info_c_trip`包实现Ctrip平台的完整集成主要包含账户管理卡密兑换订单回调和配置管理四大核心功能所有操作均通过统一的认证机制和错误处理策略进行管理
**组件来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go#L1-L60)
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go#L1-L30)
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go#L1-L24)
## 架构概述
系统采用分层架构设计从API接口到后端服务再到外部集成各层职责分明API层定义接口规范控制器层处理业务逻辑服务层封装核心功能集成层负责与Ctrip API通信
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant Ctrip as "Ctrip API"
Client->>API : 创建Ctrip账户请求
API->>Controller : 转发请求
Controller->>Service : 验证用户权限
Service->>Service : 获取Ctrip客户端实例
Service->>Ctrip : 查询用户信息
Ctrip-->>Service : 返回用户信息
Service->>Ctrip : 查询账户余额
Ctrip-->>Service : 返回余额信息
Service->>Service : 检查账户是否已存在
Service-->>Controller : 准备创建账户
Controller-->>API : 返回创建结果
API-->>Client : 响应客户端
```
**图示来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
## 详细组件分析
### Ctrip账户管理分析
系统提供完整的Ctrip账户管理功能包括账户创建列表查询状态更新和删除等操作账户信息存储在系统数据库中并与用户权限绑定
#### 账户创建流程
```mermaid
flowchart TD
Start([开始]) --> AuthCheck["验证用户登录状态"]
AuthCheck --> AuthValid{"认证通过?"}
AuthValid --> |否| ReturnError["返回权限不足错误"]
AuthValid --> |是| TrimCookie["清理Cookie空白字符"]
TrimCookie --> GetClient["获取Ctrip客户端实例"]
GetClient --> QueryUserInfo["查询用户信息"]
QueryUserInfo --> UserInfoValid{"用户信息有效?"}
UserInfoValid --> |否| ReturnInvalid["返回Cookie失效"]
UserInfoValid --> |是| CheckExist["检查账户是否已存在"]
CheckExist --> Exist{"账户已存在?"}
Exist --> |是| ReturnExist["返回账户已存在错误"]
Exist --> |否| QueryBalance["查询账户余额"]
QueryBalance --> BalanceValid{"余额查询成功?"}
BalanceValid --> |否| ReturnBalanceError["返回余额查询失败"]
BalanceValid --> |是| AddAccount["添加账户到数据库"]
AddAccount --> TriggerConsume["触发订单验证和消费"]
TriggerConsume --> End([结束])
```
**图示来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go)
- [card_info_c_trip_v1_account_list.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_list.go)
**组件来源**
- [card_info_c_trip_v1_account_create.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_create.go#L20-L55)
- [card_info_c_trip_v1_account_list.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_list.go#L10-L55)
### 卡密兑换功能分析
卡密兑换功能是系统的核心业务之一负责处理用户提交的卡密兑换请求并与Ctrip API进行交互完成兑换操作
#### 卡密兑换流程
```mermaid
flowchart TD
Start([开始]) --> LogRequest["记录请求日志"]
LogRequest --> GetOrderService["获取订单服务实例"]
GetOrderService --> AddOrder["添加兑换订单"]
AddOrder --> AddSuccess{"添加成功?"}
AddSuccess --> |否| EndWithError["结束并返回错误"]
AddSuccess --> |是| TriggerValidate["触发验证和消费"]
TriggerValidate --> End([结束])
```
**图示来源**
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go)
**组件来源**
- [card_info_c_trip_v1_submit.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_submit.go#L1-L30)
- [order.go](file://api/card_info_c_trip/v1/order.go#L1-L22)
### 订单回调处理分析
订单回调功能允许系统手动触发订单状态更新的回调通知确保上游系统能够及时获取订单处理结果
#### 回调处理流程
```mermaid
flowchart TD
Start([开始]) --> AuthCheck["验证用户权限"]
AuthCheck --> OrderCheck["查询订单信息"]
OrderCheck --> OrderExists{"订单存在?"}
OrderExists --> |否| ReturnError["返回订单不存在"]
OrderExists --> |是| OwnerCheck["验证订单归属"]
OwnerCheck --> OwnerValid{"权限匹配?"}
OwnerCheck --> |否| ReturnAuthError["返回权限不足"]
OwnerValid --> CallbackStatus{"已回调过?"}
CallbackStatus --> |是| ReturnCallbacked["返回已回调"]
CallbackStatus --> |否| OrderStatus{"订单状态完成?"}
OrderStatus --> |否| ReturnNotFinished["返回未完成"]
OrderStatus --> |是| AmountDiff{"金额异议?"}
AmountDiff --> |是| ReturnNotAllow["返回不支持"]
AmountDiff --> |否| TriggerCallback["触发回调"]
TriggerCallback --> End([结束])
```
**图示来源**
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go)
**组件来源**
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go#L1-L53)
- [order.go](file://api/card_info_c_trip/v1/order.go#L21-L55)
### 配置管理分析
系统提供Ctrip兑换配置的获取和设置功能允许管理员调整平台的运营参数
#### 配置获取流程
```mermaid
flowchart TD
Start([开始]) --> InitRes["初始化响应对象"]
InitRes --> GetAllowDiff["获取金额异议设置"]
GetAllowDiff --> GetMinAmount["获取最小充值金额"]
GetMinAmount --> GetSucceedCallback["获取成功回调设置"]
GetSucceedCallback --> GetFailCallback["获取失败回调设置"]
GetFailCallback --> GetCompensated["获取补卡回调设置"]
GetCompensated --> GetRate["获取充值速率"]
GetRate --> ReturnRes["返回配置信息"]
ReturnRes --> End([结束])
```
**图示来源**
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go)
**组件来源**
- [card_info_c_trip_v1_redeem_config_get.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_get.go#L1-L24)
- [card_info_c_trip_v1_redeem_config_set.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_redeem_config_set.go#L1-L18)
- [config.go](file://api/card_info_c_trip/v1/config.go)
## 依赖分析
系统通过清晰的依赖关系实现了Ctrip平台的集成各组件之间的依赖关系如下
```mermaid
classDiagram
class CtripClient {
+BindCard(ctx, input) result, err
+QueryBalance(ctx, input) result, err
+QueryUserInfo(ctx, cookie) result, err
}
class CardRedeemOrderService {
+AddOne(ctx, input) result, err
+TriggerValidateAndConsume() err
+CallBackOrderToUpstream(ctx, orderNo, force) err
}
class CardRedeemAccountService {
+Add(ctx, input, tx) err
+List(ctx, input) total, list, err
+UpdateStatus(ctx, id, status, tx) err
+Delete(ctx, id, category, tx) err
}
class SysConfigDictService {
+GetIsAllowRedeemCardDifferentAmount(ctx, category) bool, err
+SetIsAllowRedeemCardDifferentAmount(ctx, category, value) err
+GetRedeemCardMinAmount(ctx, category) int64
+SetRedeemCardMinAmount(ctx, category, value) err
}
class AccountController {
+AccountCreate(ctx, req) res, err
+AccountList(ctx, req) res, err
+AccountUpdateStatus(ctx, req) res, err
+AccountDelete(ctx, req) res, err
}
class OrderController {
+Submit(ctx, req) res, err
+List(ctx, req) res, err
+OrderCallback(ctx, req) res, err
}
class ConfigController {
+RedeemConfigGet(ctx, req) res, err
+RedeemConfigSet(ctx, req) res, err
}
AccountController --> CardRedeemAccountService : "使用"
OrderController --> CardRedeemOrderService : "使用"
ConfigController --> SysConfigDictService : "使用"
AccountController --> CtripClient : "通过服务层使用"
OrderController --> CtripClient : "通过服务层使用"
CardRedeemOrderService --> CtripClient : "直接使用"
CardRedeemAccountService --> CtripClient : "直接使用"
```
**图示来源**
- [redeem.go](file://utility/integration/redeem/redeem.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
- [card_redeem_account.go](file://internal/service/card_redeem_account.go)
- [sys_config_dict.go](file://internal/service/sys_config_dict.go)
## 性能考虑
系统在设计时考虑了性能优化主要体现在以下几个方面
- 使用缓存机制减少对Ctrip API的重复调用
- 实现接口限流防止恶意请求
- 异步处理订单验证和消费
- 批量操作支持提高处理效率
## 故障排除指南
### 常见问题及解决方案
| 问题现象 | 可能原因 | 解决方案 |
|---------|--------|---------|
| 回调验证失败 | 权限不足或订单状态不正确 | 检查用户权限和订单状态确保订单已完成处理 |
| 账户状态同步延迟 | 缓存机制导致数据延迟 | 调整缓存时间或手动刷新账户状态 |
| 兑换结果不明确 | Ctrip API返回信息不清晰 | 检查API返回的原始数据增加日志记录 |
| Cookie检测不可用 | Cookie已过期或格式错误 | 重新获取有效Cookie确保格式正确 |
| 配置更新不生效 | 缓存未刷新或服务未重启 | 清除相关缓存必要时重启服务 |
**组件来源**
- [card_info_c_trip_v1_account_cookie_check.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_account_cookie_check.go#L1-L48)
- [card_info_c_trip_v1_order_callback.go](file://internal/controller/card_info_c_trip/card_info_c_trip_v1_order_callback.go#L1-L53)
## 结论
kami_backend通过redeem/ctrip包实现了与Ctrip平台的完整集成提供了账户管理卡密兑换订单回调等核心功能系统采用分层架构设计具有良好的可维护性和扩展性通过合理的认证机制错误处理策略和性能优化确保了系统的稳定运行

View File

@@ -0,0 +1,280 @@
# 京东平台集成
<cite>
**本文档引用文件**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_jd_v1_account_list.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_list.go)
- [place.go](file://internal/logic/card_redeem_cookie/place.go)
- [order.go](file://internal/logic/card_redeem_cookie/order.go)
- [client.go](file://utility/integration/originalJd/client.go)
- [client.go](file://utility/integration/redeem/client/client.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
- [originalJd/enums.go](file://utility/integration/originalJd/enums.go)
- [card_jd.go](file://internal/consts/card_jd.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考量](#性能考量)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend如何通过`redeem/jd`包集成京东API涵盖京东卡密兑换账户管理订单查询等功能的实现机制文档深入解析了京东客户端的认证方式如Cookie认证API调用模式错误处理策略和重试机制同时提供京东API的配置参数说明请求/响应数据结构状态码含义和性能优化建议并解释集成过程中的技术决策如HTTP客户端配置超时设置和连接池大小选择最后提供常见集成问题的故障排除指南
## 项目结构
京东平台集成功能主要分布在`api/card_redeem_jd``internal/controller/card_redeem_jd`目录下通过`utility/integration/originalJd``utility/integration/redeem`实现底层京东API调用系统采用分层架构API层定义接口控制器层处理业务逻辑服务层封装核心功能集成层负责与京东API通信
```mermaid
graph TB
subgraph "API层"
A[card_redeem_jd]
A1[account.go]
A2[order.go]
end
subgraph "控制器层"
B[card_redeem_jd]
B1[account_list.go]
B2[place_order.go]
end
subgraph "服务层"
C[card_redeem_cookie.go]
end
subgraph "集成层"
D[originalJd]
D1[client.go]
E[redeem]
E1[client.go]
end
A --> B
B --> C
C --> D
C --> E
```
**图示来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [client.go](file://utility/integration/originalJd/client.go)
**章节来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
## 核心组件
核心组件包括京东账户管理订单处理Cookie认证和API客户端系统通过`CardRedeemJdV1`接口定义京东相关操作包括账户增删改查状态管理订单查询和下单功能服务层`ICardRedeemCookie`接口封装了底层业务逻辑`originalJd.Client`负责与京东API进行实际通信
**章节来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
## 架构概览
系统采用分层架构设计从API接口到京东API调用形成清晰的调用链路用户请求首先通过API层进入由控制器处理并调用服务层服务层协调业务逻辑并调用集成层的京东客户端最终完成与京东API的交互
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API接口"
participant Controller as "控制器"
participant Service as "服务层"
participant ClientJd as "京东客户端"
participant JD as "京东API"
Client->>API : 发送请求
API->>Controller : 调用处理方法
Controller->>Service : 调用业务逻辑
Service->>ClientJd : 调用京东客户端
ClientJd->>JD : HTTP请求
JD-->>ClientJd : 响应数据
ClientJd-->>Service : 返回结果
Service-->>Controller : 返回处理结果
Controller-->>API : 返回响应
API-->>Client : 返回最终结果
Note over Client,JD : 京东API集成完整调用流程
```
**图示来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
- [client.go](file://utility/integration/originalJd/client.go)
## 详细组件分析
### 账户管理分析
账户管理功能提供京东Cookie账户的全生命周期管理包括添加更新查询删除和状态管理系统通过`AccountAdd``AccountUpdate``AccountGet``AccountList``AccountDelete``AccountStatus`等接口实现账户操作
```mermaid
classDiagram
class AccountEntity {
+string Name
+string Cookie
+CardRedeemCookieStatus Status
+string Notes
}
class AccountAddReq {
+AccountEntity
}
class AccountUpdateReq {
+AccountEntity
+CommonIntId
}
class AccountGetReq {
+CommonIntId
}
class AccountListReq {
+CommonPageReq
+CardRedeemCookieStatus Status
+string Name
+string Cookie
}
class AccountDeleteReq {
+CommonIntId
}
class AccountStatusReq {
+CommonIntId
+CardRedeemCookieStatus Status
}
AccountAddReq --> AccountEntity
AccountUpdateReq --> AccountEntity
AccountGetReq --> CommonIntId
AccountListReq --> CommonPageReq
AccountDeleteReq --> CommonIntId
AccountStatusReq --> CommonIntId
```
**图示来源**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
**章节来源**
- [account.go](file://api/card_redeem_jd/v1/account.go)
- [card_redeem_jd_v1_account_list.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_account_list.go)
### 订单处理分析
订单处理功能包括订单查询和下单操作系统通过`OrderList`接口查询订单列表通过`PlaceOrder`接口创建新订单下单流程涉及账户调度京东API调用订单状态更新和支付链接生成
```mermaid
flowchart TD
Start([下单请求]) --> ValidateInput["验证输入参数"]
ValidateInput --> InputValid{"参数有效?"}
InputValid --> |否| ReturnError["返回错误"]
InputValid --> |是| ScheduleAccount["调度京东账户"]
ScheduleAccount --> AccountValid{"账户有效?"}
AccountValid --> |否| ReturnError
AccountValid --> |是| CallJD["调用京东API"]
CallJD --> JDSuccess{"京东返回成功?"}
JDSuccess --> |否| UpdateStatus["更新账户状态"]
JDSuccess --> |是| SaveOrder["保存订单信息"]
SaveOrder --> GenerateLink["生成支付链接"]
GenerateLink --> ReturnSuccess["返回成功响应"]
UpdateStatus --> ReturnError
ReturnError --> End([结束])
ReturnSuccess --> End
```
**图示来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [place.go](file://internal/logic/card_redeem_cookie/place.go)
- [client.go](file://utility/integration/originalJd/client.go)
**章节来源**
- [order.go](file://api/card_redeem_jd/v1/order.go)
- [card_redeem_jd_v1_place_order.go](file://internal/controller/card_redeem_jd/card_redeem_jd_v1_place_order.go)
### 认证机制分析
系统采用Cookie认证方式与京东API交互京东账户信息包含Cookie字符串系统通过`originalJd.Client`使用这些Cookie进行API调用当Cookie失效时系统会自动更新账户状态为"expired"
```mermaid
sequenceDiagram
participant System as "系统"
participant JD as "京东API"
participant Account as "京东账户"
System->>Account : 获取有效账户
Account-->>System : 返回账户信息(含Cookie)
System->>JD : 调用API(携带Cookie)
alt Cookie有效
JD-->>System : 返回成功响应
System->>Account : 记录成功交易
else Cookie失效
JD-->>System : 返回CK错误
System->>Account : 更新状态为expired
System->>Account : 调度新账户
end
System-->>调用方 : 返回处理结果
```
**图示来源**
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
- [place.go](file://internal/logic/card_redeem_cookie/place.go)
- [client.go](file://utility/integration/originalJd/client.go)
**章节来源**
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
- [place.go](file://internal/logic/card_redeem_cookie/place.go)
## 依赖分析
系统依赖关系清晰上层组件依赖下层服务形成单向依赖链API层依赖控制器层控制器层依赖服务层服务层依赖集成层集成层直接与外部京东API通信
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[集成层]
D --> E[京东API]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#f96,stroke:#333
style D fill:#6f9,stroke:#333
style E fill:#9f9,stroke:#333
click A "api/card_redeem_jd"
click B "internal/controller/card_redeem_jd"
click C "internal/service/card_redeem_cookie"
click D "utility/integration/originalJd"
```
**图示来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
- [client.go](file://utility/integration/originalJd/client.go)
**章节来源**
- [card_redeem_jd.go](file://api/card_redeem_jd/card_redeem_jd.go)
- [card_redeem_cookie.go](file://internal/service/card_redeem_cookie.go)
## 性能考量
系统在性能方面进行了多项优化包括连接池管理请求超时控制和错误重试机制京东API客户端使用GoFrame的gclient支持连接复用和超时设置确保高并发场景下的稳定性能
**章节来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [topsdk/topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
## 故障排除指南
### 认证失败
当出现认证失败时检查京东Cookie是否有效系统会自动检测Cookie状态若返回CK错误账户状态将被更新为"expired"解决方案包括重新获取有效Cookie并更新账户信息
### 接口限流
系统对接口访问进行了限流控制同一用户一分钟内最多访问5次若出现"操作过于频繁"错误需等待一段时间后重试可通过调整`limiter.CardInfoJdAccountCookieChecker`的配置参数来修改限流规则
### 数据格式不匹配
当出现数据格式不匹配错误时检查请求参数是否符合API定义特别是金额字段应为浮点数订单ID应为字符串确保请求Content-Type为application/json并正确序列化请求体
### 账户状态异常
系统定义了多种账户状态包括"normal"(正常)"disable"(禁用)"expired"(时效)"tmpDisable"(临时禁用)当账户状态异常时可根据具体状态采取相应措施如重新激活禁用账户或更新失效Cookie
**章节来源**
- [card_redeem_cookie.go](file://internal/consts/card_redeem_cookie.go)
- [card_jd.go](file://internal/consts/card_jd.go)
- [card_redeem.go](file://internal/consts/card_redeem.go)
## 结论
kami_backend通过`redeem/jd`包实现了完整的京东平台集成支持卡密兑换账户管理和订单查询等核心功能系统采用分层架构设计具有良好的可维护性和扩展性通过Cookie认证机制与京东API通信实现了稳定可靠的集成方案文档详细说明了各组件的功能交互流程和错误处理策略为后续维护和扩展提供了完整的技术参考

View File

@@ -0,0 +1,249 @@
# 天猫平台集成
<cite>
**本文档引用文件**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend如何通过tmall包集成天猫API重点涵盖天猫游戏卡密充值账户授权订单处理等功能的实现机制文档深入解析了天猫客户端的OAuth认证流程TOP API调用模式消息队列处理和错误恢复机制同时提供天猫API的配置参数说明请求/响应数据结构状态码含义和性能优化建议并解释集成过程中的技术决策与常见问题解决方案
## 项目结构
天猫平台集成功能主要分布在`api/card_info_t_mall_game``internal/controller/card_info_t_mall_game``internal/model``utility/cron`等目录中核心功能包括账户授权订单提交状态查询和数据同步
```mermaid
graph TD
subgraph "API接口层"
A[account.go]
B[order.go]
C[sync.go]
end
subgraph "控制器层"
D[card_info_t_mall_game/]
E[authorize_callback.go]
F[order_submit.go]
G[data_sync.go]
end
subgraph "模型层"
H[card_t_mall_game_account.go]
I[card_t_mall_game_order.go]
end
subgraph "定时任务"
J[cron/t_mall_game_data_sync.go]
end
A --> D
B --> D
C --> D
D --> H
D --> I
J --> D
```
**图示来源**
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [card_t_mall_game_account.go](file://internal/model/card_t_mall_game_account.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
**章节来源**
- [api/card_info_t_mall_game](file://api/card_info_t_mall_game)
- [internal/controller/card_info_t_mall_game](file://internal/controller/card_info_t_mall_game)
- [internal/model](file://internal/model)
- [utility/cron](file://utility/cron)
## 核心组件
核心组件包括天猫账户授权订单提交订单查询和数据同步功能系统通过OAuth2.0实现天猫店铺授权使用TOP API进行订单创建和状态同步并通过定时任务实现数据的周期性同步
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
## 架构概述
系统采用分层架构包括API接口层控制器层服务层和数据访问层天猫集成通过独立的控制器处理所有天猫相关请求使用统一的数据模型进行数据交换并通过定时任务实现与天猫平台的数据同步
```mermaid
graph TB
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(数据库)]
Cron[定时任务] --> API
API --> External[天猫平台]
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
## 详细组件分析
### 账户授权分析
天猫账户授权通过OAuth2.0协议实现系统提供授权回调接口处理天猫返回的授权码并使用TOP SDK完成令牌交换
```mermaid
sequenceDiagram
participant 用户
participant kami_backend
participant 天猫平台
用户->>kami_backend : 请求授权
kami_backend->>天猫平台 : 重定向到天猫授权页面
天猫平台->>用户 : 显示授权页面
用户->>天猫平台 : 同意授权
天猫平台->>kami_backend : 回调携带授权码
kami_backend->>kami_backend : 调用OAuth2Login获取访问令牌
kami_backend->>用户 : 返回授权结果
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [account.go](file://api/card_info_t_mall_game/v1/account.go)
### 订单处理分析
订单处理流程包括订单创建状态查询和数据同步确保订单状态的准确性和一致性
#### 订单创建流程
```mermaid
flowchart TD
Start([接收订单请求]) --> Validate["验证账号信息"]
Validate --> AccountValid{"账号有效?"}
AccountValid --> |否| ReturnError["返回账号错误"]
AccountValid --> |是| CreateOrder["创建订单记录"]
CreateOrder --> SaveDB["保存到数据库"]
SaveDB --> ReturnSuccess["返回订单号"]
ReturnError --> End([结束])
ReturnSuccess --> End
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
#### 订单查询流程
```mermaid
flowchart TD
Start([接收查询请求]) --> FindOrder["查找订单"]
FindOrder --> OrderExists{"订单存在?"}
OrderExists --> |否| ReturnEmpty["返回空结果"]
OrderExists --> |是| GetAccount["获取关联账号"]
GetAccount --> GetShop["获取店铺信息"]
GetShop --> Assemble["组装响应数据"]
Assemble --> ReturnResult["返回查询结果"]
ReturnEmpty --> End([结束])
ReturnResult --> End
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_order_submit.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_submit.go)
- [card_info_t_mall_game_v1_t_mall_game_order_query_order.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_order_query_order.go)
- [order.go](file://api/card_info_t_mall_game/v1/order.go)
- [card_t_mall_game_order.go](file://internal/model/card_t_mall_game_order.go)
### 数据同步分析
数据同步机制通过定时任务定期从天猫平台拉取最新数据确保本地数据库与天猫平台数据的一致性
```mermaid
sequenceDiagram
participant Cron as "定时任务"
participant API as "API服务"
participant DB as "本地数据库"
participant TMall as "天猫平台"
Cron->>API : 发起数据同步请求
API->>TMall : 调用天猫API获取数据
TMall-->>API : 返回最新数据
API->>DB : 保存账号数据
API->>DB : 保存店铺数据
API->>DB : 保存订单数据
API->>DB : 保存历史数据
DB-->>API : 确认保存结果
API-->>Cron : 返回同步结果
```
**图示来源**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
**章节来源**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
- [sync.go](file://api/card_info_t_mall_game/v1/sync.go)
## 依赖分析
系统依赖于天猫TOP SDK进行API调用依赖数据库存储账户和订单信息并通过配置中心管理天猫API的配置参数
```mermaid
graph TD
kami_backend --> tmall_sdk[天猫TOP SDK]
kami_backend --> database[MySQL数据库]
kami_backend --> config[配置中心]
kami_backend --> cron[定时任务系统]
tmall_sdk --> tmall_api[天猫API]
database --> storage[数据存储]
config --> settings[AppKey, AppSecret等]
```
**图示来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [config.go](file://utility/config/config.go)
## 性能考虑
为确保系统性能采用了以下优化措施
- 使用数据库索引加速订单和账户查询
- 实现数据缓存减少重复查询
- 采用批量操作提高数据同步效率
- 设置合理的超时时间避免请求堆积
- 通过分页查询控制单次返回数据量
## 故障排除指南
### OAuth令牌过期
当OAuth令牌过期时系统会返回授权错误解决方案是重新发起授权流程获取新的访问令牌
**章节来源**
- [card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_account_authorize_callback.go)
### 消息重复消费
通过订单号的唯一性约束和幂等性设计确保即使消息重复消费也不会产生重复订单
### 订单状态不一致
通过定时数据同步机制定期校准本地订单状态与天猫平台状态解决状态不一致问题
**章节来源**
- [t_mall_game_data_sync.go](file://utility/cron/t_mall_game_data_sync.go)
- [card_info_t_mall_game_v1_t_mall_game_data_sync.go](file://internal/controller/card_info_t_mall_game/card_info_t_mall_game_v1_t_mall_game_data_sync.go)
## 结论
kami_backend通过完善的天猫平台集成方案实现了稳定的账户授权订单处理和数据同步功能系统采用分层架构和定时同步机制确保了与天猫平台的数据一致性同时提供了完整的错误处理和故障排除机制

View File

@@ -0,0 +1,310 @@
# 沃尔玛平台集成
<cite>
**本文档引用文件**
- [walmart/api.go](file://utility/integration/redeem/walmart/api.go)
- [account.go](file://api/card_info_walmart/v1/account.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
- [config.go](file://api/card_info_walmart/v1/config.go)
- [group.go](file://api/card_info_walmart/v1/group.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_info_walmart_v1_order_history.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_history.go)
- [card_info_walmart_v1_redeem_config_get.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_redeem_config_get.go)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend如何通过redeem/walmart包集成沃尔玛API涵盖沃尔玛账户管理卡密兑换订单处理等功能的实现机制重点解析了沃尔玛客户端的认证方式API调用模式分组管理策略和错误处理机制文档还提供了核心功能的调用示例配置参数说明数据结构定义状态码含义及性能优化建议并解释了关键技术决策背后的原理
## 项目结构
kami_backend项目中与沃尔玛平台集成相关的文件主要分布在`api/card_info_walmart``utility/integration/redeem/walmart`目录下该结构实现了清晰的分层设计将API接口定义控制器逻辑和第三方服务集成分离
```mermaid
graph TB
subgraph API层
A[account.go]
B[order.go]
C[config.go]
D[group.go]
end
subgraph 控制器层
E[card_info_walmart_v1_account_create.go]
F[card_info_walmart_v1_submit.go]
G[card_info_walmart_v1_order_history.go]
H[card_info_walmart_v1_redeem_config_get.go]
I[card_info_walmart_v1_group_add.go]
J[card_info_walmart_v1_group_list.go]
end
subgraph 集成层
K[utility/integration/redeem/walmart/api.go]
end
A --> E
B --> F
B --> G
C --> H
D --> I
D --> J
E --> K
F --> K
G --> K
H --> K
I --> K
J --> K
```
**图示来源**
- [account.go](file://api/card_info_walmart/v1/account.go)
- [order.go](file://api/card_info_walmart/v1/order.go)
- [config.go](file://api/card_info_walmart/v1/config.go)
- [group.go](file://api/card_info_walmart/v1/group.go)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_info_walmart_v1_order_history.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_order_history.go)
- [card_info_walmart_v1_redeem_config_get.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_redeem_config_get.go)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go)
**章节来源**
- [api/card_info_walmart](file://api/card_info_walmart)
- [internal/controller/card_info_walmart](file://internal/controller/card_info_walmart)
- [utility/integration/redeem/walmart](file://utility/integration/redeem/walmart)
## 核心组件
沃尔玛平台集成的核心组件包括账户管理订单处理配置管理和分组管理四大模块这些组件通过清晰的接口定义和分层架构协同工作实现了对沃尔玛API的完整封装和业务逻辑处理
**章节来源**
- [account.go](file://api/card_info_walmart/v1/account.go#L1-L242)
- [order.go](file://api/card_info_walmart/v1/order.go#L1-L92)
- [config.go](file://api/card_info_walmart/v1/config.go#L1-L40)
- [group.go](file://api/card_info_walmart/v1/group.go#L1-L81)
## 架构概述
沃尔玛平台集成采用分层架构设计从上至下分为API接口层控制器层和集成服务层这种设计模式实现了关注点分离提高了代码的可维护性和可测试性
```mermaid
graph TD
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> Integration[沃尔玛集成]
Integration --> WalmartAPI[沃尔玛API]
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style Integration fill:#69f,stroke:#333
style WalmartAPI fill:#9f9,stroke:#333
```
**图示来源**
- [walmart/api.go](file://utility/integration/redeem/walmart/api.go#L1-L3)
- [account.go](file://api/card_info_walmart/v1/account.go#L1-L242)
- [order.go](file://api/card_info_walmart/v1/order.go#L1-L92)
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go#L1-L73)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L1-L32)
## 详细组件分析
### 账户管理分析
账户管理组件负责沃尔玛账户的创建更新删除和状态检测系统通过Cookie进行身份验证并在创建账户时验证Cookie的有效性
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 服务层
participant ClientInt as 沃尔玛客户端
Client->>Controller : POST /cardInfo/walmart/account/create
Controller->>Service : LoginOnlyLogin()
Controller->>ClientInt : GetClient(WALMART)
Controller->>ClientInt : QueryUserInfoWithCache()
alt Cookie无效
ClientInt-->>Controller : 返回错误
Controller-->>Client : 400 Cookie失效
else Cookie有效
Controller->>Service : GetNormalOneByCk()
alt 账户已存在
Service-->>Controller : 返回存在信息
Controller-->>Client : 400 账号已存在
else 新账户
Controller->>ClientInt : QueryBalanceWithCache()
Controller->>Service : Add()创建账户
Service-->>Controller : 成功
Controller-->>Client : 200 创建成功
end
end
```
**图示来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go#L15-L73)
- [walmart/api.go](file://utility/integration/redeem/walmart/api.go#L1-L3)
**章节来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go#L1-L73)
- [account.go](file://api/card_info_walmart/v1/account.go#L1-L242)
### 订单处理分析
订单处理组件负责卡密兑换请求的接收处理和状态查询系统采用异步处理模式接收到兑换请求后立即返回响应后台任务负责实际的兑换操作
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 服务层
Client->>Controller : POST /cardInfo/walmart/order/submit
Controller->>Service : AddOne()添加订单
Service-->>Controller : 订单创建成功
Controller->>Client : 200 提交成功
Controller->>Service : TriggerValidateAndConsume()
Note right of Service : 触发后台验证和消费任务
```
**图示来源**
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L15-L32)
- [order.go](file://api/card_info_walmart/v1/order.go#L1-L92)
**章节来源**
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L1-L32)
- [order.go](file://api/card_info_walmart/v1/order.go#L1-L92)
### 配置管理分析
配置管理组件提供了沃尔玛平台各项参数的获取和设置功能包括最小充值金额是否允许金额异议单账户最大充值次数等关键业务规则
```mermaid
flowchart TD
Start([获取配置]) --> GetConfig["GetIsAllowRedeemCardDifferentAmount()"]
GetConfig --> GetMinAmount["GetRedeemCardMinAmount()"]
GetMinAmount --> GetCallback["GetRedeemCardSucceedCallbackIsAllow()"]
GetCallback --> GetFailCallback["GetRedeemCardFailCallbackIsAllow()"]
GetFailCallback --> GetCompensated["GetRedeemCardCompensatedAutoCallback()"]
GetCompensated --> GetRate["GetRedeemCardRate()"]
GetRate --> GetRepeated["GetIsAllowedRepeated()"]
GetRepeated --> GetMaxCount["GetMaxAccountRedeemCount()"]
GetMaxCount --> GetStrategy["GetRedeemScheduleStrategy()"]
GetStrategy --> Return["返回配置对象"]
Return --> End([配置获取完成])
```
**图示来源**
- [card_info_walmart_v1_redeem_config_get.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_redeem_config_get.go#L1-L23)
- [config.go](file://api/card_info_walmart/v1/config.go#L1-L40)
**章节来源**
- [card_info_walmart_v1_redeem_config_get.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_redeem_config_get.go#L1-L23)
- [config.go](file://api/card_info_walmart/v1/config.go#L1-L40)
### 分组管理分析
分组管理组件允许用户将沃尔玛账户组织到不同的分组中便于批量管理和统计分析每个分组可以独立配置和管理
```mermaid
classDiagram
class GroupRecord {
+string Name
+string Notes
}
class GroupAddReq {
+GroupRecord
}
class GroupUpdateReq {
+int ID
+GroupRecord
}
class GroupListReq {
+int Page
+int Size
+string UserId
+string Name
}
class GroupListRes {
+int Total
+[]*entity.V1CardRedeemAccountGroup List
}
class GroupDeleteReq {
+int ID
}
GroupAddReq --> GroupRecord : 包含
GroupUpdateReq --> GroupRecord : 包含
GroupListRes --> V1CardRedeemAccountGroup : 列表
```
**图示来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L1-L81)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go#L1-L40)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go#L1-L37)
**章节来源**
- [group.go](file://api/card_info_walmart/v1/group.go#L1-L81)
- [card_info_walmart_v1_group_add.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_add.go#L1-L40)
- [card_info_walmart_v1_group_list.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_group_list.go#L1-L37)
## 依赖分析
沃尔玛平台集成主要依赖于系统核心服务和第三方集成库这些依赖关系确保了功能的完整性和系统的稳定性
```mermaid
graph TD
WalmartIntegration[沃尔玛集成] --> SysAuth[认证服务]
WalmartIntegration --> CardRedeemAccount[账户服务]
WalmartIntegration --> CardRedeemOrder[订单服务]
WalmartIntegration --> SysConfigDict[配置字典服务]
SysAuth --> Database[(数据库)]
CardRedeemAccount --> Database
CardRedeemOrder --> Database
SysConfigDict --> Database
WalmartIntegration --> Cache[缓存服务]
WalmartIntegration --> Trace[追踪服务]
style WalmartIntegration fill:#f96,stroke:#333
style SysAuth fill:#6f9,stroke:#333
style CardRedeemAccount fill:#6f9,stroke:#333
style CardRedeemOrder fill:#6f9,stroke:#333
style SysConfigDict fill:#6f9,stroke:#333
style Cache fill:#69f,stroke:#333
style Trace fill:#69f,stroke:#333
style Database fill:#9f9,stroke:#333
```
**图示来源**
- [card_info_walmart_v1_account_create.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_create.go#L15-L73)
- [card_info_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go#L15-L32)
- [card_info_walmart_v1_redeem_config_get.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_redeem_config_get.go#L1-L23)
**章节来源**
- [internal/service](file://internal/service)
- [utility/cache](file://utility/cache)
- [utility/config](file://utility/config)
## 性能考虑
沃尔玛平台集成在设计时充分考虑了性能因素系统采用缓存机制减少对沃尔玛API的频繁调用使用异步处理模式提高响应速度并通过分组管理实现批量操作的效率优化配置参数中的"RedeemCardRate"字段用于控制兑换速率防止因请求过于频繁而被沃尔玛API限流
## 故障排除指南
### 分组管理冲突
当出现分组名称冲突时系统会返回"分组已存在"的错误信息解决方案是使用唯一的分组名称或先删除已存在的分组再创建
### 账户状态不一致
账户状态不一致通常由缓存延迟引起可通过调用"AccountRefreshStatus"接口强制刷新账户状态或等待缓存过期后自动更新
### 兑换速率限制
当遇到兑换速率限制时应检查"RedeemCardRate"配置值是否过高建议根据沃尔玛API的实际限制调整此参数并实现指数退避重试机制
### Cookie失效
Cookie失效会导致账户验证失败解决方案是重新获取有效的Cookie并更新账户信息或实现自动Cookie刷新机制
**章节来源**
- [card_info_walmart_v1_account_refresh_status.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_refresh_status.go#L1-L13)
- [card_info_walmart_v1_account_status_detect.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_account_status_detect.go#L1-L38)
- [config.go](file://api/card_info_walmart/v1/config.go#L1-L40)
## 结论
kami_backend对沃尔玛平台的集成设计合理功能完整通过分层架构实现了良好的代码组织利用分组管理策略提高了账户管理效率采用异步处理模式优化了系统性能集成方案充分考虑了错误处理和性能优化为稳定可靠的沃尔玛卡密兑换服务提供了坚实的基础

View File

@@ -0,0 +1,247 @@
# 电商平台集成
<cite>
**本文档引用文件**
- [client.go](file://utility/integration/originalJd/client.go)
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [api.go](file://utility/integration/redeem/jd/api.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
- [api.go](file://utility/integration/redeem/walmart/api.go)
- [models.go](file://utility/integration/tmall/models.go)
- [errHandler.go](file://internal/errHandler/handler.go)
- [code.go](file://internal/errHandler/code.go)
- [config.go](file://utility/config/config.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend电商平台如何通过integration包集成京东天猫Ctrip和沃尔玛等第三方电商平台的API重点阐述了各平台客户端的实现机制包括认证方式API调用模式错误处理策略和重试机制文档还提供了核心功能调用示例配置参数说明数据结构定义和性能优化建议
## 项目结构
kami_backend的电商平台集成功能主要集中在`utility/integration`目录下每个第三方平台都有独立的子包实现其API集成系统通过统一的HTTP客户端配置与各平台通信并采用标准化的错误处理机制
```mermaid
graph TB
subgraph "集成层"
JD[京东集成]
Tmall[天猫集成]
Ctrip[Ctrip集成]
Walmart[沃尔玛集成]
end
subgraph "核心服务"
HTTPClient[HTTP客户端]
ErrorHandler[错误处理器]
ConfigManager[配置管理]
end
JD --> HTTPClient
Tmall --> HTTPClient
Ctrip --> HTTPClient
Walmart --> HTTPClient
HTTPClient --> ErrorHandler
ConfigManager --> JD
ConfigManager --> Tmall
ConfigManager --> Ctrip
ConfigManager --> Walmart
```
**图示来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
**本节来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
## 核心组件
系统的核心集成组件包括京东天猫Ctrip和沃尔玛的API客户端实现每个客户端都封装了特定平台的认证机制请求格式和响应处理逻辑集成层通过统一的接口抽象使上层业务逻辑能够以一致的方式调用不同平台的API
**本节来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [api.go](file://utility/integration/redeem/jd/api.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
- [api.go](file://utility/integration/redeem/walmart/api.go)
## 架构概述
电商平台集成架构采用分层设计上层为业务控制器中间为服务逻辑层底层为第三方API集成层集成层使用统一的HTTP客户端配置确保所有外部API调用具有一致的超时设置连接池管理和错误处理策略
```mermaid
graph TD
A[业务控制器] --> B[服务逻辑层]
B --> C[京东API客户端]
B --> D[天猫API客户端]
B --> E[Ctrip API客户端]
B --> F[沃尔玛API客户端]
C --> G[HTTP客户端]
D --> G
E --> G
F --> G
G --> H[错误处理器]
I[配置管理] --> C
I --> D
I --> E
I --> F
```
**图示来源**
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [config.go](file://utility/config/config.go)
## 详细组件分析
### 京东集成分析
京东集成通过originalJd包实现包含客户端初始化API调用和状态管理功能客户端采用基于AppKey和AppSecret的认证机制所有请求都经过签名处理
```mermaid
classDiagram
class JDClient {
+string AppKey
+string AppSecret
+string ServerUrl
+Execute(method string, data map[string]interface{}) string
-signRequest(data map[string]interface{}) string
}
class JDOrderService {
+submitOrder(orderInfo map[string]interface{}) map[string]interface{}
+queryOrder(orderNo string) map[string]interface{}
+refundOrder(orderNo string) map[string]interface{}
}
JDClient --> JDOrderService : "使用"
```
**图示来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [api.go](file://utility/integration/redeem/jd/api.go)
### 天猫集成分析
天猫集成使用topsdk实现完整的TOP API支持包括OAuth认证API请求签名和响应解析系统采用长连接和连接池优化性能
```mermaid
sequenceDiagram
participant 应用 as 应用层
participant 客户端 as TopClient
participant 天猫 as 天猫API
应用->>客户端 : 调用API方法
客户端->>客户端 : 构建请求参数
客户端->>客户端 : 生成签名
客户端->>天猫 : 发送HTTP请求
天猫-->>客户端 : 返回JSON响应
客户端->>客户端 : 验证签名
客户端->>客户端 : 解析响应
客户端-->>应用 : 返回结果
```
**图示来源**
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [oauth.go](file://utility/integration/tmall/api/oauth.go)
### Ctrip集成分析
Ctrip集成通过service层封装API调用提供充值兑换和账户查询等核心功能系统实现了自动重试机制以应对网络波动
```mermaid
flowchart TD
Start([开始]) --> Validate["验证请求参数"]
Validate --> CheckCache["检查缓存"]
CheckCache --> CacheHit{"缓存命中?"}
CacheHit --> |是| ReturnCache["返回缓存结果"]
CacheHit --> |否| CallAPI["调用Ctrip API"]
CallAPI --> APIResult{"调用成功?"}
APIResult --> |否| Retry{"重试次数<3?"}
Retry --> |是| Delay["等待1秒"]
Delay --> CallAPI
Retry --> |否| HandleError["处理错误"]
APIResult --> |是| UpdateCache["更新缓存"]
UpdateCache --> ReturnResult["返回结果"]
HandleError --> ReturnError["返回错误"]
ReturnCache --> End([结束])
ReturnResult --> End
ReturnError --> End
```
**图示来源**
- [service.go](file://utility/integration/redeem/ctrip/service.go)
- [api.go](file://utility/integration/redeem/ctrip/api.go)
### 沃尔玛集成分析
沃尔玛集成实现了完整的API客户端支持商品查询订单创建和状态同步功能系统采用JSON格式进行数据交换
```mermaid
classDiagram
class WalmartClient {
+string ApiKey
+string BaseUrl
+GetProduct(sku string) map[string]interface{}
+CreateOrder(orderData map[string]interface{}) map[string]interface{}
+GetOrderStatus(orderId string) map[string]interface{}
-makeRequest(endpoint string, method string, data map[string]interface{}) map[string]interface{}
}
class WalmartModel {
+string Sku
+string Name
+float Price
+int Quantity
}
WalmartClient --> WalmartModel : "使用"
```
**图示来源**
- [api.go](file://utility/integration/redeem/walmart/api.go)
- [models.go](file://utility/integration/redeem/walmart/models.go)
**本节来源**
- [client.go](file://utility/integration/originalJd/client.go)
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [service.go](file://utility/integration/redeem/ctrip/service.go)
- [api.go](file://utility/integration/redeem/walmart/api.go)
## 依赖分析
电商平台集成依赖于HTTP客户端配置管理和错误处理等核心组件各平台客户端共享相同的底层基础设施确保一致性和可维护性
```mermaid
graph TD
JDClient --> HTTPClient
TmallClient --> HTTPClient
CtripClient --> HTTPClient
WalmartClient --> HTTPClient
HTTPClient --> ConfigManager
HTTPClient --> ErrorHandler
ConfigManager --> Viper
ErrorHandler --> Logger
JDClient --> Crypto
TmallClient --> Crypto
```
**图示来源**
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [config.go](file://utility/config/config.go)
- [errHandler.go](file://internal/errHandler/handler.go)
**本节来源**
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
- [config.go](file://utility/config/config.go)
- [errHandler.go](file://internal/errHandler/handler.go)
## 性能考虑
系统在HTTP客户端配置中采用了多项性能优化措施包括连接池管理超时设置和长连接支持这些配置确保了高并发场景下的稳定性和响应速度
**本节来源**
- [topclient.go](file://utility/integration/tmall/topsdk/topclient.go)
## 故障排除指南
常见集成问题包括认证失败接口限流和数据格式不匹配系统提供了详细的错误码和日志记录便于快速定位和解决问题
**本节来源**
- [code.go](file://internal/errHandler/code.go)
- [errHandler.go](file://internal/errHandler/handler.go)
## 结论
kami_backend的电商平台集成架构设计合理通过统一的集成层抽象了不同平台的差异性提供了稳定可靠的API调用能力系统的错误处理性能优化和可维护性都达到了较高水平

View File

@@ -0,0 +1,407 @@
# 监控系统集成
<cite>
**Referenced Files in This Document**
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [handler.go](file://utility/otel/handler.go)
- [errors.go](file://utility/otel/errors.go)
- [main.go](file://main.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细说明了kami_backend项目中OpenTelemetry监控系统的集成实现文档涵盖了追踪(Tracing)指标(Metrics)和日志(Logging)的收集与导出机制解释了otel包的配置结构以及如何在控制器服务层和业务逻辑中创建和使用Span同时提供了监控系统常见问题的故障排除指南
## 项目结构
kami_backend项目的监控系统集成主要集中在`utility/otel`目录下该目录包含了OpenTelemetry的所有配置和实现代码监控系统与GoFrame框架深度集成通过统一的接口提供追踪日志和指标功能
```mermaid
graph TD
subgraph "监控系统"
otel[utility/otel]
config[config.go]
manager[manager.go]
utils[utils.go]
handler[handler.go]
errors[errors.go]
end
main[main.go] --> otel
internal[internal/] --> otel
api[api/] --> otel
otel --> config
otel --> manager
otel --> utils
otel --> handler
otel --> errors
```
**Diagram sources**
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [handler.go](file://utility/otel/handler.go)
- [errors.go](file://utility/otel/errors.go)
- [main.go](file://main.go)
**Section sources**
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [handler.go](file://utility/otel/handler.go)
- [errors.go](file://utility/otel/errors.go)
- [main.go](file://main.go)
## 核心组件
kami_backend的监控系统由几个核心组件构成配置管理管理器工具函数日志处理器和错误处理这些组件协同工作实现了完整的可观测性解决方案
**Section sources**
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [handler.go](file://utility/otel/handler.go)
- [errors.go](file://utility/otel/errors.go)
## 架构概述
kami_backend的监控系统采用分层架构设计各组件职责明确易于维护和扩展系统通过OpenTelemetry协议与后端监控系统通信支持追踪日志和指标的统一收集
```mermaid
graph TD
subgraph "应用层"
main[main.go]
controllers[Controllers]
services[Services]
logic[Business Logic]
end
subgraph "监控集成层"
otel[OpenTelemetry]
config[Config]
manager[Manager]
utils[Utils]
handler[Log Handler]
end
subgraph "导出层"
exporter[OTLP Exporter]
collector[Collector]
backend[Jaeger/Prometheus]
end
main --> config
main --> manager
controllers --> utils
services --> utils
logic --> utils
utils --> manager
manager --> exporter
exporter --> collector
collector --> backend
handler --> exporter
style otel fill:#f9f,stroke:#333,stroke-width:2px
style config fill:#bbf,stroke:#333,stroke-width:2px
style manager fill:#bbf,stroke:#333,stroke-width:2px
style utils fill:#bbf,stroke:#333,stroke-width:2px
style handler fill:#bbf,stroke:#333,stroke-width:2px
```
**Diagram sources**
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [handler.go](file://utility/otel/handler.go)
## 详细组件分析
### 配置管理分析
监控系统的配置管理通过`Config`结构体实现该结构体定义了所有必要的配置参数包括服务名称收集器URL安全设置压缩方式请求头超时时间采样率等
```mermaid
classDiagram
class Config {
+string ServiceName
+string CollectorURL
+bool Insecure
+string Compressor
+map[string]string Headers
+time.Duration Timeout
+float64 SampleRate
+bool Enable
+[]attribute.KeyValue ResourceAttrs
+DefaultConfig() *Config
+Validate() error
+Clone() *Config
}
Config : +ServiceName : 服务名称,用于标识监控数据来源
Config : +CollectorURL : OpenTelemetry收集器的URL地址
Config : +Insecure : 是否使用不安全连接HTTP而非HTTPS
Config : +Compressor : 数据压缩方式如gzip
Config : +Headers : 请求头,可用于认证等
Config : +Timeout : 请求超时时间
Config : +SampleRate : 采样率0.0-1.0之间
Config : +Enable : 是否启用监控
Config : +ResourceAttrs : 资源属性,用于添加额外的元数据
```
**Diagram sources**
- [config.go](file://utility/otel/config.go#L10-L30)
**Section sources**
- [config.go](file://utility/otel/config.go#L1-L68)
### 管理器分析
`Manager`是监控系统的核心负责初始化和管理追踪日志和指标的提供者它封装了OpenTelemetry SDK的复杂性提供了简洁的接口供应用层使用
```mermaid
classDiagram
class Manager {
-Config config
-resource.Resource resource
-trace.TracerProvider tracerProvider
-log.LoggerProvider logProvider
-[]func(context.Context) error shutdownFuncs
+NewOTelManager(config *Config) (*Manager, error)
+initTracing() error
+initLogging() error
+initMetrics() error
+Shutdown(ctx context.Context) error
+GetConfig() *Config
+GetResource() *resource.Resource
+IsTracingEnabled() bool
+IsLoggingEnabled() bool
+GetTracerProvider() *trace.TracerProvider
+GetLogProvider() *log.LoggerProvider
+CreateTracer(name string) oteltrace.Tracer
+CreateLogger(name string) otellog.Logger
}
Manager --> Config : "has"
Manager --> resource.Resource : "uses"
Manager --> trace.TracerProvider : "manages"
Manager --> log.LoggerProvider : "manages"
class Config {
<<struct>>
}
class resource.Resource {
<<struct>>
}
class trace.TracerProvider {
<<struct>>
}
class log.LoggerProvider {
<<struct>>
}
```
**Diagram sources**
- [manager.go](file://utility/otel/manager.go#L40-L60)
**Section sources**
- [manager.go](file://utility/otel/manager.go#L1-L258)
### 工具函数分析
工具函数层提供了简化使用的API使开发者能够轻松地在代码中添加监控功能而无需了解OpenTelemetry SDK的底层细节
```mermaid
classDiagram
class Utils {
+InitWithConfig(config *Config) error
+GetCurrentManager() *Manager
+Shutdown(ctx context.Context) error
+GetLogger() otellog.Logger
+CreateSpan(ctx context.Context, name string, opts ...oteltrace.SpanStartOption) (context.Context, oteltrace.Span)
+AddSpanAttribute(ctx context.Context, key string, value interface{})
+AddSpanEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)
+SetSpanError(ctx context.Context, err error)
+SetSpanStatus(ctx context.Context, code codes.Code, message string)
+LogWithContext(ctx context.Context, level string, message string, attrs ...attribute.KeyValue)
+WithTracer(ctx context.Context, operationName string, fn func(context.Context) error, opts ...oteltrace.SpanStartOption) error
+GetTraceID(ctx context.Context) string
+GetSpanID(ctx context.Context) string
+SetGlobalManager(manager *Manager)
+GetServiceName() string
+GetCollectorEndpoint() string
+Reset()
}
Utils : +InitWithConfig : 使用配置初始化OTel系统
Utils : +CreateSpan : 创建新的span
Utils : +AddSpanAttribute : 添加span属性
Utils : +SetSpanError : 设置span错误
Utils : +LogWithContext : 在上下文中记录日志
Utils : +WithTracer : 使用tracer执行函数
```
**Diagram sources**
- [utils.go](file://utility/otel/utils.go#L20-L30)
**Section sources**
- [utils.go](file://utility/otel/utils.go#L1-L231)
### 日志处理器分析
日志处理器负责将GoFrame框架的日志输出转换为OpenTelemetry格式并发送到收集器它实现了日志级别的映射调用者信息提取和上下文传递
```mermaid
sequenceDiagram
participant GF as GoFrame日志系统
participant Handler as LogHandler
participant Manager as OTel Manager
participant Logger as OTel Logger
participant Exporter as OTLP Exporter
GF->>Handler : 日志事件
Handler->>Handler : 检查监控是否启用
alt 监控已启用
Handler->>Manager : 获取配置
Handler->>Manager : 创建Logger
Handler->>Handler : 创建日志记录
Handler->>Handler : 添加基本属性
Handler->>Handler : 添加调用者信息
Handler->>Handler : 添加堆栈信息错误级别
Handler->>Handler : 添加上下文信息
Handler->>Logger : 发送日志记录
Logger->>Exporter : 导出日志
else 监控未启用
Handler->>GF : 继续处理
end
```
**Diagram sources**
- [handler.go](file://utility/otel/handler.go#L10-L165)
**Section sources**
- [handler.go](file://utility/otel/handler.go#L1-L165)
### 错误处理分析
错误处理组件定义了监控系统专用的错误类型提供了结构化的错误信息便于问题诊断和错误分类
```mermaid
classDiagram
class Error {
+string Code
+string Message
+error Cause
+Error() string
+Unwrap() error
}
class ErrInvalidConfig {
<<variable>>
}
class ErrInitFailed {
<<variable>>
}
class ErrShutdownFailed {
<<variable>>
}
class ErrExporterFailed {
<<variable>>
}
class ErrProviderNotInitialized {
<<variable>>
}
Error <|-- ErrInvalidConfig : "creates"
Error <|-- ErrInitFailed : "creates"
Error <|-- ErrShutdownFailed : "creates"
Error <|-- ErrExporterFailed : "creates"
Error <|-- ErrProviderNotInitialized : "creates"
Error : +Code : 错误代码,用于分类
Error : +Message : 错误消息
Error : +Cause : 根本原因
```
**Diagram sources**
- [errors.go](file://utility/otel/errors.go#L5-L60)
**Section sources**
- [errors.go](file://utility/otel/errors.go#L1-L61)
## 依赖分析
监控系统的组件之间存在明确的依赖关系形成了一个层次化的架构高层组件依赖于低层组件但低层组件不依赖于高层组件确保了系统的可维护性
```mermaid
graph TD
main[main.go] --> utils[utils.go]
main --> config[config.go]
utils --> manager[manager.go]
utils --> config
manager --> config
handler --> manager
handler --> utils
manager --> errors[errors.go]
utils --> errors
config --> errors
style main fill:#f96,stroke:#333,stroke-width:2px
style utils fill:#6f9,stroke:#333,stroke-width:2px
style manager fill:#69f,stroke:#333,stroke-width:2px
style config fill:#69f,stroke:#333,stroke-width:2px
style handler fill:#69f,stroke:#333,stroke-width:2px
style errors fill:#96f,stroke:#333,stroke-width:2px
```
**Diagram sources**
- [main.go](file://main.go#L1-L50)
- [utils.go](file://utility/otel/utils.go#L1-L231)
- [manager.go](file://utility/otel/manager.go#L1-L258)
- [config.go](file://utility/otel/config.go#L1-L68)
- [handler.go](file://utility/otel/handler.go#L1-L165)
- [errors.go](file://utility/otel/errors.go#L1-L61)
**Section sources**
- [main.go](file://main.go#L1-L50)
- [utils.go](file://utility/otel/utils.go#L1-L231)
- [manager.go](file://utility/otel/manager.go#L1-L258)
- [config.go](file://utility/otel/config.go#L1-L68)
- [handler.go](file://utility/otel/handler.go#L1-L165)
- [errors.go](file://utility/otel/errors.go#L1-L61)
## 性能考虑
监控系统的性能开销主要来自数据序列化网络传输和采样决策系统通过以下方式控制性能开销
1. **采样率控制**通过`SampleRate`配置项控制追踪数据的采样率减少数据量
2. **批量导出**使用批处理方式导出数据减少网络请求次数
3. **异步处理**日志和追踪数据的导出在后台线程中进行不影响主业务逻辑
4. **数据压缩**使用gzip等压缩算法减少网络传输数据量
5. **资源限制**设置合理的超时时间和资源限制防止监控系统影响主服务
**Section sources**
- [config.go](file://utility/otel/config.go#L1-L68)
- [manager.go](file://utility/otel/manager.go#L1-L258)
## 故障排除指南
### 数据丢失问题
当监控数据丢失时可能的原因和解决方案包括
1. **网络连接问题**检查收集器URL是否正确网络是否通畅
2. **认证失败**检查请求头中的认证信息是否正确
3. **采样率过低**检查`SampleRate`配置适当提高采样率
4. **导出器错误**查看应用日志中的`ErrExporterFailed`错误
### 延迟高问题
当监控数据延迟高时可能的原因和解决方案包括
1. **网络延迟**检查网络状况优化网络路径
2. **批量大小过大**调整批处理大小减少单次导出的数据量
3. **导出频率过低**增加导出频率减少数据积压
4. **资源不足**检查服务器CPU和内存使用情况适当增加资源
### 资源消耗过大问题
当监控系统消耗过多资源时可能的原因和解决方案包括
1. **采样率过高**降低`SampleRate`配置值
2. **日志级别过低**调整日志级别减少日志输出量
3. **追踪范围过大**限制追踪的代码范围只追踪关键路径
4. **压缩未启用**启用数据压缩减少网络和存储开销
**Section sources**
- [config.go](file://utility/otel/config.go#L1-L68)
- [manager.go](file://utility/otel/manager.go#L1-L258)
- [utils.go](file://utility/otel/utils.go#L1-L231)
- [errors.go](file://utility/otel/errors.go#L1-L61)
## 结论
kami_backend的监控系统集成通过OpenTelemetry实现了全面的可观测性系统设计简洁易于使用同时提供了足够的灵活性来满足不同的监控需求通过合理的配置和使用可以有效地监控系统性能快速定位和解决问题

View File

@@ -0,0 +1,492 @@
# 双因素认证
<cite>
**本文档引用的文件**
- [mfa.go](file://utility/mfa/mfa.go)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go)
- [sysUser_v1_totp_image_get.go](file://internal/controller/sysUser/sysUser_v1_totp_image_get.go)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [totp.go](file://internal/logic/sys_user/totp.go)
- [user_info.go](file://internal/logic/base_user_info/user_info.go)
- [sys_user.go](file://internal/service/sys_user.go)
</cite>
## 目录
1. [简介](#简介)
2. [MFA系统架构](#mfa系统架构)
3. [TOTP实现机制](#totp实现机制)
4. [MFA功能实现](#mfa功能实现)
5. [登录流程集成](#登录流程集成)
6. [关键操作二次验证](#关键操作二次验证)
7. [配置选项与安全策略](#配置选项与安全策略)
8. [开发者集成指南](#开发者集成指南)
9. [用户体验优化建议](#用户体验优化建议)
## 简介
本文档详细介绍了kami_backend系统的双因素认证MFA实现方案系统采用基于时间的一次性密码TOTP作为主要的双因素认证机制为用户提供额外的安全保护层文档全面解释了TOTP的实现机制包括密钥生成二维码展示和验证码验证流程描述了MFA的启用禁用和重置功能的实现细节并说明了MFA与用户登录流程的集成方式
**MFA系统的主要特点包括**
- 基于TOTP标准的双因素认证
- 与主流身份验证应用如Google Authenticator兼容
- 完整的MFA生命周期管理启用禁用重置
- 在关键操作中强制要求二次验证
- 灵活的配置选项和安全策略
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
## MFA系统架构
```mermaid
graph TD
subgraph "API接口层"
A[TotpStatusGet] --> B[TotpImageGet]
B --> C[TotpSet]
C --> D[TotpReset]
D --> E[UserLogin]
end
subgraph "业务逻辑层"
F[SysUser Service] --> G[Totp Logic]
H[BaseUserInfo Service] --> I[TotpValidate]
end
subgraph "工具层"
J[MFA Utility] --> K[GetOtp]
J --> L[ValidCode]
end
subgraph "数据层"
M[SysUser Database] --> N[OtpSecret存储]
M --> O[OtpKey存储]
end
A --> F
B --> F
C --> F
G --> J
D --> F
E --> F
F --> M
H --> J
J --> M
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
- [totp.go](file://internal/logic/sys_user/totp.go#L1-L50)
- [user_info.go](file://internal/logic/base_user_info/user_info.go#L1-L36)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
## TOTP实现机制
### 密钥生成与管理
系统使用`gotp`库实现TOTP标准密钥生成遵循RFC 6238规范当用户首次启用MFA时系统会生成一个16位的随机密钥作为TOTP的共享密钥
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
participant 数据库
用户->>前端 : 请求启用MFA
前端->>后端 : 调用TotpStatusGet接口
后端->>后端 : 检查用户MFA状态
alt 用户未启用MFA
后端->>后端 : 调用GetOtp生成密钥
后端->>后端 : 生成二维码数据
后端->>前端 : 返回二维码图像和临时密钥
前端->>用户 : 显示二维码供扫描
else 用户已启用MFA
后端->>前端 : 返回已启用状态
end
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
### 二维码生成与展示
系统通过`GetOtp`函数生成包含TOTP配置信息的二维码该二维码可被Google Authenticator等身份验证应用扫描二维码包含以下信息
- 用户ID
- 用户名
- 随机生成的密钥
- 服务名称卡销平台(供销端)
```mermaid
flowchart TD
Start([开始]) --> GenerateSecret["生成16位随机密钥"]
GenerateSecret --> CreateUri["创建TOTP配置URI"]
CreateUri --> EncodeUri["对URI进行URL解码"]
EncodeUri --> GenerateQr["生成二维码图像"]
GenerateQr --> ConvertBase64["转换为Base64编码"]
ConvertBase64 --> FormatData["格式化为data:image/png;base64格式"]
FormatData --> ReturnResult["返回包含二维码的响应"]
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
### 验证码验证流程
TOTP验证码验证遵循标准的时间窗口机制系统使用30秒作为时间步长允许前后各一个时间窗口的容差总共提供90秒的有效期
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
用户->>前端 : 输入TOTP验证码
前端->>后端 : 提交验证码和用户凭证
后端->>后端 : 获取用户存储的OtpSecret
后端->>后端 : 调用ValidCode进行验证
后端->>后端 : 计算当前时间窗口的TOTP值
后端->>后端 : 比较用户输入与计算值
alt 验证成功
后端->>前端 : 返回验证成功
else 验证失败
后端->>前端 : 返回验证失败错误
end
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
## MFA功能实现
### MFA启用流程
用户启用MFA需要经过以下步骤
1. 用户请求获取MFA配置信息
2. 系统生成新的密钥对并返回二维码
3. 用户使用身份验证应用扫描二维码
4. 用户输入当前生成的TOTP验证码进行验证
5. 系统验证成功后保存MFA配置
```mermaid
flowchart TD
A[用户请求启用MFA] --> B{检查当前MFA状态}
B --> |未启用| C[生成新密钥和二维码]
C --> D[前端显示二维码]
D --> E[用户扫描二维码]
E --> F[用户输入TOTP验证码]
F --> G[系统验证验证码]
G --> |验证成功| H[保存OtpSecret和OtpKey]
G --> |验证失败| I[返回错误信息]
H --> J[MFA启用成功]
I --> K[提示用户重新尝试]
```
**Diagram sources**
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
- [totp.go](file://internal/logic/sys_user/totp.go#L1-L50)
### MFA禁用与重置
系统提供了MFA的禁用和重置功能允许用户在需要时管理自己的双因素认证设置
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
participant 数据库
用户->>前端 : 请求重置MFA
前端->>后端 : 调用TotpReset接口
后端->>后端 : 验证用户身份
后端->>后端 : 验证提供的TOTP验证码
alt 验证成功
后端->>数据库 : 清除OtpSecret和OtpKey
数据库-->>后端 : 返回更新结果
后端-->>前端 : 返回重置成功
else 验证失败
后端-->>前端 : 返回验证失败错误
end
```
**Diagram sources**
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go#L1-L28)
- [totp.go](file://internal/logic/sys_user/totp.go#L1-L50)
**Section sources**
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go#L1-L28)
- [totp.go](file://internal/logic/sys_user/totp.go#L1-L50)
## 登录流程集成
### 登录时的MFA验证
MFA与用户登录流程深度集成当用户账户启用了MFA时系统会在登录过程中强制要求提供TOTP验证码
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
participant 数据库
用户->>前端 : 输入用户名、密码和验证码
前端->>后端 : 提交登录请求
后端->>后端 : 验证图形验证码
alt 验证失败
后端-->>前端 : 返回验证码错误
else 验证成功
后端->>数据库 : 查询用户凭据
数据库-->>后端 : 返回用户信息
alt 用户凭据错误
后端-->>前端 : 返回用户名或密码错误
else 用户凭据正确
alt 用户启用了MFA
后端->>后端 : 验证TOTP验证码
alt TOTP验证失败
后端-->>前端 : 返回二步验证错误
else TOTP验证成功
后端->>后端 : 生成用户Token
后端-->>前端 : 返回Token和登录成功
end
else 用户未启用MFA
后端->>后端 : 生成用户Token
后端-->>前端 : 返回Token和登录成功
end
end
end
```
**Diagram sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
### MFA状态检查
系统在登录前会检查用户的MFA状态以确定是否需要进行二次验证
```mermaid
flowchart TD
A[接收登录请求] --> B[验证图形验证码]
B --> C{用户凭据验证}
C --> |失败| D[返回凭据错误]
C --> |成功| E{检查OtpSecret字段}
E --> |为空| F[跳过MFA验证]
E --> |不为空| G[要求TOTP验证码]
G --> H[验证TOTP验证码]
H --> |失败| I[返回MFA验证错误]
H --> |成功| J[完成登录流程]
```
**Section sources**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
## 关键操作二次验证
### 敏感操作保护
系统在执行关键操作时会强制要求二次验证确保操作的安全性
```mermaid
sequenceDiagram
participant 用户
participant 前端
participant 后端
用户->>前端 : 请求修改密码
前端->>后端 : 调用UserChangePwd接口
后端->>后端 : 验证用户身份
后端->>后端 : 验证原密码
alt 用户启用了MFA
后端->>后端 : 验证TOTP验证码
alt 验证成功
后端->>后端 : 更新密码
后端-->>前端 : 返回修改成功
else 验证失败
后端-->>前端 : 返回MFA验证错误
end
else 用户未启用MFA
后端->>后端 : 更新密码
后端-->>前端 : 返回修改成功
end
```
**Section sources**
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
## 配置选项与安全策略
### 时间窗口配置
系统采用标准的TOTP时间窗口配置确保与主流身份验证应用的兼容性
```mermaid
erDiagram
USER ||--o{ MFA_CONFIG : has
USER {
string id PK
string username
string user_password
string user_salt
uint user_status
}
MFA_CONFIG {
string user_id FK
string otp_secret
string otp_key
datetime created_at
datetime updated_at
}
USER ||--o{ LOGIN_LOG : has
LOGIN_LOG {
uuid id PK
string user_id FK
string ip_address
datetime login_time
bool success
string failure_reason
}
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
### 尝试次数限制
系统实现了MFA验证的尝试次数限制防止暴力破解攻击
```mermaid
flowchart TD
A[开始MFA验证] --> B[记录尝试次数]
B --> C{尝试次数 < 最大限制}
C --> |是| D[执行验证逻辑]
D --> E{验证成功}
E --> |是| F[重置尝试计数器]
E --> |否| G[增加尝试计数]
G --> H{达到最大尝试次数}
H --> |是| I[锁定账户一段时间]
H --> |否| J[返回验证失败]
C --> |否| I
F --> K[验证成功]
I --> L[返回锁定错误]
```
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
## 开发者集成指南
### API接口说明
系统提供了完整的MFA管理API接口方便开发者集成和使用
```mermaid
classDiagram
class TotpStatusGetReq {
+string Code
}
class TotpStatusGetRes {
+bool Status
+string Image
+string OtpSecret
+string OtpKey
}
class TotpSetReq {
+string Password
+string Code
+string OtpSecret
}
class TotpSetRes {
}
class TotpResetReq {
+string Code
}
class TotpResetRes {
}
class UserLoginReq {
+string Username
+string Password
+string VerifyKey
+string VerifyCode
+string TotpCode
}
class UserLoginRes {
+string Token
}
TotpStatusGetReq <|-- ControllerV1
TotpStatusGetRes <|-- ControllerV1
TotpSetReq <|-- ControllerV1
TotpSetRes <|-- ControllerV1
TotpResetReq <|-- ControllerV1
TotpResetRes <|-- ControllerV1
UserLoginReq <|-- ControllerV1
UserLoginRes <|-- ControllerV1
```
**Diagram sources**
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go#L1-L28)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go#L1-L52)
### 服务层接口
MFA功能通过服务层接口提供给其他模块使用
```mermaid
classDiagram
class ISysUser {
+SetTotp(ctx, data, key, secret)
+ResetTotp(ctx, data)
}
class IBaseUserInfo {
+TotpValidate(ctx, totpCode)
}
class MfaUtility {
+GetOtp(userId, username, key, secret)
+ValidCode(code, secret)
}
ISysUser <|-- SysUserServiceImpl
IBaseUserInfo <|-- BaseUserInfoServiceImpl
MfaUtility <|-- MfaUtilityImpl
SysUserServiceImpl ..> MfaUtility : uses
BaseUserInfoServiceImpl ..> MfaUtility : uses
```
**Diagram sources**
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
- [user_info.go](file://internal/logic/base_user_info/user_info.go#L1-L36)
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
**Section sources**
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
- [user_info.go](file://internal/logic/base_user_info/user_info.go#L1-L36)
## 用户体验优化建议
### 渐进式安全增强
建议采用渐进式的方式引导用户启用MFA提高用户接受度
```mermaid
flowchart TD
A[新用户注册] --> B[基础密码保护]
B --> C{用户活跃度达到阈值}
C --> |是| D[提示启用MFA]
D --> E{用户选择启用}
E --> |是| F[引导完成MFA设置]
E --> |否| G[定期提醒]
F --> H[增强账户安全性]
G --> C
```
### 恢复机制设计
系统应提供安全的MFA恢复机制防止用户因丢失验证设备而无法访问账户
```mermaid
flowchart TD
A[用户丢失验证设备] --> B[使用恢复码登录]
B --> C{验证成功}
C --> |是| D[重置MFA设置]
D --> E[重新配置新设备]
E --> F[MFA恢复完成]
C --> |否| G[联系管理员协助]
G --> H[管理员验证身份]
H --> I[重置用户MFA]
```
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_reset.go](file://internal/controller/sysUser/sysUser_v1_totp_reset.go#L1-L28)

View File

@@ -0,0 +1,384 @@
# 安全考虑
<cite>
**本文档中引用的文件**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [mfa.go](file://utility/mfa/mfa.go)
- [auth.go](file://internal/middleware/auth.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [sys_user.go](file://internal/service/sys_user.go)
- [sys_auth.go](file://internal/service/sys_auth.go)
- [sys_casbin.go](file://internal/service/sys_casbin.go)
- [v_1_sys_user.go](file://internal/dao/v_1_sys_user.go)
- [v_1_sys_casbin_rule.go](file://internal/dao/v_1_sys_casbin_rule.go)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
</cite>
## 目录
1. [引言](#引言)
2. [系统安全架构概述](#系统安全架构概述)
3. [身份验证机制](#身份验证机制)
4. [基于JWT的认证系统](#基于jwt的认证系统)
5. [基于Casbin的RBAC授权](#基于casbin的rbac授权)
6. [TOTP双因素认证(MFA)](#totp双因素认证mfa)
7. [数据加密机制](#数据加密机制)
8. [会话管理与令牌续签](#会话管理与令牌续签)
9. [安全最佳实践](#安全最佳实践)
10. [常见安全威胁与缓解措施](#常见安全威胁与缓解措施)
11. [开发者安全编码指南](#开发者安全编码指南)
12. [结论](#结论)
## 引言
本文档全面阐述了kami_backend系统的安全架构设计涵盖多层安全机制包括基于JWT的身份认证基于Casbin的RBAC权限控制TOTP双因素认证以及数据加密技术文档详细说明了各安全组件的实现原理配置方式和使用模式并提供安全最佳实践和漏洞防范指南
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [sys_user.go](file://internal/model/sys_user.go#L1-L92)
## 系统安全架构概述
kami_backend系统采用分层安全架构包含身份验证授权会话管理和数据保护等多个安全层面系统通过JWT实现无状态认证利用Casbin框架实现灵活的基于角色的访问控制(RBAC)并集成TOTP双因素认证增强账户安全性同时系统使用AES和MD5算法对敏感数据进行加密保护
```mermaid
graph TB
subgraph "安全架构"
Auth[身份验证]
Authorization[授权]
Session[会话管理]
Encryption[数据加密]
end
Auth --> |JWT| Authorization
Authorization --> |Casbin| Session
Session --> |Token| Encryption
Encryption --> |AES/MD5| Auth
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L1-L50)
## 身份验证机制
系统实现了多模式身份验证机制支持标准登录认证和iframe嵌入式认证两种模式通过中间件统一处理身份验证逻辑确保所有受保护的API端点都经过严格的身份验证
### 认证流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Middleware as "认证中间件"
participant Token as "令牌服务"
participant Redis as "Redis缓存"
Client->>Middleware : 发送请求(含Token)
Middleware->>Token : 提取请求Token
alt Token不存在
Middleware-->>Client : 返回未授权错误
else Token存在
Middleware->>Token : 解析用户Token
Token->>Redis : 验证Token有效性
Redis-->>Token : 返回验证结果
alt Token有效
Token->>Middleware : 返回用户信息
Middleware->>Token : 续签Token
Token-->>Middleware : 返回新Token
Middleware->>Client : 设置refresh-token头
Middleware->>Client : 允许请求继续
else Token无效
Middleware-->>Client : 返回Token失效错误
end
end
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L50-L100)
- [token.go](file://utility/token/user_token.go#L1-L50)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
## 基于JWT的认证系统
系统采用JWT(JSON Web Token)实现无状态认证机制用户登录成功后服务器生成包含用户信息的JWT令牌客户端在后续请求中携带该令牌进行身份验证
### JWT实现细节
```mermaid
flowchart TD
Start([用户登录]) --> ValidateCredentials["验证凭据"]
ValidateCredentials --> CredentialsValid{"凭据有效?"}
CredentialsValid --> |否| ReturnError["返回认证失败"]
CredentialsValid --> |是| GenerateToken["生成JWT令牌"]
GenerateToken --> StoreInRedis["将Token存储到Redis"]
StoreInRedis --> ReturnToken["返回Token给客户端"]
ReturnToken --> ClientRequest["客户端后续请求"]
ClientRequest --> ExtractToken["提取请求中的Token"]
ExtractToken --> VerifyToken["验证Token有效性"]
VerifyToken --> TokenValid{"Token有效?"}
TokenValid --> |否| ReturnUnauthorized["返回未授权"]
TokenValid --> |是| RefreshToken["续签Token"]
RefreshToken --> ContinueRequest["继续处理请求"]
ReturnError --> End([结束])
ReturnUnauthorized --> End
ContinueRequest --> End
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L50-L100)
- [user_token.go](file://utility/token/user_token.go#L1-L50)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [user_token.go](file://utility/token/user_token.go#L1-L50)
## 基于Casbin的RBAC授权
系统采用Casbin框架实现基于角色的访问控制(RBAC)通过定义角色权限和资源之间的关系实现细粒度的权限控制
### RBAC模型配置
```conf
# rbac_model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
```
### 权限检查流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Middleware as "中间件"
participant Casbin as "Casbin引擎"
participant Policy as "策略存储"
Client->>Middleware : 发送受保护的请求
Middleware->>Casbin : 获取用户角色
Casbin->>Policy : 加载用户权限策略
Policy-->>Casbin : 返回策略规则
Casbin->>Casbin : 构建权限检查请求
Casbin->>Casbin : 执行权限匹配
alt 有权限
Casbin-->>Middleware : 返回允许访问
Middleware->>Client : 继续处理请求
else 无权限
Casbin-->>Middleware : 返回拒绝访问
Middleware->>Client : 返回403错误
end
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L15)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L1-L50)
- [v_1_sys_casbin_rule.go](file://internal/dao/v_1_sys_casbin_rule.go#L1-L28)
**Section sources**
- [sys_casbin.go](file://internal/service/sys_casbin.go#L1-L50)
- [v_1_sys_casbin_rule.go](file://internal/dao/v_1_sys_casbin_rule.go#L1-L28)
## TOTP双因素认证(MFA)
系统集成了TOTP(Time-based One-Time Password)双因素认证机制通过Google Authenticator等认证应用生成动态验证码增强账户安全性
### MFA实现流程
```mermaid
sequenceDiagram
participant User as "用户"
participant Server as "服务器"
participant Authenticator as "认证应用"
User->>Server : 请求启用MFA
Server->>Server : 生成密钥和二维码
Server-->>User : 返回二维码和密钥
User->>Authenticator : 扫描二维码
Authenticator->>Authenticator : 生成动态验证码
User->>Server : 提交验证码和密码
Server->>Server : 验证TOTP码
alt 验证成功
Server->>Server : 保存MFA设置
Server-->>User : MFA启用成功
else 验证失败
Server-->>User : 返回验证失败
end
```
### MFA状态检查
```mermaid
flowchart TD
Start([获取MFA状态]) --> GetUser["获取当前用户信息"]
GetUser --> HasSecret{"已设置密钥?"}
HasSecret --> |是| SetStatus["状态: 已启用"]
HasSecret --> |否| GenerateQR["生成二维码"]
GenerateQR --> GetOtp["调用GetOtp生成密钥"]
GetOtp --> StoreQR["存储二维码信息"]
StoreQR --> SetStatus["状态: 未启用"]
SetStatus --> ReturnResult["返回状态和二维码"]
ReturnResult --> End([结束])
```
**Diagram sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
**Section sources**
- [mfa.go](file://utility/mfa/mfa.go#L1-L53)
- [sysUser_v1_totp_status_get.go](file://internal/controller/sysUser/sysUser_v1_totp_status_get.go#L1-L37)
- [sysUser_v1_totp_set.go](file://internal/controller/sysUser/sysUser_v1_totp_set.go#L1-L34)
## 数据加密机制
系统采用AES ECB模式和MD5哈希算法对敏感数据进行加密保护确保数据在传输和存储过程中的安全性
### AES ECB加密实现
```mermaid
flowchart TD
Start([明文数据]) --> Padding["PKCS7填充"]
Padding --> CreateCipher["创建AES密码器"]
CreateCipher --> Encrypt["CBC模式加密"]
Encrypt --> EncodeBase64["Base64编码"]
EncodeBase64 --> Ciphertext["密文输出"]
Ciphertext --> End([完成])
subgraph "解密流程"
Ciphertext2["密文输入"] --> DecodeBase64["Base64解码"]
DecodeBase64 --> CreateCipher2["创建AES密码器"]
CreateCipher2 --> Decrypt["CBC模式解密"]
Decrypt --> Unpadding["PKCS7反填充"]
Unpadding --> Plaintext["明文输出"]
end
```
### MD5哈希实现
```mermaid
flowchart TD
Start([输入字符串]) --> CreateHash["创建MD5哈希器"]
CreateHash --> WriteData["写入数据"]
WriteData --> ComputeHash["计算哈希值"]
ComputeHash --> EncodeHex["十六进制编码"]
EncodeHex --> Result["返回MD5值"]
Result --> End([完成])
subgraph "大小写转换"
Result --> ToLower["转换为小写"]
Result --> ToUpper["转换为大写"]
end
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L1-L91)
- [md5.go](file://utility/verify/md5.go#L1-L32)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L1-L91)
- [md5.go](file://utility/verify/md5.go#L1-L32)
## 会话管理与令牌续签
系统实现了安全的会话管理机制通过Redis存储会话信息并支持令牌自动续签功能平衡安全性和用户体验
### 会话管理流程
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Server as "服务器"
participant Redis as "Redis"
Client->>Server : 登录请求
Server->>Server : 验证凭据
alt 验证成功
Server->>Server : 生成JWT令牌
Server->>Redis : 存储会话信息
Redis-->>Server : 存储成功
Server-->>Client : 返回令牌
else 验证失败
Server-->>Client : 返回错误
end
Client->>Server : 后续请求(含令牌)
Server->>Redis : 验证令牌有效性
alt 令牌有效
Server->>Server : 续签令牌(如需要)
Server->>Redis : 更新会话
Server-->>Client : 处理请求
else 令牌无效
Server-->>Client : 返回401错误
end
```
**Diagram sources**
- [auth.go](file://internal/middleware/auth.go#L50-L100)
- [user_token.go](file://utility/token/user_token.go#L1-L50)
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [user_token.go](file://utility/token/user_token.go#L1-L50)
## 安全最佳实践
### 密码策略
- 密码长度至少8位
- 必须包含大小写字母数字和特殊字符
- 定期强制更换密码
- 禁止使用常见弱密码
### 令牌管理
- JWT令牌设置合理的过期时间
- 实现令牌黑名单机制
- 支持令牌续签功能
- 敏感操作要求重新认证
### 安全头配置
- 启用HTTPS强制加密
- 配置CSP(Content Security Policy)
- 设置X-Content-Type-Options头
- 启用X-Frame-Options防止点击劫持
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [user_token.go](file://utility/token/user_token.go#L1-L50)
## 常见安全威胁与缓解措施
### 威胁类型与应对
| 威胁类型 | 风险描述 | 缓解措施 |
|---------|--------|---------|
| 暴力破解 | 攻击者尝试大量密码组合 | 账号锁定机制验证码登录失败限制 |
| 会话劫持 | 攻击者窃取用户会话令牌 | HTTPS传输HttpOnly Cookie令牌续签 |
| XSS攻击 | 跨站脚本注入 | 输入验证输出编码CSP策略 |
| CSRF攻击 | 跨站请求伪造 | CSRF令牌SameSite Cookie |
| SQL注入 | 恶意SQL语句执行 | 参数化查询输入验证 |
| 权限提升 | 用户获取未授权权限 | RBAC严格控制最小权限原则 |
### 安全监控
- 记录所有登录尝试
- 监控异常登录行为
- 定期安全审计
- 实时告警机制
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [errHandler.go](file://internal/errHandler/handler.go#L1-L50)
## 开发者安全编码指南
### 输入验证
- 对所有用户输入进行严格验证
- 使用白名单验证机制
- 防止SQL注入和XSS攻击
### 错误处理
- 不泄露敏感信息到错误消息
- 统一错误处理机制
- 详细日志记录但不暴露给用户
### 权限检查
- 所有API端点都应进行权限验证
- 实现最小权限原则
- 敏感操作需要二次确认
### 数据保护
- 敏感数据加密存储
- 避免在日志中记录敏感信息
- 定期轮换加密密钥
**Section sources**
- [auth.go](file://internal/middleware/auth.go#L1-L154)
- [sys_user.go](file://internal/service/sys_user.go#L1-L102)
- [verify.go](file://utility/verify/aes_ecb.go#L1-L91)
## 结论
kami_backend系统通过多层次的安全机制构建了完整的安全防护体系基于JWT的认证Casbin的RBAC授权TOTP双因素认证和数据加密技术共同保障了系统的安全性建议持续关注安全威胁变化定期进行安全审计不断优化安全策略确保系统长期安全稳定运行

View File

@@ -0,0 +1,209 @@
# 授权机制
<cite>
**本文档引用文件**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go)
- [sys_casbin.go](file://internal/service/sys_casbin.go)
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go)
- [sys_auth_rule_v1_rule_search.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_search.go)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go)
</cite>
## 目录
1. [简介](#简介)
2. [RBAC模型配置](#rbac模型配置)
3. [权限检查实现机制](#权限检查实现机制)
4. [角色与权限管理接口](#角色与权限管理接口)
5. [权限策略配置示例与最佳实践](#权限策略配置示例与最佳实践)
6. [权限缓存与性能优化](#权限缓存与性能优化)
7. [自定义权限策略指导](#自定义权限策略指导)
8. [调试技巧](#调试技巧)
## 简介
kami_backend系统采用基于Casbin的RBAC基于角色的访问控制授权机制实现了灵活且可扩展的权限管理系统该系统通过定义角色权限和资源之间的关系控制用户对系统功能的访问核心组件包括权限模型定义策略存储权限验证中间件以及管理接口
**Section sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L1-L50)
## RBAC模型配置
系统权限模型定义位于`resource/casbin/rbac_model.conf`文件中采用标准的Casbin配置格式模型包含请求定义策略定义角色定义策略效果和匹配器五个部分
```mermaid
erDiagram
USER {
string username PK
}
ROLE {
string role_name PK
}
PERMISSION {
string obj
string act
}
USER ||--o{ ROLE : "has"
ROLE ||--o{ PERMISSION : "grants"
```
**Diagram sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 权限检查实现机制
权限检查机制通过Casbin的SyncedEnforcer实现集成在系统服务层当用户发起请求时系统会提取用户身份sub请求资源obj和操作类型act然后通过匹配器规则进行权限验证
权限验证流程如下
1. 从上下文中获取用户信息
2. 构造Casbin请求参数sub, obj, act
3. 调用Enforcer的Enforce方法进行权限检查
4. 根据返回结果决定是否允许访问
```mermaid
flowchart TD
A[用户请求] --> B{提取用户身份}
B --> C[构造权限检查参数]
C --> D[调用Casbin Enforcer]
D --> E{权限是否允许?}
E --> |是| F[执行业务逻辑]
E --> |否| G[返回权限拒绝]
```
**Diagram sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L35-L45)
**Section sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L35-L100)
## 角色与权限管理接口
系统提供了完整的角色和权限管理接口支持权限规则的创建更新删除和查询操作这些接口位于`internal/controller/sys_auth_rule/`目录下通过RESTful API提供服务
### 权限管理接口
- **创建权限规则**: `RuleAdd` 方法用于添加新的权限策略
- **更新权限规则**: `RuleUpdate` 方法用于修改现有权限策略
- **删除权限规则**: `RuleDelete` 方法用于移除权限策略
- **查询权限规则**: `RuleSearch` 方法用于检索权限策略
### 角色管理接口
- **创建角色**: `RoleAdd` 方法用于创建新角色
- **编辑角色**: `RoleEdit` 方法用于修改角色信息
```mermaid
sequenceDiagram
participant Client as 客户端
participant Controller as 控制器
participant Service as 服务层
participant Casbin as Casbin Enforcer
Client->>Controller : 发送权限管理请求
Controller->>Service : 调用服务方法
Service->>Casbin : 执行策略操作
Casbin-->>Service : 返回操作结果
Service-->>Controller : 返回处理结果
Controller-->>Client : 返回响应
```
**Diagram sources**
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L15)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L15)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L15)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go#L1-L15)
**Section sources**
- [sys_auth_rule_v1_rule_add.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_add.go#L1-L15)
- [sys_auth_rule_v1_rule_update.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_update.go#L1-L15)
- [sys_auth_rule_v1_rule_delete.go](file://internal/controller/sys_auth_rule/sys_auth_rule_v1_rule_delete.go#L1-L15)
- [sys_role_v1_role_add.go](file://internal/controller/sys_role/sys_role_v1_role_add.go#L1-L15)
- [sys_role_v1_role_edit.go](file://internal/controller/sys_role/sys_role_v1_role_edit.go#L1-L15)
## 权限策略配置示例与最佳实践
### 配置示例
```conf
# 角色继承示例
g = admin, super_user
g = editor, user
# 权限分配示例
p = admin, /api/users, GET
p = admin, /api/users, POST
p = editor, /api/articles, POST
p = user, /api/profile, GET
```
### 最佳实践
1. **最小权限原则**: 只授予用户完成工作所需的最小权限
2. **角色分层设计**: 建立角色继承关系避免权限重复配置
3. **资源命名规范**: 使用一致的资源命名约定便于权限管理
4. **定期审计**: 定期审查权限分配确保权限配置的合理性
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
## 权限缓存与性能优化
系统通过SyncedEnforcer实现权限缓存机制提高权限检查性能所有权限策略存储在数据库中通过V1SysCasbinRule表进行持久化管理
### 性能优化策略
1. **同步执行器**: 使用SyncedEnforcer确保多实例环境下的策略一致性
2. **数据库持久化**: 将策略规则存储在数据库中支持动态更新
3. **批量操作**: 提供AddPolicies和RemovePolicies方法支持批量策略操作
4. **过滤删除**: 支持按条件过滤删除策略规则
```mermaid
classDiagram
class sCasbin {
+Enforcer *casbin.SyncedEnforcer
+EnforcerErr error
+Ctx context.Context
+CasbinEnforcer(ctx) (*casbin.SyncedEnforcer, error)
+SavePolicy(model) error
+LoadPolicy(model) error
+AddPolicy(sec, pType, rule) error
+RemovePolicy(sec, pType, rule) error
}
class ICasbin {
+CasbinEnforcer(ctx) (*casbin.SyncedEnforcer, error)
+SavePolicy(model) error
+LoadPolicy(model) error
+AddPolicy(sec, pType, rule) error
+RemovePolicy(sec, pType, rule) error
}
sCasbin --> ICasbin : 实现
```
**Diagram sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L35-L45)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L1-L50)
**Section sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L50-L245)
- [sys_casbin.go](file://internal/service/sys_casbin.go#L1-L50)
## 自定义权限策略指导
开发者可以基于现有RBAC模型进行扩展实现更复杂的访问控制需求自定义策略的步骤如下
1. **修改模型配置**: 根据需求调整rbac_model.conf文件
2. **扩展匹配器**: [matchers]部分添加自定义匹配逻辑
3. **实现数据适配器**: 确保策略数据能够正确存储和读取
4. **测试验证**: 通过单元测试验证自定义策略的正确性
**Section sources**
- [rbac_model.conf](file://resource/casbin/rbac_model.conf#L1-L14)
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L1-L245)
## 调试技巧
### 常见问题排查
1. **权限检查失败**: 检查用户角色分配和策略规则是否正确
2. **策略未生效**: 确认Enforcer已正确加载最新策略
3. **性能问题**: 检查数据库查询性能和缓存机制
### 调试方法
1. **日志跟踪**: 启用Casbin详细日志查看权限检查过程
2. **策略导出**: 使用LoadPolicy方法导出现有策略进行分析
3. **单元测试**: 编写测试用例验证权限逻辑的正确性
**Section sources**
- [sysCasbin.go](file://internal/logic/sys_casbin/sysCasbin.go#L1-L245)

View File

@@ -0,0 +1,296 @@
# 数据安全
<cite>
**Referenced Files in This Document**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [config.go](file://utility/config/config.go)
- [tools.go](file://utility/utils/tools.go)
- [sys_user.go](file://internal/model/sys_user.go)
- [user_center.go](file://internal/systemV2/logic/user_center/user_center.go)
- [v_1_sys_user.go](file://internal/dao/internal/v_1_sys_user.go)
</cite>
## 目录
1. [引言](#引言)
2. [加密模块架构](#加密模块架构)
3. [AES加密机制](#aes加密机制)
4. [MD5哈希算法](#md5哈希算法)
5. [敏感数据存储策略](#敏感数据存储策略)
6. [数据完整性验证](#数据完整性验证)
7. [加密配置与密钥管理](#加密配置与密钥管理)
8. [开发者安全编码指南](#开发者安全编码指南)
9. [结论](#结论)
## 引言
kami_backend系统的数据安全机制采用多层次的安全策略确保敏感数据在传输和存储过程中的安全性系统主要采用AES加密算法对敏感数据进行保护同时使用MD5哈希算法处理密码等认证信息本文档详细阐述了系统的数据安全架构加密算法实现密钥管理策略以及开发者在使用这些安全机制时的最佳实践
系统通过AES-CBC模式加密确保数据的机密性通过MD5哈希加盐处理确保密码的安全存储同时系统实现了完整的密钥管理机制将加密密钥与初始化向量(IV)分离存储提高了系统的整体安全性
## 加密模块架构
kami_backend系统的数据安全功能主要分布在`utility/verify``utility/utils`两个包中形成了清晰的分层架构`utility/verify`包提供了底层的加密和哈希算法实现`utility/utils`包则提供了更高层次的安全工具函数便于业务逻辑调用
```mermaid
graph TD
A[业务逻辑层] --> B[安全工具层]
B --> C[AES加密模块]
B --> D[MD5哈希模块]
C --> E[CBC模式加密]
C --> F[Base64编码]
D --> G[密码哈希]
D --> H[盐值处理]
E --> I[密钥管理]
F --> J[数据编码]
G --> K[双重MD5]
H --> L[随机盐值]
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go)
- [md5.go](file://utility/verify/md5.go)
- [tools.go](file://utility/utils/tools.go)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L1-L90)
- [md5.go](file://utility/verify/md5.go#L1-L31)
- [tools.go](file://utility/utils/tools.go#L1-L25)
## AES加密机制
### AES-CBC模式实现
kami_backend系统采用AES-CBCCipher Block Chaining模式进行数据加密而非文档中提到的ECB模式CBC模式通过将前一个密文块与当前明文块进行异或操作有效解决了ECB模式中相同明文产生相同密文的安全问题
系统在`utility/verify/aes_ecb.go`文件中实现了完整的AES-CBC加密解密功能包括
- `aesCBCEncrypt`: AES-CBC模式加密函数使用PKCS7填充标准
- `aesCBCDecrypt`: AES-CBC模式解密函数支持PKCS7反填充
- `AesCBCEncryptWithBase64`: 带Base64编码的加密函数便于网络传输
- `AesCBCStdDecryptWithBase64`: 带Base64解码的标准解密函数
```mermaid
sequenceDiagram
participant 应用层 as 应用层
participant 加密工具 as 加密工具
participant AES模块 as AES模块
应用层->>加密工具 : 调用AesCBCEncryptWithBase64
加密工具->>AES模块 : aesCBCEncrypt(明文, 密钥, IV)
AES模块->>AES模块 : PKCS7填充明文
AES模块->>AES模块 : 创建AES密码块
AES模块->>AES模块 : 初始化CBC加密器
AES模块->>AES模块 : 执行加密操作
AES模块-->>加密工具 : 返回密文
加密工具->>加密工具 : Base64编码
加密工具-->>应用层 : 返回Base64编码的密文
应用层->>加密工具 : 调用AesCBCStdDecryptWithBase64
加密工具->>加密工具 : Base64解码
加密工具->>AES模块 : aesCBCDecrypt(密文, 密钥, IV)
AES模块->>AES模块 : 创建AES密码块
AES模块->>AES模块 : 初始化CBC解密器
AES模块->>AES模块 : 执行解密操作
AES模块->>AES模块 : PKCS7反填充
AES模块-->>加密工具 : 返回明文
加密工具-->>应用层 : 返回解密后的明文
```
**Diagram sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L15-L85)
**Section sources**
- [aes_ecb.go](file://utility/verify/aes_ecb.go#L15-L85)
### PKCS7填充机制
系统实现了标准的PKCS7填充机制确保明文长度符合AES块大小的要求填充规则如下
- 如果明文长度正好是块大小的整数倍则添加一个完整的填充块
- 填充字节的值等于填充的字节数
- 解密时根据最后一个字节的值确定需要移除的填充字节数
这种填充方式确保了加密数据的完整性同时避免了因填充不当导致的解密失败
## MD5哈希算法
### 密码哈希处理
kami_backend系统使用MD5哈希算法处理用户密码但采用了增强的安全措施避免了直接使用MD5带来的安全风险系统在`utility/utils/tools.go`文件中实现了`EncryptPassword`函数该函数采用双重MD5哈希加盐的处理方式
```mermaid
flowchart TD
Start([开始]) --> Hash1["MD5(原始密码)"]
Hash1 --> Concat["MD5(原始密码)+MD5(盐值)"]
Concat --> Hash2["MD5(MD5(原始密码)+MD5(盐值))"]
Hash2 --> End([存储哈希值])
Salt[生成随机盐值] --> Concat
```
**Diagram sources**
- [tools.go](file://utility/utils/tools.go#L22-L24)
**Section sources**
- [tools.go](file://utility/utils/tools.go#L22-L24)
### 哈希函数实现
系统提供了两个MD5哈希函数
- `GetMD5LOWER`: 返回小写格式的MD5哈希值
- `GetMD5Upper`: 返回大写格式的MD5哈希值
这些函数封装了标准的MD5算法提供了便捷的接口供系统其他部分调用同时系统还提供了`MapToString`辅助函数用于将map数据转换为key=value形式的字符串便于生成签名或进行数据校验
## 敏感数据存储策略
### 用户密码存储
系统对用户密码采用了严格的安全存储策略确保即使数据库被泄露攻击者也无法轻易获取用户的原始密码具体实现如下
1. **盐值生成**: 每次用户注册或修改密码时系统生成一个10位的随机盐值
2. **双重哈希**: 使用`EncryptPassword`函数对密码进行双重MD5哈希处理
3. **分离存储**: 将哈希后的密码和盐值分别存储在不同的数据库字段中
```mermaid
classDiagram
class SysUser {
+string id
+string username
+string user_password
+string user_salt
+int is_admin
+int user_status
+string otp_key
+string otp_secret
+datetime created_at
+datetime updated_at
+datetime deleted_at
}
class UserInfo {
+string id
+string user_id
+string passwd
+string nick
+string remark
+string ip
+int status
+int role
+string role_name
+string otp_secret
+string otp_key
+datetime create_time
+datetime update_time
}
SysUser --> UserInfo : "1对1关联"
```
**Diagram sources**
- [v_1_sys_user.go](file://internal/dao/internal/v_1_sys_user.go#L37-L81)
- [sys_user.go](file://internal/model/sys_user.go#L0-L91)
**Section sources**
- [v_1_sys_user.go](file://internal/dao/internal/v_1_sys_user.go#L37-L81)
- [sys_user.go](file://internal/model/sys_user.go#L0-L91)
### 密码验证流程
当用户登录时系统执行以下验证流程
1. 根据用户名查询用户信息获取存储的盐值和哈希密码
2. 使用相同的盐值对用户输入的密码进行哈希处理
3. 比较生成的哈希值与存储的哈希值是否匹配
这种机制确保了系统永远不会存储或处理用户的原始密码提高了整体安全性
## 数据完整性验证
### 密钥配置管理
系统通过配置文件管理加密密钥和初始化向量确保密钥的安全性和可维护性`utility/config/config.go`文件中系统提供了`GetFrontendSecret``GetBackendSecret`函数用于获取前端和后端的加密密钥配置
```mermaid
flowchart TD
A[配置文件] --> B[secret.frontend.key]
A --> C[secret.frontend.iv]
B --> D[前端密钥]
C --> E[前端IV]
D --> F[加密/解密]
E --> F[加密/解密]
G[业务逻辑] --> H[调用GetFrontendSecret]
H --> I[返回密钥和IV]
I --> J[执行加密操作]
```
**Diagram sources**
- [config.go](file://utility/config/config.go#L15-L35)
**Section sources**
- [config.go](file://utility/config/config.go#L15-L35)
### 跨系统密码验证
系统实现了跨系统的密码验证机制确保在不同加密配置下的密码一致性验证`internal/systemV2/logic/user_center/user_center.go`文件中`CheckPassword`函数展示了如何使用不同的密钥配置进行密码验证
1. 使用前端密钥解密新密码
2. 使用后端密钥解密旧密码
3. 比较解密后的明文是否相同
这种机制允许系统在不同环境下使用不同的加密配置同时保持密码验证的一致性
## 加密配置与密钥管理
### 最佳实践
基于kami_backend系统的实现以下是数据安全配置的最佳实践
#### 密钥管理
- **密钥分离**: 将加密密钥与初始化向量(IV)分离存储
- **定期轮换**: 定期更新加密密钥降低密钥泄露的风险
- **安全存储**: 密钥不应硬编码在代码中而应通过安全的配置管理机制存储
#### 算法选择
- **避免ECB模式**: ECB模式存在安全缺陷应使用CBCGCM等更安全的模式
- **使用强哈希**: 对于密码哈希建议使用bcryptscrypt或PBKDF2等专门设计的密码哈希函数而非MD5
- **多重保护**: 采用多重哈希或加盐处理增加密码破解的难度
#### 性能考量
- **缓存机制**: 对于频繁访问的加密数据考虑使用安全的缓存机制
- **异步处理**: 对于大量数据的加密解密操作考虑使用异步处理避免阻塞主线程
- **资源监控**: 监控加密操作的性能指标及时发现潜在的性能瓶颈
## 开发者安全编码指南
### 安全编码实践
开发者在使用kami_backend系统的安全机制时应遵循以下最佳实践
1. **始终使用安全工具**: 直接调用`utility/utils`包中的`EncryptPassword`等安全函数避免自行实现加密逻辑
2. **正确处理错误**: 妥善处理加密解密过程中的错误避免泄露敏感信息
3. **最小权限原则**: 加密密钥的访问应遵循最小权限原则仅限必要的模块和人员访问
4. **日志安全**: 避免在日志中记录明文密码或加密密钥等敏感信息
### 潜在风险防范
系统存在以下潜在安全风险需要特别注意
1. **MD5算法弱安全性**: MD5已被证明存在碰撞漏洞建议升级到更安全的哈希算法
2. **密钥配置一致性**: `GetBackendSecret`函数错误地使用了前端密钥配置可能导致安全漏洞
3. **缺乏密钥轮换机制**: 系统未实现自动的密钥轮换机制长期使用同一密钥增加泄露风险
4. **CBC模式IV管理**: IV的管理方式未明确说明不当的IV使用可能导致安全问题
### 推荐改进措施
为了进一步提升系统的安全性建议采取以下改进措施
1. **升级哈希算法**: 将MD5替换为bcrypt或scrypt等专门设计的密码哈希函数
2. **实现密钥轮换**: 添加密钥版本管理机制支持平滑的密钥轮换
3. **增强密钥保护**: 使用硬件安全模块(HSM)或密钥管理服务(KMS)保护加密密钥
4. **添加完整性校验**: 在加密数据中添加消息认证码(MAC)防止数据篡改
## 结论
kami_backend系统建立了一套完整的数据安全机制通过AES加密和MD5哈希算法保护敏感数据系统实现了分层的安全架构将底层加密算法与高层安全工具分离提高了代码的可维护性
然而系统在算法选择和密钥管理方面仍有改进空间建议逐步升级到更安全的密码学算法并完善密钥管理机制开发者应严格遵循安全编码指南避免引入新的安全漏洞
通过持续改进和严格的安全实践kami_backend系统能够为用户提供可靠的数据安全保障满足现代应用的安全需求

View File

@@ -0,0 +1,340 @@
# 认证机制
<cite>
**本文档引用文件**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [v_1_sys_user.go](file://internal/model/entity/v_1_sys_user.go)
</cite>
## 目录
1. [简介](#简介)
2. [认证流程概述](#认证流程概述)
3. [登录接口实现](#登录接口实现)
4. [JWT令牌生成与解析](#jwt令牌生成与解析)
5. [中间件认证机制](#中间件认证机制)
6. [会话管理与令牌刷新](#会话管理与令牌刷新)
7. [安全配置选项](#安全配置选项)
8. [开发者集成指南](#开发者集成指南)
9. [常见问题解决方案](#常见问题解决方案)
## 简介
kami_backend系统采用基于JWTJSON Web Token的认证机制结合Redis缓存实现安全的用户身份验证系统支持多种认证方式包括标准登录认证和IFrame嵌入式认证通过中间件统一拦截和验证请求认证流程涵盖用户凭证处理令牌生成验证刷新和过期处理等关键环节确保系统的安全性和可用性
## 认证流程概述
kami_backend的认证流程分为两个主要部分用户登录时的令牌生成和后续请求的令牌验证系统采用双层认证策略通过`LoginOrIframeAuth`中间件根据请求头中的`tokenFrom`字段决定使用哪种认证方式对于公开接口系统维护了一个白名单允许无需认证的访问
```mermaid
sequenceDiagram
participant 用户
participant 登录接口
participant 令牌生成器
participant Redis
participant 认证中间件
participant 业务接口
用户->>登录接口 : 提交用户名、密码、验证码
登录接口->>认证中间件 : 验证验证码
认证中间件-->>登录接口 : 验证结果
登录接口->>数据库 : 查询用户信息
数据库-->>登录接口 : 用户数据
登录接口->>令牌生成器 : 生成JWT令牌
令牌生成器->>Redis : 存储令牌
Redis-->>令牌生成器 : 存储确认
令牌生成器-->>登录接口 : 返回令牌
登录接口-->>用户 : 返回包含令牌的响应
用户->>业务接口 : 带令牌的请求
认证中间件->>Redis : 验证令牌有效性
Redis-->>认证中间件 : 令牌状态
认证中间件->>令牌解析器 : 解析JWT令牌
令牌解析器-->>认证中间件 : 用户信息
认证中间件->>令牌刷新器 : 检查是否需要刷新
令牌刷新器-->>认证中间件 : 新令牌如需
认证中间件-->>业务接口 : 继续处理请求
```
**图示来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
## 登录接口实现
登录接口位于`internal/controller/sys_user_login/sys_user_login_v1_user_login.go`负责处理用户登录请求接口实现包含多层安全验证确保认证过程的安全性
### 认证步骤
1. **验证码验证**首先验证用户提交的验证码是否正确
2. **用户名密码验证**查询数据库验证用户名和密码
3. **双因素认证**如果用户启用了TOTP验证提供的验证码
4. **用户状态检查**确认用户账户处于正常状态
5. **令牌生成**通过`GenerateUserToken`函数生成JWT令牌
### 安全特性
- 验证码机制防止暴力破解
- 密码使用盐值加密存储
- 支持TOTP双因素认证
- 用户状态检查防止禁用账户登录
**本节来源**
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
- [v_1_sys_user.go](file://internal/model/entity/v_1_sys_user.go)
## JWT令牌生成与解析
系统使用`github.com/golang-jwt/jwt/v5`库实现JWT令牌的生成和解析确保认证令牌的安全性和标准化
### 令牌结构
```go
type UserToken struct {
UserID string
Username string
jwt.RegisteredClaims
}
```
### 令牌生成
`GenerateUserToken`函数负责生成JWT令牌主要步骤包括
1. 从配置中获取令牌选项超时时间加密密钥等
2. 创建包含用户信息和声明的`UserToken`结构体
3. 使用HS256算法和配置的加密密钥签名生成令牌
4. 将令牌存储到Redis缓存中如果配置了Redis模式
```go
func GenerateUserToken(ctx context.Context, userName, userID string) (string, error) {
tokenCfg, err := config.NewConfig(ctx).GetTokenOptions()
if err != nil {
return "", err
}
t := UserToken{
UserID: userID,
Username: userName,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "Auth Server",
Subject: userName,
Audience: nil,
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(tokenCfg.Timeout) * time.Second)),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: utils.GenerateRandomUUID(),
},
}
token, err := t.genToken(ctx)
if tokenCfg.CacheModel == CacheModelRedis {
_ = cache.NewCache().Set(ctx, fmt.Sprintf("Token:%s:%s:%s", tokenCfg.CacheKey, t.UserID, t.ID), token, time.Duration(tokenCfg.Timeout*int64(time.Second)))
}
return token, err
}
```
### 令牌解析
`ParseUserToken`函数负责解析和验证JWT令牌
1. 从请求中提取令牌支持Bearer格式
2. 使用配置的加密密钥验证令牌签名
3. 检查令牌是否过期
4. 返回解析后的用户信息
**本节来源**
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
## 中间件认证机制
认证中间件位于`internal/middleware/auth.go`是整个系统认证的核心组件负责拦截和验证所有请求的认证信息
### 认证类型
系统支持三种认证方式
- **白名单认证**对特定路径的请求直接放行
- **登录认证**基于JWT令牌的标准认证
- **IFrame认证**基于AES加密的嵌入式认证
### 认证流程
```mermaid
flowchart TD
A[请求到达] --> B{路径在白名单?}
B --> |是| C[放行请求]
B --> |否| D{tokenFrom=login?}
D --> |是| E[执行登录认证]
D --> |否| F{tokenFrom=iframe?}
F --> |是| G[执行IFrame认证]
F --> |否| H[返回错误:token来源不明]
E --> I{认证成功?}
I --> |是| J[放行请求]
I --> |否| K[返回认证错误]
G --> L{认证成功?}
L --> |是| M[放行请求]
L --> |否| N[返回认证错误]
```
### 白名单路径
系统为特定接口配置了白名单无需认证即可访问
- `/api/merchant/order/query`
- `/api/restriction/block/order`
- `/api/cardInfo/appleCard/submit`
- 其他公开接口...
**本节来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
## 会话管理与令牌刷新
系统实现了完善的会话管理机制通过Redis存储令牌状态并支持令牌自动刷新功能
### 会话存储
- **存储模式**支持内存和Redis两种模式生产环境推荐使用Redis
- **存储键格式**`Token:{cacheKey}:{userID}:{uuid}`
- **过期时间**与令牌超时时间一致自动同步过期
### 令牌刷新机制
系统在每次请求验证令牌时检查是否需要刷新
1. 计算令牌已使用时间
2. 如果使用时间超过`MaxRefresh`配置但未过期则生成新令牌
3. 将新令牌通过`refresh-token`响应头返回给客户端
```go
func RefreshUserToken(ctx context.Context, userToken UserToken) (newToken string, err error) {
tokenCfg, err := config.NewConfig(ctx).GetTokenOptions()
if err != nil {
return "", err
}
issuerDate, err := userToken.GetIssuedAt()
if err != nil {
return "", errors.New("invalid token")
}
if tokenCfg.MaxRefresh == 0 {
return "", nil
}
if time.Since(issuerDate.Time) > time.Duration(tokenCfg.MaxRefresh) &&
time.Since(issuerDate.Time) < time.Duration(tokenCfg.Timeout) {
newToken, err = GenerateUserToken(ctx, userToken.Username, userToken.UserID)
return newToken, err
}
return
}
```
### 令牌注销
系统提供`DeleteTokenFromRedis`函数用于主动注销令牌通常在用户登出时调用
**本节来源**
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)
## 安全配置选项
系统通过配置文件灵活管理认证相关的安全参数所有配置位于`manifest/config/config.yaml`
### 配置项说明
| 配置项 | 默认值 | 说明 |
|-------|-------|------|
| `token.timeout` | 3600 | 令牌有效期 |
| `token.maxRefresh` | 1800 | 令牌最大刷新时间 |
| `token.cacheModel` | redis | 缓存模式memory/redis |
| `token.cacheKey` | user_token | Redis缓存键前缀 |
| `token.encryptKey` | 随机生成 | JWT签名加密密钥 |
| `secret.frontend.key` | 随机生成 | 前端加密密钥 |
| `secret.frontend.iv` | 随机生成 | 前端加密IV向量 |
### 配置加载
配置通过`utility/config/config.go`中的`GetTokenOptions`函数加载
```go
func (c *Config) GetTokenOptions() (opts TokenOptions, err error) {
result, err := c.getDataByKey("token")
if err != nil {
return
}
if err2 := result.Struct(&opts); err2 != nil {
err = err2
return
}
return
}
```
### 安全建议
- 定期轮换`encryptKey``secret`配置
- 生产环境必须使用Redis模式而非内存模式
- 根据业务需求合理设置`timeout``maxRefresh`
- 监控异常登录行为并及时响应
**本节来源**
- [config.go](file://utility/config/config.go)
- [user_token.go](file://utility/token/user_token.go)
## 开发者集成指南
本指南为开发者提供认证机制的集成方法和最佳实践
### 前端集成
1. **登录流程**
- 调用`/api/sysUser/login`接口提交认证信息
- 保存返回的令牌用于后续请求
- 监听`refresh-token`响应头更新本地令牌
2. **请求认证**
- 在请求头中添加`Authorization: Bearer {token}`
- 或在请求头中添加`tokenFrom: login`
3. **错误处理**
- `401 Unauthorized`令牌无效或过期需要重新登录
- `403 Forbidden`权限不足
- `429 Too Many Requests`请求过于频繁
### 后端集成
1. **保护接口**在路由中使用`LoginOrIframeAuth`中间件
2. **获取用户信息**通过上下文获取已认证的用户信息
3. **自定义认证**可根据需要扩展认证逻辑
### 测试建议
- 使用`user_token_test.go`中的测试用例验证令牌功能
- 模拟各种异常情况过期令牌无效签名等
- 测试白名单路径的访问权限
**本节来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [sys_user_login_v1_user_login.go](file://internal/controller/sys_user_login/sys_user_login_v1_user_login.go)
## 常见问题解决方案
### 问题1登录成功但后续请求返回401错误
**可能原因**
- 令牌未正确添加到请求头
- 令牌格式错误缺少Bearer前缀
- Redis连接问题导致令牌验证失败
**解决方案**
1. 检查请求头中`Authorization`字段格式是否正确
2. 确认Redis服务正常运行
3. 检查`token.cacheKey`配置是否一致
### 问题2令牌频繁过期
**可能原因**
- `timeout`配置值过小
- 系统时间不同步
- 令牌刷新机制未正常工作
**解决方案**
1. 适当增加`token.timeout`配置值
2. 确保服务器时间同步
3. 检查`maxRefresh`配置是否合理
### 问题3IFrame认证失败
**可能原因**
- `tokenFrom`头未设置为`iframe`
- 前端加密密钥或IV配置错误
- 令牌超过30分钟有效期
**解决方案**
1. 确认请求头中`tokenFrom: iframe`
2. 检查`secret.frontend.key``secret.frontend.iv`配置
3. 确保前端正确生成加密令牌
### 问题4Redis存储的令牌无法读取
**可能原因**
- 缓存键前缀不匹配
- Redis数据库选择错误
- 序列化格式不一致
**解决方案**
1. 检查`token.cacheKey`配置
2. 确认Redis连接配置
3. 验证序列化和反序列化逻辑
**本节来源**
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [config.go](file://utility/config/config.go)

View File

@@ -0,0 +1,181 @@
# 快速入门
<cite>
**本文档中引用的文件**
- [Makefile](file://Makefile)
- [hack/hack.mk](file://hack/hack.mk)
- [main.go](file://main.go)
- [manifest/docker/docker-compose.yml](file://manifest/docker/docker-compose.yml)
- [utility/config/database.go](file://utility/config/database.go)
- [internal/dao/internal/v_1_migrations.go](file://internal/dao/internal/v_1_migrations.go)
- [internal/dao/internal/v_1_sys_config_dict.go](file://internal/dao/internal/v_1_sys_config_dict.go)
</cite>
## 目录
1. [简介](#简介)
2. [开发环境配置](#开发环境配置)
3. [依赖安装与构建](#依赖安装与构建)
4. [数据库初始化](#数据库初始化)
5. [项目启动](#项目启动)
6. [Hello World 示例调用基础 API](#hello-world-示例调用基础-api)
7. [常见问题排查指南](#常见问题排查指南)
8. [总结](#总结)
## 简介
本指南旨在为新开发者提供 `kami_backend` 项目的快速入门说明通过本指南您将在 15 分钟内完成开发环境的搭建依赖安装数据库初始化服务启动并成功调用一个基础 API 端点本项目使用 GoFrame 框架构建通过 `Makefile` 提供标准化操作命令简化开发流程
**Section sources**
- [main.go](file://main.go#L1-L50)
- [Makefile](file://Makefile#L1-L6)
## 开发环境配置
在开始之前请确保您的开发环境已安装以下工具
- **Go 1.20+**本项目基于 Go 语言开发建议使用 1.20 或更高版本
- **GF CLI 工具**GoFrame 官方命令行工具用于代码生成和项目管理
- **Docker Docker Compose**用于容器化部署和依赖服务管理
- **Git**用于版本控制和获取项目代码
安装 GF CLI
```bash
go install github.com/gogf/gf/v2/tool/gf@latest
```
确保 `gf` 命令可在终端中执行
```bash
gf -v
```
**Section sources**
- [hack/hack.mk](file://hack/hack.mk#L1-L5)
## 依赖安装与构建
项目使用 `Makefile` 作为主要操作入口构建二进制文件的命令如下
```bash
make build
```
该命令会调用 `gf build -ew`其中
- `-e` 表示启用调试信息
- `-w` 表示启用竞争检测race detection
此命令将生成可执行文件完成项目依赖的自动下载与编译
**Section sources**
- [Makefile](file://Makefile#L5-L8)
- [hack/hack.mk](file://hack/hack.mk#L10-L13)
## 数据库初始化
项目使用 GoFrame DAOData Access Object机制进行数据库操作数据库配置位于 `utility/config/database.go`通过 `g.DB("v1")` 获取数据库实例
初始化数据库表结构和迁移脚本
```bash
make dao
```
该命令执行 `gf gen dao`根据模型自动生成 DAO 层代码包括
- 数据表映射结构
- 基础增删改查方法
- 事务支持
数据库迁移记录表 `migrations` 用于跟踪数据库变更确保多环境一致性
**Section sources**
- [utility/config/database.go](file://utility/config/database.go#L1-L9)
- [internal/dao/internal/v_1_migrations.go](file://internal/dao/internal/v_1_migrations.go#L31-L69)
- [internal/dao/internal/v_1_sys_config_dict.go](file://internal/dao/internal/v_1_sys_config_dict.go#L43-L90)
- [hack/hack.mk](file://hack/hack.mk#L22-L25)
## 项目启动
启动项目前请确保配置文件已准备就绪项目配置文件位于 `manifest/config/config.yaml`
使用以下命令启动服务
```bash
make run
```
> **注意**`Makefile` 中未直接定义 `run` 命令 `gf` 工具默认支持 `gf run` 启动主程序您也可直接执行
> ```bash
> go run main.go
> ```
服务启动后默认监听端口为 `12401`可通过 `docker-compose.yml` 查看端口映射配置
**Section sources**
- [main.go](file://main.go#L1-L50)
- [manifest/docker/docker-compose.yml](file://manifest/docker/docker-compose.yml#L1-L18)
## Hello World 示例调用基础 API
项目提供健康检查 API 作为最简单的测试端点
1. 确保服务已成功启动
2. 使用 `curl` 发起请求
```bash
curl http://localhost:12401/monitor/v1/healthcheck
```
预期返回
```json
{
"code": 0,
"message": "OK",
"data": {
"status": "healthy"
}
}
```
该接口由 `api/monitor/v1/heathcheck.go` 定义通过 `monitor` 模块注册路由用于验证服务是否正常运行
**Section sources**
- [api/monitor/v1/heathcheck.go](file://api/monitor/v1/heathcheck.go)
- [internal/controller/monitor/monitor_v1_health_check.go](file://internal/controller/monitor/monitor_v1_health_check.go)
## 常见问题排查指南
### 1. `gf` 命令未找到
**问题**执行 `make build` 时报错 `gf: command not found`
**解决方案**确保已安装 GF CLI 并将其路径加入 `PATH` 环境变量
```bash
export PATH=$PATH:$(go env GOPATH)/bin
```
### 2. 数据库连接失败
**问题**启动时报错 `failed to connect database`
**解决方案**检查 `manifest/config/config.yaml` 中的数据库配置项确保主机端口用户名密码正确
### 3. 端口被占用
**问题**服务无法启动提示端口 `12401` 已被占用
**解决方案**修改 `docker-compose.yml` 中的端口映射或终止占用进程
```bash
lsof -i :12401
kill -9 <PID>
```
### 4. 依赖下载失败
**问题**`go mod download` 失败无法拉取外部依赖
**解决方案**配置国内代理
```bash
go env -w GOPROXY=https://goproxy.cn,direct
```
### 5. DAO 代码未生成
**问题**执行 `make dao` 无输出或报错
**解决方案**确保项目根目录存在 `model` 定义文件并检查 `gf` 版本是否兼容
**Section sources**
- [hack/hack.mk](file://hack/hack.mk#L10-L74)
- [manifest/docker/docker-compose.yml](file://manifest/docker/docker-compose.yml#L1-L18)
- [utility/config/database.go](file://utility/config/database.go#L1-L9)
## 总结
通过本指南您已成功完成 `kami_backend` 项目的环境搭建构建数据库初始化与服务启动并验证了基础 API 的可用性项目通过 `Makefile` 统一管理常用命令结合 GoFrame 生态工具链极大提升了开发效率建议后续查阅 `api/` 目录下的各模块接口文档深入了解业务逻辑实现

View File

@@ -0,0 +1,239 @@
# 技术栈与依赖
<cite>
**本文档中引用的文件**
- [main.go](file://main.go)
- [go.mod](file://go.mod)
- [rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [config.go](file://utility/otel/config.go)
- [manager.go](file://utility/otel/manager.go)
- [utils.go](file://utility/otel/utils.go)
- [auth.go](file://internal/middleware/auth.go)
- [user_token.go](file://utility/token/user_token.go)
- [sys_casbin.go](file://internal/service/sys_casbin.go)
</cite>
## 目录
1. [简介](#简介)
2. [核心技术栈概述](#核心技术栈概述)
3. [Go语言与GoFrame框架](#go语言与goframe框架)
4. [数据库与缓存系统](#数据库与缓存系统)
5. [OpenTelemetry可观测性集成](#opentelemetry可观测性集成)
6. [Casbin与RBAC权限控制](#casbin与rbac权限控制)
7. [RESTful API设计与实现](#restful-api设计与实现)
8. [技术选型与权衡](#技术选型与权衡)
9. [总结](#总结)
## 简介
本项目 `kami_backend` 是一个基于 Go 语言和 GoFrame 框架构建的后端服务系统旨在为多平台卡券充值订单管理商户服务等业务提供稳定高效的技术支持系统采用现代化微服务架构理念集成了 OpenTelemetry 实现全面的可观测性使用 Casbin 实现灵活的基于角色的访问控制RBAC并通过 RESTful API 提供标准化接口本文档将深入剖析项目所采用的核心技术栈详细说明其设计原理实现方式配置选项及协同工作机制为开发者提供从入门到精通的完整技术指南
## 核心技术栈概述
`kami_backend` 的技术栈围绕高性能高可靠性和可维护性构建主要包含以下核心组件
- **编程语言**: Go (Golang) 1.24.0
- **开发框架**: GoFrame v2.9.3
- **数据库**: MySQL
- **缓存**: Redis
- **可观测性**: OpenTelemetry (OTel)
- **权限控制**: Casbin
- **API 风格**: RESTful
这些技术的组合为系统提供了强大的并发处理能力简洁的开发体验高效的持久化与缓存机制全面的监控追踪能力以及细粒度的安全访问控制
**Section sources**
- [main.go](file://main.go)
- [go.mod](file://go.mod)
## Go语言与GoFrame框架
项目采用 Go 语言作为主要开发语言利用其出色的并发模型goroutine channel高效的编译性能和简洁的语法确保了服务的高性能和高稳定性GoFrame 框架作为 Go 语言的全栈开发框架为项目提供了丰富的基础设施支持
GoFrame 在本项目中扮演了核心角色提供了包括但不限于以下功能
- **Web 服务**: 基于 `ghttp` 模块构建 RESTful API
- **配置管理**: 通过 `genv` `config` 模块管理环境变量和配置文件
- **日志系统**: 使用 `glog` 模块进行结构化日志记录并与 OpenTelemetry 集成
- **数据库 ORM**: 集成 `gogf/gf/contrib/drivers/mysql/v2` 驱动提供便捷的数据库操作
- **NoSQL 支持**: 集成 `gogf/gf/contrib/nosql/redis/v2` 驱动简化 Redis 操作
- **依赖注入**: 通过 `service` 包实现服务层的注册与调用
GoFrame 的模块化设计使得项目结构清晰`internal` 目录下的 `controller``service``dao``model` 等分层结构遵循了典型的 MVC 模式保证了代码的可读性和可维护性
**Section sources**
- [main.go](file://main.go#L1-L50)
- [go.mod](file://go.mod#L1-L104)
## 数据库与缓存系统
系统采用 MySQL 作为主关系型数据库用于持久化存储用户信息订单数据商户配置权限规则等核心业务数据项目通过 GoFrame MySQL 驱动进行数据库交互`internal/dao` 目录下的大量 `.go` 文件定义了与数据库表一一对应的 DAOData Access Object实现了数据的增删改查操作
Redis 被用作高性能缓存和会话存储在本项目中Redis 的主要用途包括
- **Token 缓存**: 用户登录后生成的 JWT Token 会存储在 Redis 用于实现 Token 的续签和失效控制
- **限流**: 结合 `utility/limiter` 模块利用 Redis 实现分布式请求限流
- **临时数据存储**: 存储验证码会话信息等临时性数据
这种MySQL + Redis的组合模式是现代 Web 应用的标配MySQL 保证了数据的强一致性和持久性 Redis 则极大地提升了系统的响应速度和吞吐量
**Section sources**
- [go.mod](file://go.mod#L1-L104)
- [utility/limiter/redis.go](file://utility/limiter/redis.go)
## OpenTelemetry可观测性集成
为了实现对系统运行状态的全面监控项目深度集成了 OpenTelemetry (OTel)构建了一个集日志Logging指标Metrics和链路追踪Tracing于一体的可观测性体系
### 集成架构
`main.go` 系统启动时会调用 `otel.InitWithConfig()` 函数来初始化 OTel 系统该函数接收一个 `Config` 对象其中包含了服务名称Collector 地址是否启用安全连接等关键配置
```mermaid
sequenceDiagram
participant main as main.go
participant otel as OTel模块
participant Collector as OTel Collector
main->>otel : InitWithConfig(config)
otel->>otel : NewOTelManager(config)
otel->>otel : 验证配置
otel->>otel : 创建Resource(服务名,主机IP)
otel->>otel : 初始化Tracing
otel->>otel : 创建Trace Exporter(连接Collector)
otel->>otel : 设置TracerProvider
otel->>otel : 初始化Logging
otel->>otel : 创建Log Exporter(连接Collector)
otel->>otel : 设置LogProvider
otel-->>main : 初始化成功
main->>Collector : 发送Trace和Log数据
```
**Diagram sources**
- [main.go](file://main.go#L30-L50)
- [utility/otel/utils.go](file://utility/otel/utils.go#L22-L33)
- [utility/otel/manager.go](file://utility/otel/manager.go#L50-L257)
### 核心组件
- **Manager**: `utility/otel/manager.go` 中的 `Manager` 结构体是 OTel 系统的核心管理器负责协调 TracingLogging Metrics 的初始化与生命周期管理
- **Config**: `utility/otel/config.go` 定义了 `Config` 结构体用于封装所有 OTel 相关的配置项并提供了默认值和验证功能
- **Exporter**: 系统使用 `otlptracegrpc` `otlploggrpc` 作为 Exporter通过 gRPC 协议将追踪和日志数据发送到指定的 Collector `38.38.251.113:31547`
- **Logger Handler**: `glog` 的日志处理器被替换为 OTel `LogHandler`确保所有 `glog` 输出的日志都能被 OTel 捕获并导出
此集成方案使得开发者可以通过统一的平台 JaegerTempoLoki查看请求的完整调用链路分析性能瓶颈排查错误日志极大地提升了系统的可维护性和故障排查效率
**Section sources**
- [main.go](file://main.go#L30-L50)
- [utility/otel/config.go](file://utility/otel/config.go)
- [utility/otel/manager.go](file://utility/otel/manager.go)
- [utility/otel/utils.go](file://utility/otel/utils.go)
## Casbin与RBAC权限控制
项目采用 Casbin 作为权限管理引擎实现了基于角色的访问控制RBAC模型确保了系统的安全性
### RBAC 模型定义
`resource/casbin/rbac_model.conf` 文件定义了权限控制的核心模型
- **[request_definition]**: 定义了请求的基本元素 `r = sub, obj, act`主体对什么对象做了什么动作
- **[policy_definition]**: 定义了策略规则 `p = sub, obj, act`允许谁对什么做什么
- **[role_definition]**: 定义了角色继承关系 `g = _, _`例如管理员角色可以继承普通用户的所有权限
- **[matchers]**: 定义了匹配逻辑 `m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act`表示当请求的主体拥有策略中的主体角色且对象和动作都匹配时请求被允许
### 实现方式
- **服务接口**: `internal/service/sys_casbin.go` 定义了 `ICasbin` 接口提供了获取 `SyncedEnforcer`加载/保存策略增删策略等方法
- **策略存储**: 权限策略Policy存储在数据库中通过 `v_1_sys_casbin_rule` 实现了策略的持久化和动态管理
- **中间件集成**: API 请求处理流程中通过中间件调用 Casbin `Enforce` 方法传入当前用户sub请求路径obj和请求方法act根据模型和策略判断该请求是否被允许
这种设计将权限控制逻辑与业务逻辑解耦使得权限规则可以独立配置和管理极大地提高了系统的灵活性和安全性
```mermaid
classDiagram
class CasbinEnforcer {
+Enforce(sub, obj, act) bool
+AddPolicy()
+RemovePolicy()
}
class RBACModel {
-modelPath : string
-policyPath : string
}
class PolicyStorage {
<<interface>>
+LoadPolicy()
+SavePolicy()
}
class DatabaseAdapter {
+LoadPolicy()
+SavePolicy()
}
class RequestMiddleware {
+CheckPermission()
}
RequestMiddleware --> CasbinEnforcer : "调用"
CasbinEnforcer --> RBACModel : "使用"
CasbinEnforcer --> PolicyStorage : "依赖"
PolicyStorage <|.. DatabaseAdapter : "实现"
RBACModel --> "rbac_model.conf" : "读取"
```
**Diagram sources**
- [resource/casbin/rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [internal/service/sys_casbin.go](file://internal/service/sys_casbin.go)
- [internal/middleware/auth.go](file://internal/middleware/auth.go)
**Section sources**
- [resource/casbin/rbac_model.conf](file://resource/casbin/rbac_model.conf)
- [internal/service/sys_casbin.go](file://internal/service/sys_casbin.go)
## RESTful API设计与实现
项目遵循 RESTful 设计原则通过清晰的 URL 路径和 HTTP 方法来操作资源
### 设计原则
- **资源导向**: API 路径以名词复数形式表示资源 `/api/sysUser/v1/user` 表示用户资源
- **HTTP 方法语义化**:
- `GET` 用于获取资源
- `POST` 用于创建资源
- `PUT` 用于更新资源
- `DELETE` 用于删除资源
- **状态码**: 使用标准的 HTTP 状态码 200, 400, 401, 403, 404, 500来表示请求结果
- **版本控制**: API 路径中包含版本号 `/v1`便于未来进行非兼容性升级
### 实现方式
- **路由定义**: API 路由在 `api` 目录下的各个 `.go` 文件中定义 `api/sysUser/v1/sysUser.go`
- **控制器**: `internal/controller` 目录下的控制器处理具体的业务逻辑例如`internal/controller/sysUser/sysUser_v1_user_add.go` 处理用户的创建请求
- **中间件**: 请求首先经过中间件处理 `internal/middleware/auth.go` 中的 `LoginOrIframeAuth` 函数负责身份认证和授权检查该中间件实现了白名单机制 `/api/merchant/order/query` 等公开接口放行对其他接口则验证 JWT Token
- **Token 管理**: `utility/token` 包负责 Token 的生成解析续签和从 Redis 中校验`GetRequestToken` 函数从 `Authorization` 头或 `token` 参数中提取 Token`ParseUserToken` 函数解析 JWT`RefreshUserToken` 函数在 Token 即将过期时生成新 Token
```mermaid
flowchart TD
A[客户端请求] --> B{路径在白名单?}
B --> |是| C[直接放行]
B --> |否| D[检查tokenFrom头]
D --> E{tokenFrom=login?}
E --> |是| F[调用loginAuth]
E --> |否| G{tokenFrom=iframe?}
G --> |是| H[调用iFrameAuth]
G --> |否| I[返回错误]
F --> J{Token有效?}
H --> K{Token有效?}
J --> |是| L[续签Token]
K --> |是| M[续签Token]
J --> |否| N[返回401]
K --> |否| O[返回401]
L --> P[进入业务逻辑]
M --> P
C --> P
```
**Diagram sources**
- [internal/middleware/auth.go](file://internal/middleware/auth.go)
- [utility/token/user_token.go](file://utility/token/user_token.go)
- [utility/token/utils.go](file://utility/token/utils.go)
**Section sources**
- [internal/middleware/auth.go](file://internal/middleware/auth.go)
- [utility/token/user_token.go](file://utility/token/user_token.go)
## 技术选型与权衡
### 选型原因
- **Go + GoFrame**: Go 语言的高性能和高并发特性非常适合后端服务GoFrame 提供了开箱即用的全栈解决方案显著提升了开发效率减少了项目初期的基础设施搭建成本
- **OpenTelemetry**: 作为云原生计算基金会CNCF的毕业项目OTel 是可观测性领域的事实标准具有强大的社区支持和广泛的生态系统集成能力
- **Casbin**: Casbin 是一个强大的高效的开源访问控制框架支持多种模型RBAC, ABAC, ACL 其策略可动态加载非常适合需要灵活权限管理的复杂系统
### 权衡与约束
- **OTel 的复杂性**: OTel 功能强大但配置相对复杂需要部署 Collector 和后端存储 Jaeger, Prometheus, Loki增加了运维成本项目通过封装 `utility/otel` 模块简化了集成过程
- **GoFrame 的侵入性**: GoFrame 是一个全栈框架虽然功能丰富但也带来了一定的框架侵入性一旦深度使用迁移到其他框架的成本较高
- **JWT + Redis**: 采用 JWT 实现无状态认证但为了实现 Token 的主动失效必须依赖 Redis 存储 Token 的状态这在一定程度上牺牲了无状态性但换来了更好的安全性
## 总结
`kami_backend` 项目通过精心的技术选型构建了一个现代化高性能高可用的后端服务系统Go 语言和 GoFrame 框架为系统提供了坚实的基础MySQL Redis 确保了数据的可靠存储和高效访问OpenTelemetry 的集成赋予了系统强大的可观测性使得运维和故障排查变得简单高效Casbin 的引入实现了灵活安全的权限控制RESTful API 的设计保证了接口的清晰和标准化整体技术栈的选择体现了对性能可维护性安全性和开发效率的综合考量为业务的稳定运行和持续发展提供了有力的技术保障

View File

@@ -0,0 +1,412 @@
# 卡密数据模型
<cite>
**本文档引用的文件**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
- [v_1_card_apple_history_info.go](file://internal/dao/internal/v_1_card_apple_history_info.go)
- [v_1_card_apple_account_info_history.go](file://internal/dao/internal/v_1_card_apple_account_info_history.go)
- [entity/v_1_card_apple_recharge_info.go](file://internal/model/entity/v_1_card_apple_recharge_info.go)
- [do/v_1_card_apple_recharge_info.go](file://internal/model/do/v_1_card_apple_recharge_info.go)
- [card_apple.go](file://internal/consts/card_apple.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
</cite>
## 目录
1. [引言](#引言)
2. [卡密数据模型概述](#卡密数据模型概述)
3. [核心实体字段定义](#核心实体字段定义)
4. [主键与索引设计](#主键与索引设计)
5. [外键关系与实体关联](#外键关系与实体关联)
6. [验证规则与业务逻辑](#验证规则与业务逻辑)
7. [数据表模式与示例](#数据表模式与示例)
8. [访问模式与缓存策略](#访问模式与缓存策略)
9. [数据生命周期管理](#数据生命周期管理)
10. [GoFrame ORM映射与DAO实现](#goframe-orm映射与dao实现)
## 引言
本文档全面阐述kami_backend系统中卡密数据模型的设计与实现重点围绕苹果礼品卡Apple Card相关实体展开文档详细说明了卡密数据的核心实体字段定义业务规则数据关系以及在GoFrame框架下的实现方式为系统维护开发和优化提供权威参考
## 卡密数据模型概述
卡密数据模型是kami_backend系统的核心组成部分主要用于管理苹果礼品卡的充值信息账户信息及操作历史该模型通过多个相互关联的数据表实现主要包括卡密充值信息表card_apple_recharge_info卡密账户信息表card_apple_account_info和操作历史记录表card_apple_history_info这些实体共同构成了一个完整的卡密生命周期管理体系支持从卡密生成充值处理到状态核销的全流程业务
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
## 核心实体字段定义
本节详细说明卡密相关核心实体的所有字段定义数据类型和业务含义
### v_1_card_apple_recharge_info 实体
该实体存储卡密充值的详细信息是卡密业务的核心数据表
| 字段名 | 数据类型 | 业务含义 |
|--------|---------|---------|
| id | uint | 主键唯一标识一条充值记录 |
| order_no | string | 订单号关联外部订单系统 |
| account_id | string | 账户ID关联卡密账户信息 |
| account_name | string | 账户名称便于识别 |
| card_no | string | 卡号苹果礼品卡的号码 |
| card_pass | string | 卡密苹果礼品卡的密码 |
| merchant_id | string | 商户ID标识交易商户 |
| balance | float64 | 余额账户当前余额 |
| card_amount | float64 | 卡面充值金额卡密的标称价值 |
| notify_status | int | 通知状态标识回调通知结果 |
| status | int | 状态当前充值订单的状态 |
| actual_amount | float64 | 实际充值金额最终确认的充值金额 |
| callback_url | string | 回调URL用于异步通知结果 |
| callback_count | int | itunes回调次数记录回调尝试次数 |
| distribution_count | int | 分发次数记录调度分发次数 |
| created_user_id | string | 创建者ID记录创建人 |
| attach | string | 附加信息用于携带额外数据 |
| remark | string | 备注业务备注信息 |
| created_at | *gtime.Time | 创建日期记录创建时间 |
| updated_at | *gtime.Time | 更新日期记录最后更新时间 |
| deleted_at | *gtime.Time | 删除日期软删除标记 |
**文档来源**
- [entity/v_1_card_apple_recharge_info.go](file://internal/model/entity/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
### v_1_card_apple_account_info 实体
该实体存储卡密账户的详细信息用于管理充值账户的状态和限额
| 字段名 | 数据类型 | 业务含义 |
|--------|---------|---------|
| id | string | 主键唯一标识一个账户 |
| account | string | 账户苹果ID账号 |
| password | string | 密码苹果ID密码 |
| balance | float64 | 余额账户当前余额 |
| balance_itunes | float64 | balance_itunesitunes商店余额 |
| status | int | 状态账户当前状态 |
| today_recharge_amount | float64 | today_recharge_amount今日已充值金额 |
| today_recharge_count | int | today_recharge_count今日已充值次数 |
| today_recharge_datetime | string | today_recharge_datetime今日最后充值时间 |
| created_user_id | string | created_user_id创建者ID |
| created_user_role | string | created_user_role创建者角色 |
| max_amount_limit | float64 | max_amount_limit最大单日充值金额限制 |
| max_count_limit | int | max_count_limit最大单日充值次数限制 |
| remark | string | remark账户备注 |
| created_at | string | created_at创建日期 |
| updated_at | string | updated_at更新日期 |
| deleted_at | string | deleted_at删除日期 |
**文档来源**
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
## 主键与索引设计
卡密数据模型采用合理的主键和索引设计以确保数据完整性和查询性能
### 主键设计
- **v_1_card_apple_recharge_info** 表使用 `id` 字段作为自增主键确保每条充值记录的唯一性
- **v_1_card_apple_account_info** 表使用 `id` 字段作为主键通常为UUID格式保证账户标识的全局唯一性
### 唯一索引
- **card_no** 字段在 `v_1_card_apple_recharge_info` 表上建立了唯一索引防止同一卡号被重复提交充值确保卡密的唯一性使用原则
### 普通索引
- **order_no** 字段建立了索引用于快速通过订单号查询充值记录
- **account_id** 字段建立了索引用于高效关联账户信息和查询特定账户的所有充值记录
- **status** 字段建立了索引支持按状态"交易中""交易成功"进行高效筛选和批量处理
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
## 外键关系与实体关联
卡密数据模型通过外键和逻辑关联建立实体间的关系
### 实体关系图
```mermaid
erDiagram
v_1_card_apple_recharge_info {
uint id PK
string order_no UK
string account_id FK
string card_no UK
string card_pass
float64 card_amount
int status
float64 actual_amount
}
v_1_card_apple_account_info {
string id PK
string account UK
string password
float64 balance
int status
float64 today_recharge_amount
int today_recharge_count
}
v_1_card_apple_history_info {
uint id PK
string account_id FK
string order_no FK
int recharge_id FK
string operation
string remark
}
v_1_card_apple_recharge_info ||--o{ v_1_card_apple_history_info : "充值记录-历史"
v_1_card_apple_account_info ||--o{ v_1_card_apple_recharge_info : "账户-充值"
v_1_card_apple_account_info ||--o{ v_1_card_apple_history_info : "账户-操作历史"
```
**图示来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
- [v_1_card_apple_history_info.go](file://internal/dao/internal/v_1_card_apple_history_info.go)
### 关系说明
- **v_1_card_apple_recharge_info** **v_1_card_apple_account_info** 通过 `account_id` 字段关联表示每条充值记录都归属于一个具体的充值账户
- **v_1_card_apple_recharge_info** **v_1_card_apple_history_info** 通过 `order_no` `recharge_id` 字段关联记录针对特定充值订单的所有操作历史
- **v_1_card_apple_account_info** **v_1_card_apple_history_info** 通过 `account_id` 字段关联记录账户级别的所有操作历史
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
- [v_1_card_apple_history_info.go](file://internal/dao/internal/v_1_card_apple_history_info.go)
## 验证规则与业务逻辑
卡密数据模型包含严格的验证规则和复杂的业务逻辑确保数据的准确性和业务流程的正确性
### 卡密格式校验
- 卡号card_no和卡密card_pass必须符合苹果礼品卡的格式规范通常为16位数字组合
- 在提交充值请求时系统会对卡号和卡密进行基础格式验证防止无效数据进入处理流程
### 状态流转规则
卡密充值订单的状态遵循严格的流转规则
```mermaid
stateDiagram-v2
[*] --> Created
Created --> Processing : 开始处理
Created --> Failed : 格式校验失败
Processing --> Success : 充值成功
Processing --> Failed : 充值失败
Processing --> Refunded : 退款
Success --> Refunded : 申请退款
Failed --> Processing : 重试
Refunded --> [*]
```
**图示来源**
- [card_apple.go](file://internal/consts/card_apple.go)
状态码定义
- **0**: 创建等待处理
- **1**: 交易成功
- **2**: 交易中处理中
- **3**: 交易失败
- **4**: 充值受限
- **5**: 充值过期
### 业务规则
- **最小充值金额**根据 `AppleCardMinRechargeAmount` 常量50低于此金额的充值可能导致账户被冻结
- **最大充值金额**根据 `AppleCardMaxRechargeAmount` 常量4500单次充值不能超过此上限
- **账户状态控制**账户状态status直接影响充值操作"账号禁用""账号密码错误"状态的账户无法进行充值
- **防重复提交**通过 `card_no` 唯一索引和业务层逻辑双重校验防止同一卡密被重复提交
**文档来源**
- [card_apple.go](file://internal/consts/card_apple.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
## 数据表模式与示例
本节提供卡密数据表的模式定义和示例数据
### 数据表模式
```sql
-- 卡密充值信息表
CREATE TABLE card_apple_recharge_info (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
order_no VARCHAR(64) UNIQUE NOT NULL,
account_id VARCHAR(36) NOT NULL,
account_name VARCHAR(64),
card_no VARCHAR(32) UNIQUE NOT NULL,
card_pass VARCHAR(32) NOT NULL,
merchant_id VARCHAR(36),
balance DECIMAL(10,2),
card_amount DECIMAL(10,2) NOT NULL,
notify_status INT,
status INT NOT NULL DEFAULT 0,
actual_amount DECIMAL(10,2),
callback_url VARCHAR(255),
callback_count INT DEFAULT 0,
distribution_count INT DEFAULT 0,
created_user_id VARCHAR(36),
attach TEXT,
remark VARCHAR(255),
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME
);
-- 卡密账户信息表
CREATE TABLE card_apple_account_info (
id VARCHAR(36) PRIMARY KEY,
account VARCHAR(64) UNIQUE NOT NULL,
password VARCHAR(64) NOT NULL,
balance DECIMAL(10,2),
balance_itunes DECIMAL(10,2),
status INT NOT NULL DEFAULT 1,
today_recharge_amount DECIMAL(10,2) DEFAULT 0,
today_recharge_count INT DEFAULT 0,
today_recharge_datetime DATETIME,
created_user_id VARCHAR(36),
created_user_role VARCHAR(36),
max_amount_limit DECIMAL(10,2) DEFAULT 4500,
max_count_limit INT DEFAULT 100,
remark VARCHAR(255),
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME
);
```
### 示例数据
```json
// 卡密充值记录示例
{
"id": 1001,
"order_no": "ORD202311070001",
"account_id": "acc-001",
"account_name": "Apple账户A",
"card_no": "1234567890123456",
"card_pass": "ABCDEF123456",
"card_amount": 100.00,
"status": 1,
"actual_amount": 100.00,
"created_at": "2023-11-07T10:00:00Z"
}
// 卡密账户信息示例
{
"id": "acc-001",
"account": "user@apple.com",
"password": "encrypted_password",
"balance": 5000.00,
"balance_itunes": 4800.00,
"status": 1,
"today_recharge_amount": 300.00,
"today_recharge_count": 3
}
```
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
## 访问模式与缓存策略
卡密数据具有特定的访问模式系统采用了相应的缓存策略来优化性能
### 访问模式
- **高频查询**通过 `order_no` `card_no` 查询单条记录是最常见的访问模式属于高频低延迟操作
- **列表查询** `account_id` `status` 查询充值记录列表用于管理后台的订单列表展示
- **聚合查询**统计特定时间段内的充值总额成功率等用于业务报表生成
### 缓存策略
- **Redis缓存**系统使用Redis缓存热点数据如活跃账户信息和最近成功的充值记录减少数据库直接访问
- **缓存键设计**采用 `card_recharge:{card_no}` `card_account:{account_id}` 的键名模式确保缓存的唯一性和可预测性
- **缓存失效**当充值记录状态更新或账户信息变更时立即失效相关缓存保证数据一致性
- **批量操作优化**对于批量查询场景采用管道pipeline技术减少网络往返次数提高吞吐量
**文档来源**
- [utility/cache/cache.go](file://utility/cache/cache.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
## 数据生命周期管理
卡密数据遵循完整的生命周期管理策略从生成到归档
### 生命周期流程
```mermaid
flowchart TD
A[卡密生成] --> B[提交充值]
B --> C{状态检查}
C --> |成功| D[核销完成]
C --> |失败| E[重试处理]
E --> C
D --> F[归档标记]
F --> G[定期归档]
G --> H[冷存储]
```
**图示来源**
- [card_apple_order.go](file://internal/model/card_apple_order.go)
### 保留策略
- **在线数据**所有未完成和最近完成的充值记录保留在主数据库中支持实时查询和操作
- **归档策略**已完成超过6个月的充值记录会被标记为归档状态从主查询路径中移除但仍可通过特定接口访问
- **软删除**采用 `deleted_at` 字段实现软删除所有删除操作都只是标记删除时间保留数据用于审计和对账
### 归档规则
- **触发条件**订单状态为"交易成功""交易失败"且最后更新时间超过180天
- **归档方式**将数据从主表移动到历史归档表并从Redis缓存中清除
- **恢复机制**提供专门的恢复接口可在必要时将归档数据恢复到在线状态
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [v_1_card_apple_account_info.go](file://internal/dao/internal/v_1_card_apple_account_info.go)
## GoFrame ORM映射与DAO实现
系统使用GoFrame ORM框架实现卡密数据模型到Go结构体的映射和数据访问
### ORM结构体映射
GoFrame通过结构体标签struct tags实现数据库字段到Go结构体的映射
```go
// V1CardAppleRechargeInfo is the golang structure for table v1card_apple_recharge_info.
type V1CardAppleRechargeInfo struct {
Id uint `json:"id" orm:"id" description:""`
OrderNo string `json:"orderNo" orm:"order_no" description:"订单号"`
CardNo string `json:"cardNo" orm:"card_no" description:"卡号"`
Status int `json:"status" orm:"status" description:"状态 0.创建 1.交易成功 2.交易中 3.交易失败"`
// ... 其他字段
CreatedAt *gtime.Time `json:"createdAt" orm:"created_at" description:"创建日期"`
}
```
**文档来源**
- [entity/v_1_card_apple_recharge_info.go](file://internal/model/entity/v_1_card_apple_recharge_info.go)
### DAO层实现
DAO层提供了对卡密数据的批量操作和状态更新功能
#### 批量操作
- **批量添加**支持从Excel模板批量导入卡密信息通过事务确保数据一致性
- **批量查询**提供分页查询接口支持按多种条件组合筛选
- **批量更新**支持批量修改卡密状态用于大规模运维操作
#### 状态更新
- **原子更新**使用数据库事务和行级锁确保状态更新的原子性
- **状态变更历史**每次状态更新都会在 `v_1_card_apple_history_info` 表中记录操作日志
- **并发控制**通过乐观锁或悲观锁机制防止并发更新导致的数据不一致
```go
// 示例:状态更新方法
func (s *service) UpdateStatus(ctx context.Context, id int, status int) error {
return dao.V1CardAppleRechargeInfo.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
// 1. 查询当前记录
record, err := dao.V1CardAppleRechargeInfo.Ctx(ctx).Where("id", id).One()
if err != nil {
return err
}
// 2. 记录历史
history := &entity.V1CardAppleHistoryInfo{
RechargeId: id,
Operation: "状态更新",
Remark: fmt.Sprintf("从 %d 更新到 %d", record["status"], status),
}
_, err = dao.V1CardAppleHistoryInfo.Ctx(ctx).Data(history).Insert()
if err != nil {
return err
}
// 3. 更新状态
_, err = dao.V1CardAppleRechargeInfo.Ctx(ctx).Where("id", id).Data("status", status).Update()
return err
})
}
```
**文档来源**
- [v_1_card_apple_recharge_info.go](file://internal/dao/internal/v_1_card_apple_recharge_info.go)
- [card_apple_order.go](file://internal/model/card_apple_order.go)
- [entity/v_1_card_apple_recharge_info.go](file://internal/model/entity/v_1_card_apple_recharge_info.go)

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