Kiểm thử Webhook với Local Tunnel
Kiểm thử webhook HiTechCloud Pay: chạy endpoint trên máy local và nhận webhook thật qua ngrok hoặc cloudflared, kèm cách giả lập payload bằng cURL.
Khi đang phát triển, endpoint của bạn chạy ở localhost nên HiTechCloud Pay không thể gọi vào. Local tunnel tạo một URL công khai tạm thời chuyển tiếp request về máy bạn, giúp nhận webhook thật ngay khi code.
Cách 1: Dùng ngrok
Mở tunnel tới cổng ứng dụng local
# Giả sử ứng dụng chạy ở cổng 3000
ngrok http 3000
# ngrok in ra URL công khai, ví dụ:
# Forwarding https://a1b2-14-225-0-1.ngrok-free.app -> http://localhost:3000Dán URL https://...ngrok-free.app/api/hitechcloud-webhook vào mục URL Webhook trên Sandbox, rồi bấm Gửi thử. Giao diện web của ngrok tại http://127.0.0.1:4040 cho bạn xem lại và phát lại (replay) từng request.
Cách 2: Dùng cloudflared (miễn phí, không cần tài khoản)
Tạo tunnel nhanh với cloudflared
cloudflared tunnel --url http://localhost:3000
# Xuat ra URL dang:
# https://random-words-here.trycloudflare.comGiả lập payload bằng cURL
Để kiểm thử nhanh mà không phụ thuộc mạng, bạn có thể tự POST một payload mẫu vào endpoint local.
Gửi payload giả lập vào endpoint local
curl -X POST http://localhost:3000/api/hitechcloud-webhook \
-H 'Content-Type: application/json' \
-d '{
"id": 999001,
"gateway": "Vietcombank",
"transactionDate": "2026-10-31 10:00:00",
"accountNumber": "9988776655",
"code": "DH12345",
"content": "DH12345 thanh toan thu",
"transferType": "in",
"transferAmount": 50000,
"accumulated": 0,
"referenceCode": "TEST001"
}'Giả lập kèm chữ ký HMAC hợp lệ
Tự ký payload để test luồng xác thực HMAC (bash)
SECRET="whsec_sandbox_xxx"
BODY='{"id":999002,"transferAmount":50000,"content":"DH999 test","transferType":"in"}'
TS=$(date +%s)
SIG="sha256=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')"
curl -X POST http://localhost:3000/api/hitechcloud-webhook \
-H 'Content-Type: application/json' \
-H "X-HiTechCloud-Timestamp: $TS" \
-H "X-HiTechCloud-Signature: $SIG" \
--data "$BODY"Khi test HMAC bằng cURL, hãy đảm bảo chuỗi
--data gửi đi khớp từng byte với chuỗi bạn dùng để ký. Mọi khác biệt về khoảng trắng đều làm chữ ký sai.Viết kiểm thử tự động
Unit test endpoint bằng Jest + supertest
const request = require('supertest');
const app = require('../app');
test('xu ly giao dich tien vao', async () => {
const res = await request(app)
.post('/api/hitechcloud-webhook')
.send({ id: 1, transferAmount: 50000, content: 'DH1', transferType: 'in' });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
test('chong trung lap: gui lai cung id van tra 200', async () => {
const payload = { id: 2, transferAmount: 50000, content: 'DH2', transferType: 'in' };
await request(app).post('/api/hitechcloud-webhook').send(payload);
const res = await request(app).post('/api/hitechcloud-webhook').send(payload);
expect(res.status).toBe(200);
});