# Kami Gateway 集成

<cite>
**本文档中引用的文件**
- [client.go](file://utility/integration/kami_gateway/client.go)
- [model.go](file://utility/integration/kami_gateway/model.go)
- [utils.go](file://utility/integration/kami_gateway/utils.go)
- [config.yaml](file://manifest/config/config.yaml)
- [auth.go](file://internal/middleware/auth.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_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.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_original_jd_v1_original_jd_account_create.go](file://internal/controller/card_info_original_jd/card_info_original_jd_v1_original_jd_account_create.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)
</cite>

## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)

## 简介
本文档详细介绍了 Kami Gateway 集成模块的设计、实现和功能。该模块作为 Kami 后端系统的重要组成部分，负责与外部支付网关进行通信，处理订单提交、状态同步和回调通知等关键业务流程。系统支持多个电商平台（如京东、沃尔玛、飞猪等）的卡密兑换和订单处理，通过统一的网关接口实现与外部系统的安全、可靠交互。

## 项目结构
Kami 后端项目采用模块化设计，主要分为 API 接口层、内部控制器、数据访问对象（DAO）、业务逻辑层和服务层。`utility/integration/kami_gateway` 目录下的文件专门负责与外部 Kami Gateway 的集成，包括请求构建、签名生成和 HTTP 通信。

```mermaid
graph TD
subgraph "集成层"
A[kami_gateway/client.go] --> B[kami_gateway/model.go]
A --> C[kami_gateway/utils.go]
end
subgraph "配置"
D[manifest/config/config.yaml]
end
subgraph "认证中间件"
E[internal/middleware/auth.go]
end
subgraph "控制器"
F[internal/controller/card_info_t_mall_game/...]
G[internal/controller/card_info_walmart/...]
H[internal/controller/card_info_jd/...]
end
subgraph "服务层"
I[internal/service/card_redeem_order.go]
end
D --> A
E --> F
E --> G
E --> H
F --> I
G --> I
H --> I
```

**图示来源**
- [client.go](file://utility/integration/kami_gateway/client.go)
- [model.go](file://utility/integration/kami_gateway/model.go)
- [utils.go](file://utility/integration/kami_gateway/utils.go)
- [config.yaml](file://manifest/config/config.yaml)
- [auth.go](file://internal/middleware/auth.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_walmart_v1_submit.go](file://internal/controller/card_info_walmart/card_info_walmart_v1_submit.go)
- [card_redeem_order.go](file://internal/service/card_redeem_order.go)

## 核心组件
核心组件包括 `SubmitOrderReq` 和 `SubmitOrderResponse` 数据模型，用于定义与 Kami Gateway 通信的请求和响应结构。`SubmitOrder` 函数是主要的业务方法，负责执行 HTTP POST 请求。`GetMD5SignMF` 函数实现了基于 MD5 的签名算法，确保通信的安全性。`auth.go` 中的中间件负责处理不同来源（登录/iframe）的认证逻辑。

**组件来源**
- [client.go](file://utility/integration/kami_gateway/client.go#L16-L47)
- [model.go](file://utility/integration/kami_gateway/model.go#L9-L65)
- [utils.go](file://utility/integration/kami_gateway/utils.go#L11-L51)
- [auth.go](file://internal/middleware/auth.go#L25-L165)

## 架构概述
系统采用分层架构，前端应用通过 API 网关访问后端服务。后端服务通过 `kami_gateway` 集成模块与外部支付网关通信。认证中间件确保所有请求的合法性，控制器处理具体的业务逻辑，服务层协调数据访问和业务规则。配置文件 `config.yaml` 集中管理数据库、Redis 和第三方服务的连接信息。

```mermaid
graph LR
A[前端应用] --> B[API 网关]
B --> C[Kami 后端服务]
C --> D[kami_gateway 集成模块]
D --> E[外部支付网关]
C --> F[MySQL 数据库]
C --> G[Redis 缓存]
H[配置文件 config.yaml] --> C
I[认证中间件] --> C
```

**图示来源**
- [config.yaml](file://manifest/config/config.yaml#L1-L105)
- [auth.go](file://internal/middleware/auth.go#L25-L165)

## 详细组件分析

### Kami Gateway 客户端分析
该组件封装了与外部 Kami Gateway 的通信细节，提供了一个简洁的接口供上层业务调用。

#### 对象关系图
```mermaid
classDiagram
class SubmitOrderReq {
+int OrderPeriod
+string NotifyUrl
+string OrderPrice
+string OrderNo
+string ProductCode
+string ExValue
+string Ip
+string PayKey
+string PaySecret
+string Url
+GetUrl() string
+ToStrMap() map[string]any
+GetNotifyUrl() string
}
class SubmitOrderResponse {
+string PayKey
+string StatusCode
+string Msg
+int Code
}
class RedeemCardInfo {
+string FaceType
+string RecoveryType
+string Data
+string CardNo
+ToJson() string
}
class Client {
+SubmitOrder(ctx, input) (*SubmitOrderResponse, error)
}
class Utils {
+GetMD5SignMF(params, paySecret) string
+SortMap(m) []string
+GetMd5Lower(s) string
}
Client --> SubmitOrderReq : "使用"
Client --> SubmitOrderResponse : "返回"
Client --> Utils : "调用"
```

**图示来源**
- [client.go](file://utility/integration/kami_gateway/client.go#L16-L47)
- [model.go](file://utility/integration/kami_gateway/model.go#L9-L65)
- [utils.go](file://utility/integration/kami_gateway/utils.go#L11-L51)

#### 订单提交流程
```mermaid
sequenceDiagram
participant Controller as "控制器"
participant Client as "kami_gateway.Client"
participant Gateway as "外部支付网关"
participant Logger as "日志系统"
Controller->>Client : SubmitOrder(ctx, req)
Client->>Client : input.GetNotifyUrl()
Client->>Client : input.ToStrMap()
Client->>Client : GetMD5SignMF(params, secret)
Client->>Client : 构建 paramsStr
Client->>Gateway : POST /gateway/scan
alt 请求成功
Gateway-->>Client : 返回响应数据
Client->>Client : 解析 JSON 响应
Client-->>Controller : 返回 SubmitOrderResponse
else 请求失败
Gateway-->>Client : 连接错误
Client->>Logger : 记录错误日志
Client-->>Controller : 返回错误
end
```

**图示来源**
- [client.go](file://utility/integration/kami_gateway/client.go#L16-L47)
- [model.go](file://utility/integration/kami_gateway/model.go#L9-L65)

### 认证中间件分析
该中间件负责处理不同来源的请求认证，包括基于 Token 的登录认证和基于 AES 解密的 iframe 认证。

#### 认证流程图
```mermaid
flowchart TD
Start([请求进入]) --> CheckWhiteList["检查白名单路径"]
CheckWhiteList --> IsWhiteList{"路径在白名单?"}
IsWhiteList --> |是| Allow["放行请求"]
IsWhiteList --> |否| GetTokenFromHeader["从Header获取tokenFrom"]
GetTokenFromHeader --> CheckTokenSource{"tokenFrom是login?"}
CheckTokenSource --> |是| LoginAuth["执行loginAuth"]
CheckTokenSource --> |否| CheckIframe{"tokenFrom是iframe?"}
CheckIframe --> |是| IFrameAuth["执行iFrameAuth"]
CheckIframe --> |否| Deny["拒绝请求"]
LoginAuth --> ValidateToken["验证Token有效性"]
ValidateToken --> IsTokenValid{"Token有效?"}
IsTokenValid --> |是| RefreshToken["刷新Token"]
IsTokenValid --> |否| ReturnError["返回401"]
RefreshToken --> Allow
IFrameAuth --> DecryptToken["AES解密Token"]
DecryptToken --> IsTokenValid2{"Token有效且未过期?"}
IsTokenValid2 --> |是| Allow
IsTokenValid2 --> |否| ReturnError
Deny --> ReturnError
ReturnError --> End([返回响应])
Allow --> End
```

**图示来源**
- [auth.go](file://internal/middleware/auth.go#L25-L165)

## 依赖分析
系统依赖于多个外部库和内部模块。主要外部依赖包括 `gogf/gf/v2` 框架、`lancet/v2` 工具库和 OpenTelemetry 用于分布式追踪。内部依赖包括 `service` 模块用于业务逻辑，`token` 模块用于认证，`verify` 模块用于加密解密。`config.yaml` 文件是系统配置的核心，被多个模块引用。

```mermaid
graph TD
A[kami_gateway] --> B[gogf/gf/v2/net/gclient]
A --> C[github.com/duke-git/lancet/v2/convertor]
A --> D[go.opentelemetry.io/otel]
A --> E[internal/service]
A --> F[utility/token]
A --> G[utility/verify]
H[config.yaml] --> A
H --> I[database]
H --> J[redis]
H --> K[casbin]
```

**图示来源**
- [client.go](file://utility/integration/kami_gateway/client.go#L3-L14)
- [auth.go](file://internal/middleware/auth.go#L3-L23)
- [config.yaml](file://manifest/config/config.yaml#L27-L105)

## 性能考虑
系统在性能方面进行了多项优化。使用 Redis 缓存频繁访问的数据，如用户 Token 和账户信息，减少数据库查询。`gtrace` 集成提供了详细的性能追踪信息，有助于定位瓶颈。`gclient` 的 HTTP 客户端支持连接池和超时控制，确保外部通信的稳定性。异步处理机制（如 `TriggerValidateAndConsume`）避免了长时间运行的操作阻塞主线程。

## 故障排除指南
常见问题包括签名验证失败、Token 过期和外部网关连接超时。对于签名失败，应检查 `PaySecret` 是否正确以及参数排序逻辑。Token 问题通常源于过期或格式错误，可通过检查 `tokenFrom` 头和解密逻辑来诊断。连接超时问题需要检查网络配置和外部网关的可用性。详细的错误日志记录在 `resource/log/server` 目录下，是排查问题的重要依据。

**故障排除来源**
- [client.go](file://utility/integration/kami_gateway/client.go#L33-L34)
- [auth.go](file://internal/middleware/auth.go#L74-L85)
- [config.yaml](file://manifest/config/config.yaml#L6-L13)

## 结论
Kami Gateway 集成模块设计良好，实现了与外部支付系统的安全、可靠通信。通过清晰的分层架构和模块化设计，系统具有良好的可维护性和扩展性。建议未来增加更详细的监控指标和更完善的错误恢复机制，以进一步提升系统的稳定性和可观测性。