
Cổng thanh toán, webhook, idempotency, hoàn tiền, đối soátPayment gateways, webhooks, idempotency, refunds, reconciliation
Flash sale lúc 20 giờThe 8 p.m. flash sale.Một sàn thương mại điện tử xử lý 300.000 giao dịch mỗi ngày qua VNPay, MoMo và Stripe, đỉnh 150 giao dịch mỗi giây lúc flash sale. Mỗi giao dịch là tiền thật đã rời tài khoản khách.A marketplace processes 300,000 payments a day through VNPay, MoMo and Stripe, peaking at 150 per second during flash sales. Every payment is real money leaving a customer's account.
Hãy theo đơn 8812 trị giá 450.000 đ được trả bằng MoMo lúc 20 giờ: Payment Service ghi giao dịch trước, gọi cổng qua adapter rồi chờ webhook thay vì tin trang redirect. Webhook phải qua kiểm chữ ký và khử trùng, rồi cập nhật trạng thái cùng outbox trong một transaction, còn job đối soát hỏi lại cổng cho mọi giao dịch PENDING quá lâu. Chạy luồng thành công trước, rồi thử “Mất webhook” và “Webhook trùng” để thấy hệ thống tự sửa mà không trừ tiền khách hai lần.Follow order 8812, worth 450,000 VND, paid with MoMo at 8 p.m.: the Payment Service records the payment first, calls the gateway through an adapter and waits for a webhook instead of trusting the redirect page. The webhook must pass signature checks and deduplication, then updates the status together with an outbox row in one transaction, while a reconciliation job re-asks the gateway about every payment stuck in PENDING. Play the success flow first, then try “Webhook lost” and “Duplicate webhook” to see the system correct itself without charging anyone twice.
1Khách bấm thanh toán đơn 8812 bằng MoMo. Client gửi Idempotency-Key sinh một lần cho lượt checkout này, nên bấm lại hay app retry đều trỏ về cùng một giao dịch.The customer pays order 8812 with MoMo. The client sends an Idempotency-Key generated once for this checkout, so a second click or an app retry points to the same payment.
Client gửi Idempotency-Key cố định cho mỗi lần thanh toán đơn. Bảng payment có unique(idempotency_key); request lặp trả lại payment cũ thay vì tạo giao dịch mới ở cổng. Khi cổng hỗ trợ (Stripe), truyền luôn key sang cổng.The client sends a fixed Idempotency-Key per checkout. The payment table has unique(idempotency_key); a repeated request returns the existing payment instead of creating a new charge. When the gateway supports it (Stripe), pass the key through as well.
Interface PaymentGateway chung (createIntent, verifySignature, parse, queryStatus, refund). VNPay, MoMo, Stripe là các adapter; Strategy chọn adapter theo provider của payment.One PaymentGateway interface (createIntent, verifySignature, parse, queryStatus, refund). VNPay, MoMo and Stripe are adapters; a Strategy picks the adapter from the payment's provider.
Xác minh HMAC trên raw body trước khi parse. Lưu (provider, event_id) đã xử lý để bỏ qua bản trùng. State machine chỉ cho chuyển hợp lệ, nên FAILED tới sau SUCCEEDED bị bỏ qua.Verify the HMAC over the raw body before parsing. Store processed (provider, event_id) pairs to drop duplicates. The state machine only allows valid transitions, so a FAILED arriving after SUCCEEDED is ignored.
Job polling hỏi queryStatus cho payment PENDING quá 15 phút, giãn cách tăng dần. Đối soát cuối ngày so từng dòng với báo cáo quyết toán của cổng.A polling job calls queryStatus for payments PENDING over 15 minutes, with growing intervals. The nightly reconciliation matches every row against the gateway settlement report.
Ghi trạng thái payment và outbox payment.succeeded trong cùng transaction; relay đẩy sang Kafka sau commit. Order và Inventory chạy như một saga: thất bại thì nhả hàng đang giữ, hoặc hoàn tiền nếu không còn hàng.Write the payment status and a payment.succeeded outbox row in one transaction; a relay publishes after commit. Order and Inventory run as a saga: on failure release the reservation, or refund when stock is gone.
Tiền lưu bằng số nguyên đơn vị nhỏ nhất (VND không có xu, USD tính cent) hoặc BigDecimal, không dùng double. Tổng các refund SUCCEEDED không vượt số đã thu; kiểm tra dưới khoá dòng payment.Store money as integer minor units (VND has no subunit, USD uses cents) or BigDecimal, never double. The sum of SUCCEEDED refunds cannot exceed the captured amount; check it under a lock on the payment row.
Timeout ngắn khi gọi cổng, circuit breaker theo từng cổng. Breaker mở thì ẩn phương thức đó trên trang thanh toán thay vì để khách chờ.Short timeouts on gateway calls and a circuit breaker per gateway. When a breaker opens, hide that method on the checkout page instead of making customers wait.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
payment | id, order_id, provider, gateway_ref, amount_minor, currency, status, idempotency_key, version, created_at, updated_at | unique(idempotency_key), unique(provider, gateway_ref); CREATED → PENDING → SUCCEEDED · FAILED → REFUNDEDunique(idempotency_key), unique(provider, gateway_ref); CREATED → PENDING → SUCCEEDED · FAILED → REFUNDED |
refund | id, payment_id, amount_minor, status, idempotency_key, gateway_ref, reason, created_at | Nhiều refund cho một payment; sum(amount_minor) ≤ payment.amount_minorSeveral refunds per payment; sum(amount_minor) ≤ payment.amount_minor |
payment_event | id, payment_id, from_status, to_status, source, raw_payload, created_at | Lịch sử chuyển trạng thái; source = api · webhook · reconciliationStatus history; source = api · webhook · reconciliation |
processed_event | provider, event_id, received_at | PK(provider, event_id) để khử webhook trùngPK(provider, event_id) to drop duplicate webhooks |
reconciliation_item | run_date, provider, gateway_ref, gateway_amount, local_amount, result | result = MATCHED · MISSING_LOCAL · MISSING_GATEWAY · AMOUNT_MISMATCHresult = MATCHED · MISSING_LOCAL · MISSING_GATEWAY · AMOUNT_MISMATCH |
outbox | id, topic, key, payload, published_at | payment.succeeded, payment.failed, refund.succeededpayment.succeeded, payment.failed, refund.succeeded |
WebhookController (Java) là hộp Webhook Endpoint ở sơ đồ: xác minh chữ ký qua PaymentGateway của từng cổng, khử trùng bằng processed_event, đi qua state machine rồi ghi outbox vào Payments DB. Reconciler (Go) là hộp Reconciliation Job: mỗi 5 phút hỏi lại cổng cho các payment PENDING quá lâu và sửa trạng thái bằng UPDATE có điều kiện.WebhookController (Java) is the Webhook Endpoint box in the diagram: it verifies the signature through each gateway's PaymentGateway, deduplicates with processed_event, goes through the state machine and writes the outbox into Payments DB. Reconciler (Go) is the Reconciliation Job box: every 5 minutes it asks the gateway about stale PENDING payments and fixes them with a conditional UPDATE.
package com.example.payment;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class WebhookController {
private final Map<String, PaymentGateway> gateways; // "vnpay", "momo", "stripe"
private final PaymentRepository payments;
private final ProcessedEventRepository processed;
private final OutboxRepository outbox;
@PostMapping("/webhooks/{provider}")
@Transactional
public ResponseEntity<Void> handle(@PathVariable String provider,
@RequestHeader HttpHeaders headers,
@RequestBody String rawBody) {
PaymentGateway gw = gateways.get(provider);
if (gw == null || !gw.verifySignature(headers, rawBody)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
GatewayEvent ev = gw.parse(rawBody);
if (!processed.insertIfAbsent(provider, ev.eventId())) {
return ResponseEntity.ok().build(); // duplicate delivery
}
Payment p = payments.lockByGatewayRef(provider, ev.reference()); // FOR UPDATE
if (p.amountMinor() != ev.amountMinor()) {
p.flagForReview(ev); // never auto-succeed
return ResponseEntity.ok().build();
}
if (!p.canMoveTo(ev.status())) {
return ResponseEntity.ok().build(); // stale or out of order
}
p.moveTo(ev.status(), "webhook"); // PENDING -> SUCCEEDED
if (p.status() == PaymentStatus.SUCCEEDED) {
outbox.save(OutboxEvent.of("payment.succeeded", p.orderId(), p));
}
return ResponseEntity.ok().build();
}
}package main
import (
"context"
"database/sql"
"log/slog"
"time"
)
type Reconciler struct {
db *sql.DB
gateways map[string]Gateway // "vnpay", "momo", "stripe"
payments PaymentStore
outbox Outbox
}
// Run sweeps PENDING payments older than the cutoff. It runs every 5 minutes
// as the polling fallback; the nightly report job reuses apply().
func (r *Reconciler) Run(ctx context.Context, olderThan time.Duration) error {
stale, err := r.payments.FindPending(ctx, time.Now().Add(-olderThan))
if err != nil {
return err
}
for _, p := range stale {
remote, err := r.gateways[p.Provider].QueryStatus(ctx, p.GatewayRef)
if err != nil {
slog.Warn("query failed, next run retries", "id", p.ID, "err", err)
continue
}
if remote.AmountMinor != p.AmountMinor || remote.Currency != p.Currency {
r.payments.FlagMismatch(ctx, p.ID, remote) // a person decides
continue
}
if err := r.apply(ctx, p, remote.Status); err != nil {
return err
}
}
return nil
}
func (r *Reconciler) apply(ctx context.Context, p Payment, s Status) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
`UPDATE payment SET status = $1, updated_at = now()
WHERE id = $2 AND status = 'PENDING'`, s, p.ID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return nil // the webhook got there first
}
if s == StatusSucceeded {
if err := r.outbox.Add(ctx, tx, "payment.succeeded", p.OrderID); err != nil {
return err
}
}
return tx.Commit()
}| WebhookWebhook | Polling / đối soátPolling / reconciliation | |
|---|---|---|
| Độ trễLatency | Vài giây sau khi khách trảSeconds after the customer pays | Theo chu kỳ job, 5 phút tới 1 ngàyAs often as the job runs, 5 minutes to a day |
| Độ tin cậyReliability | Có thể mất, trùng, sai thứ tự, bị giả mạoCan be lost, duplicated, out of order or forged | Nguồn sự thật từ API và báo cáo của cổngThe gateway's API and report are the source of truth |
| Chi phíCost | Rẻ, cổng gọi mìnhCheap, the gateway calls you | Tốn quota API, phải giãn cáchUses API quota, needs spacing |
| Dùng khiUse it | Đường chính cho mọi giao dịchAs the main path for every payment | Lưới an toàn cho PENDING lâu và đối soát cuối ngàyAs the safety net for stale PENDING and the nightly reconciliation |
URL return chứa resultCode=0 có thể bị khách sửa tay hoặc không bao giờ tới khi khách tắt tab. Trang redirect chỉ hiện "đang xác nhận" và đọc trạng thái từ DB; chỉ webhook đã kiểm HMAC hoặc queryStatus của cổng mới được chuyển payment sang SUCCEEDED.A return URL carrying resultCode=0 can be edited by hand, or never arrive when the customer closes the tab. The redirect page only shows "confirming" and reads status from the DB; only an HMAC-verified webhook or the gateway's queryStatus may move a payment to SUCCEEDED.
Framework parse rồi serialize lại body sẽ đổi thứ tự trường hoặc khoảng trắng, chữ ký không bao giờ khớp và đội bắt đầu tắt kiểm tra cho nhanh. Đọc raw bytes, so chữ ký bằng hàm so sánh thời gian hằng (MessageDigest.isEqual, hmac.Equal), từ chối timestamp lệch quá 5 phút và theo dõi tỉ lệ signature_invalid.A framework that parses and re-serializes the body changes field order or whitespace, the signature never matches, and teams start disabling the check. Read the raw bytes, compare with a constant-time function (MessageDigest.isEqual, hmac.Equal), reject timestamps older than 5 minutes and alert on the signature_invalid rate.
Timeout không có nghĩa là cổng chưa trừ tiền; tạo giao dịch mới ở lần retry có thể trừ khách hai lần. Retry bằng cùng gateway reference hoặc idempotency key của cổng, và khi không chắc thì để payment PENDING cho job đối soát gọi queryStatus thay vì tạo lại.A timeout does not mean the gateway did not charge; creating a new transaction on retry can charge the customer twice. Retry with the same gateway reference or the gateway's idempotency key, and when unsure leave the payment PENDING for reconciliation to call queryStatus instead of creating it again.
0,1 + 0,2 bằng 0,30000000000000004, và sau 300.000 giao dịch sai số làm đối soát lệch vài nghìn đồng không giải thích nổi. Dùng BIGINT đơn vị nhỏ nhất (VND không có xu, USD tính cent) hoặc BigDecimal, lưu currency bên cạnh và kiểm tổng refund không vượt amount_minor dưới khoá dòng.0.1 + 0.2 equals 0.30000000000000004, and after 300,000 payments the drift leaves reconciliation thousands of dong off with no explanation. Use BIGINT minor units (VND has no subunit, USD uses cents) or BigDecimal, store the currency alongside, and check that refunds never exceed amount_minor under a row lock.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
Idempotency key sinh phía client cho mỗi lần checkout, unique index trong bảng payment. Request thứ hai trả lại payment cũ. Nếu cổng hỗ trợ idempotency key (Stripe), truyền tiếp để chính cổng cũng không tạo charge thứ hai.A client-generated idempotency key per checkout, with a unique index on the payment table. The second request returns the existing payment. If the gateway accepts an idempotency key (Stripe), pass it on so the gateway does not create a second charge either.
State machine chỉ cho phép chuyển hợp lệ; SUCCEEDED là trạng thái cuối trừ khi hoàn tiền. Sự kiện cũ bị bỏ qua, ghi log, vẫn trả 200. Nếu nghi ngờ, gọi queryStatus để lấy trạng thái thật từ cổng.The state machine allows only valid transitions; SUCCEEDED is final except for refunds. The stale event is ignored and logged, and the endpoint still answers 200. When in doubt, call queryStatus for the gateway's real status.
Số dấu phẩy động nhị phân không biểu diễn chính xác 0.1, cộng dồn sẽ lệch. Dùng long theo đơn vị nhỏ nhất kèm mã tiền tệ, hoặc BigDecimal với scale và RoundingMode rõ ràng.Binary floating point cannot represent 0.1 exactly, so sums drift. Use a long in minor units with a currency code, or BigDecimal with an explicit scale and RoundingMode.
Thường do lỗi giữa lúc gọi cổng và lúc ghi DB, hoặc ai đó tạo giao dịch thủ công trên portal của cổng. Ghi vào reconciliation_item với MISSING_LOCAL, báo kế toán; nếu khớp được đơn thì bổ sung, không khớp thì hoàn tiền.Usually a crash between calling the gateway and writing the DB, or someone created a payment by hand in the gateway portal. Record it as MISSING_LOCAL, alert finance; if it matches an order, backfill it, otherwise refund.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.