Skip to content

chuanghiduoc/api_tpbank_free

Repository files navigation

tpbank-api

npm version Node

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.

Cài đặt

npm install tpbank-api

Lấy Device ID

  1. Mở trình duyệt đã từng đăng nhập xác minh khuôn mặt
  2. Vào trang https://ebank.tpb.vn/retail/vX/ và đăng nhập
  3. Bấm F12, tab Console, paste đoạn code sau:
    localStorage.deviceId
  4. Copy giá trị trả về và sử dụng trong code

Sử dụng nhanh

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');

API

new TPBankClient(options)

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, ...)

client.login()

Đăng nhập và lưu access token. Trả về Promise<LoginResult>.

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();

client.getTransactionHistory(options?)

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);
});

client.isTokenValid() / client.clear()

  • 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.

Proxy

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.

Xử lý lỗi

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.

Logging tùy chỉnh

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),
  },
});

Release (cho maintainer)

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 signature

Setup lần đầu

Thêm secret NPM_TOKEN vào GitHub repo:

  1. Tạo Granular Access Token (loại Automation) tại npmjs.com/settings/tokens
  2. Repo GitHub → SettingsSecrets and variablesActionsNew repository secret
  3. 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).

Migration từ v2.x lên v3.0.0

  • getTransactionHistory() giờ trả về object TransactionHistoryResponse thay 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ải TokenExpiredError).
  • Yêu cầu Node >= 18.

Chi tiết xem CHANGELOG.md.

Miễn trừ trách nhiệm

  • 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.

About

API này cung cấp các endpoint để lấy lịch sử giao dịch cho khách hàng của Tpbank. Update 25/02/2026 OK

Topics

Resources

Stars

Watchers

Forks

Sponsor this project

 

Contributors