1. 简历要点
对微信、支付宝和银行等不同支付通道进行统一接口抽象,通过策略模式与工厂模式隔离通道差异,降低新增支付通道对核心交易流程的影响。
这项工作的关键不是定义一个只有 pay() 方法的接口,而是明确哪些能力属于统一交易流程,哪些差异必须留在渠道适配层。
2. 开源实现观察
Jeepay 的 IPaymentService 抽象了接口编码、支付方式支持判断、前置检查、自定义订单号和支付调用。其统一下单控制器根据支付接口编码取得 Spring Bean,再执行 preCheck() 和 pay()。这是“策略接口 + Bean 注册表”的直接参考:
官方 SDK 用于承接渠道协议细节:
3. 分层边界
1
2
3
4
5
6
7
8
9
10
11
12
13
| PayApplicationService
├─ 校验业务订单和幂等
├─ 创建支付尝试
├─ 调用 PaymentChannelRegistry
├─ 根据标准结果推进订单状态
└─ 写流水和领域事件
PaymentChannel
├─ 参数转换
├─ SDK/HTTP 调用
├─ 渠道错误码映射
├─ 回调验签与解密
└─ 渠道响应转换为标准结果
|
核心交易服务不应感知微信的 prepay_id、支付宝的 trade_no 或银行接口的报文域。适配器也不应直接修改订单表,否则状态规则和事务边界会散落到每个渠道。
4. 领域模型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| public enum ChannelCode {
WECHAT, ALIPAY, BANK
}
public enum PaymentScene {
APP, H5, MINI_PROGRAM, QR_CODE, BANK_TRANSFER
}
public record PayCommand(
String payOrderNo,
String merchantNo,
long amountFen,
String currency,
PaymentScene scene,
String clientIp,
String notifyUrl,
Map<String, String> extension) {
}
public enum ChannelPayState {
ACCEPTED, SUCCESS, FAILED, UNKNOWN
}
public record ChannelPayResult(
ChannelPayState state,
String channelOrderNo,
String payPayload,
String channelCode,
String channelMessage,
boolean needQuery) {
}
|
金额使用最小货币单位的整数,避免 double 精度问题。扩展参数只承载确实无法标准化的场景字段,不能把整个请求都塞入 Map,否则统一接口会退化成无约束透传。
5. 策略接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public interface PaymentChannel {
ChannelCode channelCode();
boolean supports(PaymentScene scene);
ChannelPayResult pay(PayCommand command, ChannelMerchantConfig config);
ChannelQueryResult query(ChannelQueryCommand command, ChannelMerchantConfig config);
ChannelCloseResult close(ChannelCloseCommand command, ChannelMerchantConfig config);
ChannelRefundResult refund(ChannelRefundCommand command, ChannelMerchantConfig config);
VerifiedNotification verifyNotification(
ChannelNotification notification,
ChannelMerchantConfig config);
}
|
接口设计要点:
verifyNotification() 必须由渠道实现,因为签名算法、证书、解密和应答格式不同。query() 是支付系统的必备能力,用于同步超时、未知结果和回调丢失后的补偿。close() 与本地关闭要分开。渠道关闭失败时不能直接假设支付未成功。refund() 应返回“受理中、成功、失败、未知”等标准状态,不能把 HTTP 200 等同于退款成功。
6. 注册工厂
相比在工厂中编写不断增长的 switch,可直接收集 Spring 策略 Bean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| @Component
public class PaymentChannelRegistry {
private final Map<ChannelCode, PaymentChannel> channels;
public PaymentChannelRegistry(List<PaymentChannel> channelList) {
this.channels = channelList.stream()
.collect(Collectors.toUnmodifiableMap(
PaymentChannel::channelCode,
Function.identity(),
(left, right) -> {
throw new IllegalStateException(
"Duplicate payment channel: " + left.channelCode());
}));
}
public PaymentChannel require(ChannelCode channelCode, PaymentScene scene) {
PaymentChannel channel = Optional.ofNullable(channels.get(channelCode))
.orElseThrow(() -> new UnsupportedChannelException(channelCode));
if (!channel.supports(scene)) {
throw new UnsupportedPaymentSceneException(channelCode, scene);
}
return channel;
}
}
|
工厂负责“定位策略”,路由服务负责“选择哪个通道”。二者不要混为一体:
PaymentChannelRegistry:按明确通道编码取实现。ChannelRouteService:根据商户配置、场景、限额、成本、健康度和灰度规则选择通道。
7. 渠道路由
1
2
3
4
5
6
7
8
9
10
| public record ChannelRouteContext(
String merchantNo,
PaymentScene scene,
long amountFen,
String currency) {
}
public interface ChannelRouteService {
ChannelRouteDecision route(ChannelRouteContext context);
}
|
推荐先做确定性规则,再做动态权重:
- 过滤未启用、证书过期、超出单笔限额和不支持当前场景的配置。
- 按商户显式优先级排序。
- 排除熔断中的通道。
- 根据成本或成功率做加权选择。
- 将最终路由决策快照写入
pay_attempt,后续查询和退款不能重新随机路由。
8. 核心交易编排
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| @Transactional
public PayAcceptance accept(PayRequest request) {
PayOrder order = payOrderService.requirePayable(request.payOrderNo());
PayAttempt attempt = payAttemptService.createIfAbsent(order, request.requestNo());
ChannelRouteDecision route = channelRouteService.route(
new ChannelRouteContext(
order.getMerchantNo(),
request.scene(),
order.getAmountFen(),
order.getCurrency()));
attempt.bindChannel(route.channelCode(), route.configId());
payAttemptRepository.save(attempt);
return new PayAcceptance(attempt.getAttemptNo(), route.channelCode());
}
public ChannelPayResult invokeChannel(String attemptNo) {
PayAttempt attempt = payAttemptService.requireAccepted(attemptNo);
PaymentChannel channel = channelRegistry.require(
attempt.getChannelCode(), attempt.getScene());
ChannelMerchantConfig config =
channelConfigService.require(attempt.getChannelConfigId());
ChannelPayResult result = channel.pay(toCommand(attempt), config);
paymentResultService.apply(attemptNo, result);
return result;
}
|
外部 HTTP 调用不应长时间占用数据库事务。常见做法是:
- 短事务创建支付尝试并确定路由。
- 事务提交后调用渠道。
- 再以短事务落地响应并推进状态。
- 调用超时或进程崩溃时,由查单任务恢复。
9. 回调处理
回调入口只负责协议接入,业务处理统一下沉:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| public ChannelAck handle(
ChannelCode channelCode,
ChannelNotification notification) {
ChannelMerchantConfig config =
channelConfigService.resolve(channelCode, notification);
PaymentChannel channel =
channelRegistry.require(channelCode, notification.scene());
VerifiedNotification verified =
channel.verifyNotification(notification, config);
notificationService.applyIdempotently(verified);
return channel.successAck();
}
|
处理顺序:
- 读取原始请求体,避免 JSON 重新序列化导致验签内容变化。
- 根据商户号或证书序列号定位配置。
- 验签、时间戳和随机串校验,必要时解密。
- 校验本地订单、金额、币种、商户和渠道订单号。
- 以渠道通知 ID 或“渠道 + 渠道订单号 + 通知类型”做幂等。
- 条件更新状态并记录流水。
- 成功提交后返回渠道成功应答。
10. 错误码标准化
渠道错误要同时保留两个层次:
1
2
3
4
| standard_error_code = CHANNEL_TIMEOUT
standard_error_message = 支付通道响应超时
channel_error_code = SYSTEMERROR
channel_error_message = 原始渠道错误说明
|
标准错误用于核心流程决策,原始错误用于排查。错误分类建议至少包括:
- 参数或配置错误:不重试。
- 业务拒绝:不重试,直接失败。
- 限流或系统繁忙:退避重试或换通道。
- 网络超时:状态未知,先查单,不能立即发起第二次扣款。
- 验签失败:安全告警,不进入普通重试。
11. 新增通道流程
新增银行通道时应只需要:
- 实现
PaymentChannel。 - 定义并校验该通道配置。
- 增加错误码映射和回调协议适配。
- 配置通道路由规则。
- 完成契约测试、沙箱测试和故障测试。
核心订单状态机、幂等、流水和事件发布逻辑无需修改。这才是“降低新增通道对核心交易流程影响”的可验证含义。
12. 测试重点
- 所有渠道实现通过同一套接口契约测试。
- 重复支付请求只产生一个有效支付尝试。
- 渠道同步超时后不会立即重复扣款。
- 回调重复、乱序和并发到达时状态正确。
- 金额或商户不一致时拒绝推进状态。
- 配置热更新期间,进行中的支付仍使用创建尝试时的配置快照或版本。
- 渠道 SDK 抛出未知异常时转换为标准“未知”而不是错误标记为失败。
13. 面试追问
为什么既用策略又用工厂?
策略封装各通道行为,工厂或注册表负责按通道编码定位策略,路由服务负责业务选择。
为什么不在支付成功回调里直接写所有下游表?
回调应快速、可重试。核心状态和流水在本地事务完成,下游通过可靠事件异步处理。
同步返回成功是否代表支付成功?
只有渠道明确返回终态且通过校验时才能推进成功;多数预下单接口只代表受理成功。
如何避免重复扣款?
入口业务幂等、支付尝试唯一约束、状态 CAS、未知结果优先查单,以及渠道侧请求号复用共同保证。