Integrating a VNPay-style payment gateway: redirect, signatures and IPN
The full redirect payment flow from step 1 to 9.2.3: the parties and how far to trust each, payment attempts and state machines, signing the URL with HMAC-SHA512 and the usual checksum bugs, an idempotent IPN handler with its reply codes, the return URL, and security.
On this page
Most payment bugs live around the API call: the customer closes the tab halfway, the gateway calls back three times, the amount is off by 100× because someone forgot the unit. This post walks the full VNPay-style redirect flow (MoMo, ZaloPay, OnePay and Stripe Checkout share the pattern), steps 1 to 9.2.3. Part 2 covers operations: late IPNs, reconciliation, sandbox and failure modes.
vnp_* parameters follow VNPay's 2.1.0 docs; always check the current docs the gateway gives you.
1. The problem
A handler marks a booking PAID when the return URL carries vnp_ResponseCode=00. Someone edits the parameter in the browser and gets a ticket without paying. The same week, a customer closes the tab after paying, the return URL never arrives, and a paid order stays stuck.
2. Key idea
The return URL is the customer saying "I paid"; the IPN is the stamped bank statement. Only book from the statement. The backend trusts only the amount it computed itself and the signed IPN; anything through the browser can be edited or may never arrive. 9.1 and 9.2 run in parallel, in no particular order.
| Checks on an IPN, in order | On failure return RspCode |
|---|---|
| Store the raw callback | |
Signature (MessageDigest.isEqual) |
97 |
Order exists for vnp_TxnRef |
01 |
Amount: vnp_Amount / 100 == payment.amount |
04 |
| Status not yet final | 02 (already confirmed) |
| Update in one transaction | 00 once written; 99 on DB errors so the gateway resends |
Success requires both vnp_ResponseCode = 00 and vnp_TransactionStatus = 00. Failures are recorded too (payment FAILED) and answered with 00.
2.1 Other rules
- One
txn_refper attempt (PAY-<booking>-<n>): the gateway rejects reused codes. A partial unique index keeps at most onePENDINGpayment per booking. vnp_ExpireDateshorter than the hold: URL 15 minutes, seat 20 minutes.- The hash secret lives in a secret manager, not the repo.
- Slow work (issuing tickets, email, invoices) goes through an outbox, not the IPN handler.
3. In Java
final class Signer {
private final byte[] secret;
Signer(String secret) { this.secret = secret.getBytes(StandardCharsets.UTF_8); }
String sign(Map<String, String> params) throws Exception {
String data = new TreeMap<>(params).entrySet().stream() // sorted by name
.filter(e -> !e.getKey().equals("vnp_SecureHash") && !e.getValue().isEmpty())
.map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(new SecretKeySpec(secret, "HmacSHA512"));
return HexFormat.of().formatHex(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
}
}
// "Thanh toan" -> vnp_OrderInfo=Thanh+toan (URLEncoder) differs from Thanh%20toan (encodeURIComponent)
// vnp_Amount: 6,820,000 VND -> 682000000; convert units in exactly one placeIdempotent update: UPDATE payment ... WHERE txn_ref = ? AND status IN ('PENDING','EXPIRED'); EXPIRED is accepted because real money was taken.
The payment table
CREATE TABLE payment (
payment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
booking_id bigint NOT NULL REFERENCES booking,
txn_ref text NOT NULL UNIQUE, -- vnp_TxnRef: one per attempt
amount bigint NOT NULL, -- VND, not ×100
status text NOT NULL, -- PENDING, SUCCEEDED, FAILED, EXPIRED, REFUND_PENDING
gateway_txn_no text UNIQUE, -- vnp_TransactionNo
expires_at timestamptz NOT NULL
);
CREATE UNIQUE INDEX one_pending_payment ON payment (booking_id) WHERE status = 'PENDING';A gateway_callback table stores every callback verbatim for debugging and reconciliation. Payment is its own bounded context; Booking calls it through a port.
4. Working with AI
Give the AI: the signing function from the gateway docs, fixture tests with sample signatures, an IPN handler following the check order.
Check in AI-written code:
- The return URL writes nothing to the DB.
- The amount comes from the DB; the frontend only sends
booking_code. - The IPN handler checks in order: signature, order, amount, status.
- The
UPDATEis conditional on status; no email or ticketing in the handler. - A signature fixture test exists, including values with spaces and special characters.
5. Exercises
Exercise 1: Review a handler
A handler takes the return URL; if vnp_ResponseCode == "00" it runs UPDATE booking SET status = 'PAID' WHERE booking_code = ? using vnp_TxnRef, sends an email, then redirects to a thank-you page. List the bugs.
Solution to Exercise 1
- The return URL as source of truth: move to the IPN.
- No signature check.
- No amount check (nor the ×100 unit).
- No
vnp_TransactionStatuscheck. - An
UPDATEwithout a status condition: anEXPIREDbooking gets overwritten toPAID. - Booking code as
txn_ref: no retries possible; split out apaymenttable. - Email before commit: move it to an outbox.
Exercise 2: "Invalid checksum" for some orders only
Orders whose vnp_OrderInfo is "Thanh toan don 123" get invalid checksum from the gateway; "ThanhToan123" doesn't. The AI suggests "rotate the secret and regenerate". Diagnose and prevent.
Solution to Exercise 2
Not a wrong key: the signed string has spaces encoded as + while the gateway signs with %20 (or vice versa). Rotating the secret fixes nothing.
Fix: encode exactly as the gateway's docs (or official sample code) do. Prevention: a fixture test with parameters and a sample signature taken from the docs or a real sandbox transaction, including values with spaces, /, : and &; run it in CI.
Summary
- The IPN is the source of truth; the return URL is for display.
- A
paymenttable separate frombooking, onetxn_refper attempt. - Signing: sort by name, encode, HMAC-SHA512; "invalid checksum" is usually the signed string.
vnp_Amount= VND × 100, converted in one place.- IPN handler: signature → order → amount → status; slow work via outbox.
Read more: Late IPNs and reconciliation.
Comments
Community rules