
簡介
真正的支付平台總是需要整合多個PSP(支付服務提供者)來優化成功率、成本和覆蓋範圍。本文指導多 PSP 與智慧路由整合的抽象層設計。
1. PSP 抽象層
1.1 適配器模式
┌────────────────────────────────────────────────────┐
│ PAYMENT SERVICE │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ PSP Interface (Port) │ │
│ │ authorize() / capture() / refund() / void() │ │
│ └──────────────────┬───────────────────────────┘ │
│ │ │
│ ┌──────────────┼──────────────┐ │
│ │ │ │ │
│ ┌───▼────┐ ┌─────▼────┐ ┌─────▼────┐ │
│ │ VNPay │ │ MoMo │ │ Stripe │ ... │
│ │Adapter │ │ Adapter │ │ Adapter │ │
│ └───┬────┘ └─────┬────┘ └─────┬────┘ │
└──────┼──────────────┼─────────────┼────────────────┘
│ │ │
┌───▼────┐ ┌─────▼────┐ ┌────▼─────┐
│ VNPay │ │ MoMo │ │ Stripe │
│ API │ │ API │ │ API │
└────────┘ └──────────┘ └──────────┘
1.2 PSP 介面
public interface PaymentServiceProvider {
String getId();
Set<PaymentMethod> supportedMethods();
Set<Currency> supportedCurrencies();
AuthResult authorize(AuthRequest request);
CaptureResult capture(CaptureRequest request);
RefundResult refund(RefundRequest request);
VoidResult voidPayment(VoidRequest request);
PaymentStatus queryStatus(String pspReference);
}
1.3 VNPay 適配器
@Component
public class VNPayAdapter implements PaymentServiceProvider {
@Override
public String getId() { return "vnpay"; }
@Override
public Set<PaymentMethod> supportedMethods() {
return Set.of(
PaymentMethod.ATM_CARD,
PaymentMethod.CREDIT_CARD,
PaymentMethod.QR_CODE,
PaymentMethod.BANK_TRANSFER
);
}
@Override
public AuthResult authorize(AuthRequest request) {
// Build VNPay-specific parameters
var params = new TreeMap<String, String>();
params.put("vnp_Version", "2.1.0");
params.put("vnp_Command", "pay");
params.put("vnp_TmnCode", config.getTmnCode());
params.put("vnp_Amount", String.valueOf(
request.getAmount().multiply(100).longValue()));
params.put("vnp_CurrCode", "VND");
params.put("vnp_TxnRef", request.getOrderId());
params.put("vnp_OrderInfo", request.getDescription());
params.put("vnp_ReturnUrl", config.getReturnUrl());
// Sign with HMAC-SHA512
String signature = HmacUtils.hmacSha512(
config.getHashSecret(), buildQueryString(params));
params.put("vnp_SecureHash", signature);
// Return redirect URL for customer
String paymentUrl = config.getPayUrl() + "?" + buildQueryString(params);
return AuthResult.redirect(paymentUrl);
}
}
2. 智慧路由
2.1 路由引擎
@Service
public class PSPRouter {
private final List<RoutingRule> rules;
private final PSPHealthMonitor healthMonitor;
public PaymentServiceProvider selectPSP(PaymentRequest request) {
// 1. Filter by capability
var candidates = pspRegistry.getAll().stream()
.filter(psp -> psp.supportedMethods().contains(request.getMethod()))
.filter(psp -> psp.supportedCurrencies().contains(request.getCurrency()))
.filter(psp -> healthMonitor.isHealthy(psp.getId()))
.toList();
// 2. Apply routing rules
for (var rule : rules) {
var result = rule.evaluate(request, candidates);
if (result.isPresent()) return result.get();
}
// 3. Default: cost-optimized selection
return candidates.stream()
.min(Comparator.comparing(psp -> getFeeRate(psp, request)))
.orElseThrow(() -> new NoPSPAvailableException());
}
}
2.2 路由策略
| 戰略 | 邏輯 | 使用案例 |
|---|---|---|
| 成本優化 | 最低費用 PSP | 預設 |
| 成功率 | 成功率最高的PSP | 大額交易 |
| 延遲最佳化 | 最快的 PSP | 即時付款 |
| 地理 | 最接近客户的PSP | 跨境 |
| 負載平衡 | 循環賽/加權 | 流量分佈 |
| A/B 測試 | 隨機分割 | 測試新 PSP |
2.3 故障转移模式
Primary PSP (VNPay)
│
├── Success → Done
│
├── Timeout/5xx → Retry once
│ │
│ ├── Success → Done
│ │
│ └── Fail → Fallback PSP (Stripe)
│ │
│ ├── Success → Done
│ │
│ └── Fail → Return error to customer
│
└── Terminal error (declined) → Return error (no fallback)
3. PSP 健康監測
@Component
public class PSPHealthMonitor {
// Track success rate per PSP with sliding window
private final Map<String, SlidingWindowCounter> successRates;
@Scheduled(fixedRate = 60000) // Every minute
public void checkHealth() {
for (var entry : successRates.entrySet()) {
var pspId = entry.getKey();
var counter = entry.getValue();
double rate = counter.getSuccessRate();
if (rate < 0.5) { // < 50% success rate
circuitBreaker.open(pspId);
alertService.send("PSP " + pspId + " degraded: " + rate);
}
}
}
public boolean isHealthy(String pspId) {
return !circuitBreaker.isOpen(pspId);
}
}
4. Webhook 處理
4.1 接收 PSP 回呼
@RestController
@RequestMapping("/webhooks")
public class WebhookController {
@PostMapping("/vnpay")
public ResponseEntity<String> handleVNPayCallback(
@RequestParam Map<String, String> params) {
// 1. Verify signature
if (!vnpayAdapter.verifySignature(params)) {
return ResponseEntity.badRequest().body("Invalid signature");
}
// 2. Process callback
var paymentId = params.get("vnp_TxnRef");
var responseCode = params.get("vnp_ResponseCode");
webhookProcessor.process(WebhookEvent.builder()
.pspId("vnpay")
.paymentId(paymentId)
.status(mapStatus(responseCode))
.rawPayload(params)
.build());
return ResponseEntity.ok("OK");
}
@PostMapping("/stripe")
public ResponseEntity<Void> handleStripeWebhook(
@RequestBody String payload,
@RequestHeader("Stripe-Signature") String signature) {
// Verify Stripe webhook signature
var event = stripeAdapter.verifyAndParse(payload, signature);
webhookProcessor.process(event);
return ResponseEntity.ok().build();
}
}
總結
多 PSP 整合需要:
- 适配器模式抽象出 PSP 特定的 API
- 智慧路由最佳化成本、成功率、延遲
- PSP 崩溃时自动进行 故障转移
- 附斷路器的健康監測
- 每個帶有簽名驗證的 PSP 的 Webhook 處理
下一篇文章:對帳與結算引擎-控制系統與自動結算流程。