支付系统架构设计

系列导读:本篇将深入讲解支付系统的架构设计与核心实现。


文章目录

    • 目录
    • 一、支付系统概述
      • [1.1 支付流程](#1.1 支付流程)
      • [1.2 支付渠道](#1.2 支付渠道)
    • 二、架构设计
      • [2.1 系统架构](#2.1 系统架构)
      • [2.2 数据库设计](#2.2 数据库设计)
    • 三、核心功能实现
      • [3.1 统一支付接口](#3.1 统一支付接口)
      • [3.2 支付回调处理](#3.2 支付回调处理)
      • [3.3 幂等性处理](#3.3 幂等性处理)
    • 四、安全设计
      • [4.1 签名验证](#4.1 签名验证)
      • [4.2 敏感信息加密](#4.2 敏感信息加密)
    • 总结

目录


一、支付系统概述

1.1 支付流程

复制代码
┌─────────────────────────────────────────────────────────────┐
│                    支付流程                                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  用户下单 ──► 创建支付单 ──► 调用支付渠道 ──► 用户支付     │
│                                              │              │
│                                              ▼              │
│  订单完成 ◄── 更新订单状态 ◄── 支付回调 ◄── 支付成功       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 支付渠道

渠道 说明
支付宝 国内主流
微信支付 国内主流
银联 银行卡支付
PayPal 国际支付

二、架构设计

2.1 系统架构

复制代码
┌─────────────────────────────────────────────────────────────┐
│                    支付系统架构                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                    支付网关                         │   │
│  │              统一支付入口、路由                      │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                                 │
│         ┌─────────────────┼─────────────────┐              │
│         ▼                 ▼                 ▼              │
│  ┌─────────────┐   ┌─────────────┐   ┌─────────────┐      │
│  │ 支付宝适配器 │   │ 微信适配器  │   │ 银联适配器  │      │
│  └─────────────┘   └─────────────┘   └─────────────┘      │
│                           │                                 │
│                           ▼                                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                    核心服务                         │   │
│  │     支付单管理 │ 对账 │ 退款 │ 清算                 │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2.2 数据库设计

sql 复制代码
-- 支付单表
CREATE TABLE payment (
    id BIGINT PRIMARY KEY,
    payment_no VARCHAR(50) NOT NULL,
    order_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    channel VARCHAR(20) NOT NULL,
    status INT DEFAULT 0,
    create_time DATETIME,
    pay_time DATETIME
);

-- 支付流水表
CREATE TABLE payment_log (
    id BIGINT PRIMARY KEY,
    payment_id BIGINT NOT NULL,
    action VARCHAR(50) NOT NULL,
    amount DECIMAL(10,2),
    status INT,
    create_time DATETIME
);

-- 退款表
CREATE TABLE refund (
    id BIGINT PRIMARY KEY,
    refund_no VARCHAR(50) NOT NULL,
    payment_id BIGINT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    reason VARCHAR(200),
    status INT DEFAULT 0,
    create_time DATETIME
);

三、核心功能实现

3.1 统一支付接口

java 复制代码
// 支付策略接口
public interface PaymentStrategy {
    PaymentResult pay(PaymentRequest request);
    RefundResult refund(RefundRequest request);
    PaymentResult query(String paymentNo);
}

// 支付宝实现
@Service
public class AlipayStrategy implements PaymentStrategy {
    
    @Override
    public PaymentResult pay(PaymentRequest request) {
        AlipayClient client = new DefaultAlipayClient(...);
        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        payRequest.setReturnUrl(returnUrl);
        payRequest.setNotifyUrl(notifyUrl);
        
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", request.getPaymentNo());
        bizContent.put("total_amount", request.getAmount());
        bizContent.put("subject", request.getSubject());
        payRequest.setBizContent(bizContent.toString());
        
        String form = client.pageExecute(payRequest).getBody();
        return new PaymentResult(form);
    }
}

// 支付工厂
@Component
public class PaymentFactory {
    
    @Autowired
    private Map<String, PaymentStrategy> strategies;
    
    public PaymentStrategy getStrategy(String channel) {
        return strategies.get(channel + "Strategy");
    }
}

3.2 支付回调处理

java 复制代码
@RestController
public class PaymentCallbackController {
    
    @Autowired
    private PaymentService paymentService;
    
    @PostMapping("/callback/alipay")
    public String alipayCallback(HttpServletRequest request) {
        // 1. 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(...);
        if (!signVerified) {
            return "fail";
        }
        
        // 2. 获取参数
        String paymentNo = request.getParameter("out_trade_no");
        String tradeNo = request.getParameter("trade_no");
        String tradeStatus = request.getParameter("trade_status");
        
        // 3. 处理支付结果
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            paymentService.handlePaymentSuccess(paymentNo, tradeNo);
        }
        
        return "success";
    }
}

3.3 幂等性处理

java 复制代码
@Service
public class PaymentService {
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    public void handlePaymentSuccess(String paymentNo, String tradeNo) {
        // 幂等性检查
        String key = "payment:callback:" + paymentNo;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "1", 1, TimeUnit.HOURS);
        if (!Boolean.TRUE.equals(success)) {
            log.info("支付回调已处理: {}", paymentNo);
            return;
        }
        
        // 更新支付状态
        Payment payment = paymentMapper.selectByPaymentNo(paymentNo);
        if (payment.getStatus() == PaymentStatus.SUCCESS) {
            return;
        }
        
        payment.setStatus(PaymentStatus.SUCCESS);
        payment.setTradeNo(tradeNo);
        payment.setPayTime(new Date());
        paymentMapper.updateById(payment);
        
        // 发送消息通知订单服务
        mqProducer.send("payment.success", payment);
    }
}

四、安全设计

4.1 签名验证

java 复制代码
// 签名工具
public class SignUtil {
    
    public static String sign(Map<String, String> params, String key) {
        String signStr = params.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .map(e -> e.getKey() + "=" + e.getValue())
            .collect(Collectors.joining("&"));
        
        return DigestUtils.md5Hex(signStr + "&key=" + key);
    }
    
    public static boolean verify(Map<String, String> params, String sign, String key) {
        String calculatedSign = sign(params, key);
        return calculatedSign.equals(sign);
    }
}

4.2 敏感信息加密

java 复制代码
// 敏感信息加密存储
@Encrypt
private String bankCardNo;

@Encrypt
private String idCard;

总结

支付系统概述 :支付流程、支付渠道

架构设计 :系统架构、数据库设计

核心功能实现 :统一支付接口、回调处理、幂等性

安全设计:签名验证、敏感信息加密

下篇预告日志平台架构设计


作者 :刘~浪地球
系列 :技术选型与实战(四)
更新时间:2026-04-24

相关推荐
Hvitur4 小时前
软考架构师【第十六章】嵌入式系统架构设计理论与实践
系统架构
慧一居士4 小时前
Spring AI MCP服务如何选择使用 WebMVC还是WebFlux
人工智能·系统架构
池佳齐6 小时前
软考高级系统架构设计师备考(十八):数据库系统—事务管理与并发控制
数据库·oracle·系统架构
2603_954708318 小时前
微电网架构优化设计:基于经济性与可靠性的多目标权衡
人工智能·物联网·架构·系统架构·能源
JGDT_8 小时前
直播回顾2|底层逻辑重构:AI驱动下的财务工作五大范式转移
大数据·人工智能·系统架构·系统安全·软件工程
半夏映浮光11 小时前
系统架构设计师知识点61-80
系统架构
Bruce_Liuxiaowei13 小时前
县级融媒体中心上洋播控系统架构解析——TeamViewer 不只是远程工具
系统架构·媒体·teamviewer·上洋
小短腿的代码世界21 小时前
Qt Concurrent 深度解析:并发编程范式与源码级实现原理
qt·系统架构·lucene
大迪deblog1 天前
系统架构设计-软件工程-软件开发模型、CMMI、逆向工程
系统架构·软件工程·cmmi