What is IPN and why does it matter more than return_url?
IPN (Instant Payment Notification) is a server-to-server mechanism: once a transaction completes, TCONNECT calls your backend directly to report the result, whether or not the user returns to your website.
return_url is only a browser redirect. The user can:
- Close the tab right after paying
- Lose their connection during the redirect
- Hit the Back button in the browser
If you mark an order paid at the return_url, your system will miss all of these cases. Always use IPN to confirm payment.
The standard IPN flow
[Khách thanh toán tại cổng TConnect]
│
▼
[TConnect xác nhận với ngân hàng]
│
┌────────┴────────┐
│ │
[IPN POST] [Redirect return_url]
server-to-server trình duyệt
│
▼
[Backend của bạn]
│
Verify → Process → Return 200Implementing a production-grade IPN handler
// IPN endpoint: POST /webhook/tconnect/ipn
function ipn_handler(request):
// Parse request body
body = parse_json(request)
if parse fails:
return error 400 "Invalid JSON"
// 1. Decrypt payload
txn = decrypt_aes(body.data, AES_KEY)
if decrypt fails:
log error "IPN decrypt failed"
return error 400 "Decrypt failed"
request_id = txn.request_id
order_id = txn.order_id
status = txn.status
amount = txn.amount
log info "IPN received: order={order_id} status={status} amount={amount}"
// 2. Idempotency — dùng request_id làm unique key
cache_key = "ipn:processed:{request_id}"
if cache.get(cache_key) exists:
log info "IPN duplicate skipped: request_id={request_id}"
return { status: "ok" } // Trả 200 để TConnect không retry tiếp
// 3. Xác thực order tồn tại
order = db.get_order(order_id)
if order not found:
log warning "IPN for unknown order: {order_id}"
return { status: "ok" } // Vẫn trả 200
// 4. Xác thực số tiền
if amount != order.expected_amount:
log warning "IPN amount mismatch: expected={order.expected_amount}, got={amount}"
db.flag_order_for_review(order_id, reason="amount_mismatch")
return { status: "ok" }
// 5. Xử lý theo trạng thái
if status == "SUCCESS":
db.mark_order_paid(order_id, txn)
send_confirmation_email(order)
else if status == "FAILED":
db.mark_order_failed(order_id, txn.error_code)
else if status == "PENDING":
log info "IPN pending for order {order_id} — waiting for final status"
return { status: "ok" }
// 6. Mark đã xử lý — TTL 24h để tránh memory leak
cache.set(cache_key, ttl=86400)
// 7. Bắt buộc trả 200
return { status: "ok" }Idempotency: why is it mandatory?
TCONNECT retries the IPN in these cases:
- Your backend returns an HTTP 5xx
- Connection timeout
- No response received
Without an idempotency check, a single transaction can be processed two or three times:
IPN lần 1 → Backend xử lý → Trả 200 nhưng timeout
IPN retry 1 → Backend xử lý LẦN 2 ← LỖI: charge 2 lần!The fix: use request_id (unique per IPN) as a key in Redis or a database:
// Trước khi xử lý
if cache.get("ipn:{txn.request_id}") exists:
return { status: "ok" } // Skip
// Sau khi xử lý thành công
cache.set("ipn:{txn.request_id}", ttl=86400)Handling IPNs that are delayed or never arrive
Networks are not always perfect. Implement a fallback:
// Cronjob chạy mỗi 15 phút
function reconcile_pending_orders():
// Lấy các order pending quá 10 phút
pending_orders = db.get_pending_orders(older_than_minutes=10)
for each order in pending_orders:
try:
// Query TConnect API để lấy trạng thái thực
status = tconnect.check_payment_status(order.id)
if status == "SUCCESS":
db.mark_order_paid(order.id)
else if status == "FAILED":
db.mark_order_failed(order.id)
else if status == "EXPIRED":
db.cancel_order(order.id)
on error:
log error "Reconcile failed for order {order.id}"Securing the IPN endpoint
1. Whitelist TCONNECT IPs
TCONNECT_IPS = ["103.x.x.x", "118.x.x.x"] // Lấy từ tài liệu TConnect
// HTTP middleware — chạy trước mọi request
function verify_ip_middleware(request, next):
if request.path starts with "/webhook/tconnect":
client_ip = request.client_ip
if client_ip not in TCONNECT_IPS:
return response 403 Forbidden
return next(request)2. Do not expose the IPN endpoint in docs/swagger
Add this to your OpenAPI config:
// Tắt docs/swagger hoặc exclude route IPN khỏi API schema
configure app:
disable_docs = true // Hoặc exclude "/webhook/tconnect/ipn" khỏi schema3. Rate limiting
// Áp dụng rate limiting cho IPN endpoint
// Giới hạn: 60 request/phút theo IP nguồn
// TConnect không gửi quá nhiều IPN trong 1 phút
apply rate_limit(60 per minute, key=client_ip) to POST /webhook/tconnect/ipnMonitoring and alerting
Metrics worth tracking:
| Metric | Alert when |
|---|---|
| IPN processing time | > 2 seconds |
| IPN failure rate | > 1% |
| Duplicate IPN rate | > 5% (may indicate heavy retrying) |
| Orders pending over 30 minutes | > 0 |
| AES decrypt error | > 0 |
// Metrics cần theo dõi (ví dụ: Prometheus / StatsD)
counter ipn_total(status) // Tổng IPN nhận được, nhóm theo status
histogram ipn_duration_seconds // Thời gian xử lý mỗi IPN
counter ipn_duplicates_total // Số IPN trùng đã bỏ qua
// Trong IPN handler
function ipn_handler(request):
start_timer()
// ... xử lý ...
record ipn_duration_seconds = elapsed_time()
increment ipn_total(status = txn.status)Conclusion
A good IPN handler does not stop at "receive and process." It is a system that stays reliable even when the network is flaky, even when TCONNECT retries many times, even when the server restarts mid-request. Investing in idempotency and reconciliation from the start saves a lot of debugging later.