TPBank API client cho Node.js (>= 18) — lấy lịch sử giao dịch TPBank. Viết bằng TypeScript, ship cả ESM và CJS, kèm .d.ts đầy đủ.
⚠️ NÊN DÙNG PROXY XOAY để tránh bị block từ ngân hàng. CRON chậm thôi, không quá nhanh.
npm install tpbank-api- Mở trình duyệt đã từng đăng nhập xác minh khuôn mặt
- Vào trang https://ebank.tpb.vn/retail/vX/ và đăng nhập
- Bấm F12, tab Console, paste đoạn code sau:
localStorage.deviceId
- Copy giá trị trả về và sử dụng trong code
import { TPBankClient } from 'tpbank-api';
const client = new TPBankClient({
username: 'your_username',
password: 'your_password',
deviceId: 'your_device_id',
accountId: 'your_account_id',
});
// Tự động login nếu chưa có token / token hết hạn
const data = await client.getTransactionHistory({ days: 7 });
console.log(data.transactionInfos);CommonJS cũng hoạt động:
const { TPBankClient } = require('tpbank-api');| Tham số | Kiểu | Bắt buộc | Mặc định | Mô tả |
|---|---|---|---|---|
username |
string |
✓ | — | Tên đăng nhập TPBank |
password |
string |
✓ | — | Mật khẩu đăng nhập |
deviceId |
string |
✓ | — | Device ID lấy từ trình duyệt |
accountId |
string |
✓ | — | Số tài khoản TPBank |
proxy |
ProxyConfig |
✗ | — | Cấu hình proxy (xem bên dưới) |
timeoutMs |
number |
✗ | 30000 |
Timeout cho mọi request (ms) |
extraHeaders |
Record<string, string> |
✗ | — | Override/thêm headers HTTP |
logger |
Logger |
✗ | — | Hook để log lifecycle (login, retry, ...) |
Đăng nhập và lưu access token. Trả về Promise<LoginResult>.
Có in-flight cache — nếu nhiều caller gọi đồng thời, chỉ phát ra một HTTP request login, các caller khác share kết quả.
const { accessToken, expiresIn, expiresAt } = await client.login();Lấy lịch sử giao dịch. Tự gọi login() nếu chưa có token hợp lệ.
| Option | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
days |
number |
30 |
Số ngày lấy lịch sử |
pageNumber |
number |
1 |
Trang |
pageSize |
number |
400 |
Số giao dịch mỗi trang |
keyword |
string |
'' |
Từ khóa tìm kiếm |
Trả về Promise<TransactionHistoryResponse> — object có shape API gốc, đã được validate trước khi return:
const res = await client.getTransactionHistory({ days: 7, pageSize: 100 });
res.transactionInfos.forEach((tx) => {
console.log(tx.transactionDate, tx.amount, tx.description);
});isTokenValid()→boolean. Token còn hợp lệ (có buffer 120s an toàn).clear()→ reset token đã cache, force re-login lần gọi sau.
Hỗ trợ http, https, socks4, socks5. Username/password được URL-encode tự động — cứ truyền nguyên password kể cả khi chứa @, :, #, /, ...
const client = new TPBankClient({
username: 'your_username',
password: 'your_password',
deviceId: 'your_device_id',
accountId: 'your_account_id',
proxy: {
schema: 'socks5', // 'http' | 'https' | 'socks4' | 'socks5'
host: '127.0.0.1',
port: 1080,
username: 'proxy_user', // optional
password: 'p@ss:word#1', // chứa ký tự đặc biệt vẫn OK
},
});🔒 Lưu ý bảo mật: nếu config proxy sai (thiếu field, sai schema), client sẽ throw ngay khi khởi tạo thay vì silent fallback về direct connection — tránh rò rỉ IP thật ra TPBank.
import {
TPBankClient,
AuthenticationError,
TokenExpiredError,
TPBankError,
} from 'tpbank-api';
try {
const data = await client.getTransactionHistory();
} catch (error) {
if (error instanceof AuthenticationError) {
// Sai credentials, hoặc session bị server revoke
console.error('Auth:', error.message);
} else if (error instanceof TokenExpiredError) {
// Token hết hạn (hiếm khi escape ra ngoài vì client đã auto-retry)
console.error('Token expired:', error.message);
} else if (error instanceof TPBankError) {
// Các lỗi API khác (HTTP non-2xx, response shape sai, ...)
console.error('TPBank API:', error.message, error.statusCode);
console.error('Original:', error.originalError); // credentials đã được redact
}
}Sanitization: trước khi gắn originalError (từ axios) vào TPBankError, client tự redact các field nhạy cảm (username, password, deviceId, ...) — bạn có thể log error free-mind mà không lo leak credentials.
const client = new TPBankClient({
// ...credentials,
logger: {
debug: (msg, ctx) => console.debug('[TPBank]', msg, ctx),
info: (msg, ctx) => console.info('[TPBank]', msg, ctx),
warn: (msg, ctx) => console.warn('[TPBank]', msg, ctx),
error: (msg, ctx) => console.error('[TPBank]', msg, ctx),
},
});Workflow dùng Changesets — tự động tạo Release PR khi có changeset, publish lên npm khi merge.
# Tạo changeset cho thay đổi của bạn
npm run changeset
# Commit + push → GitHub Actions sẽ:
# 1. Tạo "Version Packages" PR (gom changesets, bump version, update CHANGELOG)
# 2. Khi merge PR đó → publish lên npm với provenance signatureThêm secret NPM_TOKEN vào GitHub repo:
- Tạo Granular Access Token (loại Automation) tại npmjs.com/settings/tokens
- Repo GitHub → Settings → Secrets and variables → Actions → New repository secret
- Name:
NPM_TOKEN, Value: token vừa tạo
CI cũng cần các permission: contents: write, pull-requests: write, id-token: write (đã setup sẵn trong .github/workflows/release.yml).
getTransactionHistory()giờ trả về objectTransactionHistoryResponsethay vì array. Truy cập array qua.transactionInfos.- Proxy config sai giờ throw thay vì fallback. Kiểm tra try/catch quanh
new TPBankClient(...). - Lỗi 401 sau retry login thất bại giờ là
AuthenticationError(không phảiTokenExpiredError). - Yêu cầu Node >= 18.
Chi tiết xem CHANGELOG.md.
- Mã nguồn công khai, cho phép xem, sửa đổi, cải thiện.
- Được phép sử dụng vào mục đích thương mại: cổng thanh toán, thông báo giao dịch, ...
- Không sử dụng thương mại để mở các dịch vụ tương tự Casso.vn.
- Dịch vụ dùng API không chính thức của TPBank. Người phát triển không chịu trách nhiệm cho bất kỳ vấn đề pháp lý nào phát sinh.