Tích hợp ThueAPI.VN với Node.js 

Node.js là lựa chọn phổ biến cho các ứng dụng realtime nhờ event-driven architecture. Kết hợp với ThueAPI webhook, bạn có thể xây dựng hệ thống thanh toán tự động hiệu suất cao.

1. Gọi API với axios

// Cài đặt: npm install axios
const axios = require('axios');

const thueapi = axios.create({
  baseURL: 'https://thueapi.vn/api/v1',
  headers: {
    'Authorization': `Bearer ${process.env.THUEAPI_API_KEY}`,
    'Content-Type': 'application/json',
  },
});

// Lấy danh sách giao dịch
async function getTransactions(params = {}) {
  try {
    const { data } = await thueapi.get('/transactions', { params });
    return data.transactions;
  } catch (error) {
    console.error('ThueAPI Error:', error.response?.data || error.message);
    throw error;
  }
}

// Sử dụng
const transactions = await getTransactions({
  bank: 'VCB',
  from_date: '2026-03-01',
  per_page: 20,
});
console.log(`Tìm thấy ${transactions.length} giao dịch VCB`);

2. Webhook endpoint với Express

const express = require('express');
const app = express();
app.use(express.json());

// Middleware xác thực webhook
function verifyWebhook(req, res, next) {
  const token = req.headers.authorization?.replace('Bearer ', '');
  if (token !== process.env.THUEAPI_WEBHOOK_SECRET) {
    return res.status(401).json({ success: false });
  }
  next();
}

// Endpoint nhận webhook
app.post('/webhook/thueapi', verifyWebhook, async (req, res) => {
  const { transactions } = req.body;

  for (const tx of transactions) {
    console.log(`[${tx.bank}] ${tx.type === 'IN' ? '+' : '-'}${tx.amount.toLocaleString()}đ - ${tx.description}`);

    // Xử lý business logic
    await processTransaction(tx);
  }

  // BẮT BUỘC trả về success
  res.json({ success: true });
});

async function processTransaction(tx) {
  // Ví dụ: Tìm đơn hàng từ nội dung chuyển khoản
  const match = tx.description.match(/ORDER(\d+)/);
  if (match) {
    const orderId = match[1];
    // await Order.findByIdAndUpdate(orderId, { status: 'paid', paidAt: new Date() });
    console.log(`Đơn hàng #${orderId} đã thanh toán`);
  }
}

app.listen(3000, () => console.log('Webhook server running on port 3000'));

3. Với fetch (Node.js 18+)

// Không cần cài thêm package
const response = await fetch('https://thueapi.vn/api/v1/transactions', {
  headers: {
    'Authorization': `Bearer ${process.env.THUEAPI_API_KEY}`,
  },
});
const data = await response.json();
console.log(data.transactions);

Mẹo production

  • Idempotency: Kiểm tra transaction_id trùng lặp trước khi xử lý
  • Queue: Dùng Bull/BullMQ để xử lý webhook async, trả response nhanh
  • Logging: Log mọi webhook nhận được để debug khi cần
  • Timeout: Trả response trong 10 giây để tránh retry không cần thiết