KiotViet hiện không hỗ trợ dán trực tiếp Webhook từ SePay hay Casso vào giao diện quản trị để tự động gạch nợ chuyển khoản VietQR. Để khi khách vừa quét mã VietQR xong là trạng thái thanh toán trên KiotViet tự động cập nhật (và báo qua Telegram/Zalo cho kho đóng hàng ngay), bạn cần dựng một Middleware Listener nhẹ bằng Node.js hoặc n8n.
Tuy nhiên, các hướng dẫn sơ sài thường bỏ qua 3 lỗi chết người trong thực tế vận hành tiền thật:
- Webhook từ cổng ngân hàng bắn retry khi timeout → Gạch nợ 2 lần cho cùng 1 giao dịch nếu thiếu lớp
Idempotency. - App ngân hàng phía người gửi tự chèn tiền tố dài hoặc xoá mất dấu gạch ngang → Regex đơn giản tìm không ra mã hoá đơn
HD012345/DH012345. - Khách chuyển thiếu 10.000đ hoặc gộp tiền 2 đơn → Nếu code tự đánh dấu Đã thanh toán đủ là thất thoát công nợ ngay.
Bài viết này cung cấp cấu trúc xử lý chuẩn production đang được Kỹ sư Trần Như Ý triển khai cho hệ thống tích hợp KiotViet & VietQR SePay tại Sèo Trum.

1. Luồng xử lý an toàn giữa SePay/Casso → Middleware → KiotViet
[Khách quét VietQR] ──▶ [Ngân hàng] ──▶ [SePay / Casso Webhook POST]
│
(1) Verify Header Apikey / Secure-Token
(2) Idempotency Check (transactionId / referenceCode)
(3) Extract Mã HĐ/ĐH + Kiểm tra tiền vào (in)
(4) OAuth2 KiotViet Public API -> Check Tổng tiền
├── Đủ tiền ──▶ POST thanh toán KiotViet + Báo Telegram
└── Sai lệch ──▶ Không gạch tự động + Cảnh báo Kế toán
2. Code Node.js (Next.js / Express) nhận Webhook SePay & Gạch nợ KiotViet API
Đoạn code dưới đây xử lý đầy đủ:
- Xác thực Header
Authorization: Apikey <KEY>từ SePay (tránh người ngoài giả mạo request POST vào endpoint của bạn). - Bộ nhớ đệm
Access Tokencủa KiotViet Public API (hết hạn tự xin lại, không gọi OAuth2 thừa mỗi giao dịch). - Bảng ghi Idempotency chống gạch nợ đúp khi SePay gửi retry.
- Kiểm tra chặt chẽ số tiền còn phải thu (
remaining = total - totalPayment) trước khi ghi nhận thanh toán.
// webhook-handler.ts (chạy được trên Node.js 18+/22+ hoặc Next.js App Router)
import crypto from "crypto";
interface SepayWebhookPayload {
id: number;
gateway: string;
transactionDate: string;
accountNumber: string;
code: string | null;
content: string;
transferType: "in" | "out";
transferAmount: number;
referenceCode?: string;
}
// Trong production lưu vào SQLite / PostgreSQL bảng UNIQUE(tx_key)
const processedTxKeys = new Set<string>();
let cachedKiotToken: { token: string; expiresAt: number } | null = null;
async function getKiotVietAccessToken(): Promise<string> {
if (cachedKiotToken && Date.now() < cachedKiotToken.expiresAt - 60_000) {
return cachedKiotToken.token;
}
const params = new URLSearchParams({
scopes: "PublicApi.Access",
grant_type: "client_credentials",
client_id: process.env.KIOTVIET_CLIENT_ID!,
client_secret: process.env.KIOTVIET_CLIENT_SECRET!,
});
const res = await fetch("https://id.kiotviet.vn/connect/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
});
if (!res.ok) {
throw new Error(`KiotViet OAuth failed: HTTP ${res.status}`);
}
const data = (await res.json()) as { access_token: string; expires_in: number };
cachedKiotToken = {
token: data.access_token,
expiresAt: Date.now() + data.expires_in * 1000,
};
return cachedKiotToken.token;
}
function verifySepayAuth(authHeader: string | null): boolean {
const expected = `Apikey ${process.env.SEPAY_WEBHOOK_API_KEY || ""}`;
if (!authHeader || !process.env.SEPAY_WEBHOOK_API_KEY) return false;
const a = Buffer.from(authHeader.trim());
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
function extractOrderOrInvoiceCode(payload: SepayWebhookPayload): string | null {
if (payload.code && /^(?:DH|HD)[A-Z0-9]{4,14}$/i.test(payload.code.trim())) {
return payload.code.trim().toUpperCase();
}
// Xử lý trường hợp ngân hàng chèn chuỗi "MBVCB... DH 12345 chuyen khoan"
const normalized = (payload.content || "").toUpperCase().replace(/[^A-Z0-9\s]/g, " ");
const m = normalized.match(/\b((?:DH|HD)\s?\d{4,12})\b/);
return m ? m[1].replace(/\s+/g, "") : null;
}
export async function processSepayWebhook(
authHeader: string | null,
payload: SepayWebhookPayload,
notifyTelegram: (msg: string) => Promise<void>,
) {
// 1. Bảo mật bắt buộc
if (!verifySepayAuth(authHeader)) {
return { status: 401, body: { ok: false, error: "Invalid Apikey" } };
}
// Chỉ xử lý giao dịch tiền VÀO
if (payload.transferType !== "in" || payload.transferAmount <= 0) {
return { status: 200, body: { ok: true, ignored: "not_incoming_transfer" } };
}
// 2. Idempotency Lock chống webhook retry ghi sổ 2 lần
const txKey = `sepay:${payload.id}:${payload.referenceCode || ""}`;
if (processedTxKeys.has(txKey)) {
return { status: 200, body: { ok: true, deduplicated: true } };
}
processedTxKeys.add(txKey);
// 3. Bóc tách mã đơn/hoá đơn
const docCode = extractOrderOrInvoiceCode(payload);
if (!docCode) {
await notifyTelegram(
`⚠️ Tiền về ${payload.transferAmount.toLocaleString("vi-VN")}đ (${payload.gateway}) nhưng KHÔNG tìm thấy mã ĐH/HĐ.\nNội dung: ${payload.content}`,
);
return { status: 200, body: { ok: true, matched: false } };
}
// 4. Tra cứu hoá đơn trên KiotViet Public API
const kvToken = await getKiotVietAccessToken();
const kvHeaders = {
Authorization: `Bearer ${kvToken}`,
Retailer: process.env.KIOTVIET_RETAILER!,
"Content-Type": "application/json",
};
const searchRes = await fetch(
`https://public.kiotapi.com/invoices/code/${encodeURIComponent(docCode)}`,
{ headers: kvHeaders },
);
if (!searchRes.ok) {
await notifyTelegram(
`⚠️ Nhận ${payload.transferAmount.toLocaleString("vi-VN")}đ cho mã ${docCode} nhưng không tra thấy hoá đơn trên KiotViet (HTTP ${searchRes.status}).`,
);
return { status: 200, body: { ok: true, kiotFound: false } };
}
const invoice = (await searchRes.json()) as {
id: number;
code: string;
total: number;
totalPayment: number;
branchId: number;
};
const remaining = Math.max(0, (invoice.total || 0) - (invoice.totalPayment || 0));
// 5. Đối soát số tiền (Cho phép sai số tối đa 0đ; chuyển thiếu phải cảnh báo)
if (remaining <= 0) {
return { status: 200, body: { ok: true, note: "Invoice already fully paid" } };
}
if (payload.transferAmount < remaining) {
await notifyTelegram(
`🚨 CHUYỂN THIẾU TIỀN mã ${invoice.code}: Cần thu ${remaining.toLocaleString("vi-VN")}đ, khách chuyển ${payload.transferAmount.toLocaleString("vi-VN")}đ (${payload.gateway}). Chưa chốt đủ đơn!`,
);
return { status: 200, body: { ok: true, partialPayment: true } };
}
// 6. Ghi nhận thanh toán / Cập nhật công nợ sang KiotViet Payments API
const payRes = await fetch("https://public.kiotapi.com/payments", {
method: "POST",
headers: kvHeaders,
body: JSON.stringify({
invoiceId: invoice.id,
method: "Transfer",
amount: remaining,
description: `Auto VietQR ${payload.gateway} ref=${payload.referenceCode || payload.id}`,
branchId: invoice.branchId,
}),
});
if (!payRes.ok) {
const errTxt = await payRes.text();
await notifyTelegram(`❌ Lỗi ghi nhận thanh toán KiotViet cho ${invoice.code}: ${errTxt}`);
return { status: 500, body: { ok: false, error: "KiotViet payment sync failed" } };
}
await notifyTelegram(
`✅ Đã gạch nợ thành công ${invoice.code}: +${payload.transferAmount.toLocaleString("vi-VN")}đ (${payload.gateway})`,
);
return { status: 200, body: { ok: true, syncedInvoice: invoice.code } };
}
3. Áp dụng tương tự cho Webhook Casso & n8n
Nếu bạn dùng Casso thay cho SePay, cấu trúc trung gian y hệt, chỉ khác 2 chi tiết nhỏ ở bước nhận Payload:
- Header xác thực của Casso là
secure-tokenthay vìAuthorization: Apikey .... - Casso bắn về mảng
payload.data(có thể chứa nhiều giao dịch trong 1 lần webhook), nên trong n8n cần đặt thêm một node Split Out (Field To Split Out = body.data) trước bước Regex & Idempotency check (đọc/ghi bảng PostgreSQL/SQLiteON CONFLICT (tx_id) DO NOTHING).
4. Kết luận
Triển khai đối soát biến động số dư không khó ở bước gọi API, mà khó ở tính toàn vẹn giao dịch (Idempotency) và các ca ngoại lệ chuyển thiếu/sai cú pháp. Một middleware ~150 dòng chạy trên VPS riêng sẽ ổn định và tiết kiệm chi phí hơn nhiều so với mua phần mềm trung gian theo tháng.
Bạn có thể xem thêm các phương án đồng bộ tại Tích Hợp KiotViet Với VietQR SePay Tự Động, giải pháp Bot Telegram Điều Hành Đơn Hàng và Tự Động Hoá Kế Toán & Đối Soát của Sèo Trum.




