bankopenapi 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BankOpenAPI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,218 @@
1
- # Temporary Holding Version
1
+ # bankopenapi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Thư viện chính thức của [BankOpenAPI](https://bankopenapi.com) cho JavaScript và TypeScript: nhận tiền chuyển khoản vào tài khoản ngân hàng Việt Nam, hiện mã VietQR cho từng đơn, nhận webhook khi tiền về để đơn tự chuyển sang đã thanh toán.
4
+
5
+ Official BankOpenAPI SDK for Node.js, Next.js, Cloudflare Workers, Bun and Deno: bank-transfer payments with VietQR and signed payment webhooks in Vietnam. Zero dependencies, fully typed.
6
+
7
+ - Chạy trên Node.js 20+, Next.js (App Router, Pages Router, Edge), Cloudflare Workers, Bun, Deno. Không phụ thuộc gói nào.
8
+ - Kiểu TypeScript cho mọi đối tượng và sự kiện webhook.
9
+ - Tự thử lại khi lỗi mạng, 429, 5xx; tự gửi `Idempotency-Key` nên thử lại không bao giờ tạo trùng yêu cầu thanh toán.
10
+ - Verify webhook theo chuẩn Standard Webhooks, có sẵn hàm ký để viết test.
11
+
12
+ ## Cài đặt
13
+
14
+ ```bash
15
+ npm install bankopenapi
16
+ # hoặc: pnpm add bankopenapi · yarn add bankopenapi · bun add bankopenapi
17
+ ```
18
+
19
+ Lấy API key ở [app.bankopenapi.com/api-key](https://app.bankopenapi.com/api-key) rồi đặt vào biến môi trường của backend:
20
+
21
+ ```bash
22
+ BANKOPENAPI_API_KEY=boa_test_... # Sandbox: thử miễn phí, không cần tài khoản ngân hàng thật
23
+ BANKOPENAPI_WEBHOOK_SECRET=whsec_... # signing secret của webhook endpoint (trang Webhook trong app)
24
+ ```
25
+
26
+ API key là bí mật: chỉ dùng ở backend (route handler, server action, API route, Worker), không đưa vào code chạy trên trình duyệt. Thư viện báo lỗi nếu bị gọi trên trình duyệt.
27
+
28
+ ## Bắt đầu nhanh
29
+
30
+ ```ts
31
+ import BankOpenAPI from 'bankopenapi';
32
+
33
+ const boa = new BankOpenAPI(); // đọc BANKOPENAPI_API_KEY
34
+
35
+ // 1. Khách đặt đơn: tạo yêu cầu thanh toán
36
+ const pr = await boa.paymentRequests.create(
37
+ {
38
+ amount: 150000,
39
+ orderId: 'DH1028',
40
+ description: 'Đơn hàng DH1028',
41
+ returnUrl: 'https://shop.vn/don-hang/DH1028', // không bắt buộc: trang thanh toán có nút quay lại, trả xong tự chuyển về
42
+ },
43
+ { idempotencyKey: 'order-DH1028' }, // bấm hai lần cũng chỉ tạo một yêu cầu
44
+ );
45
+
46
+ // 2. Cho người mua trả tiền: chuyển tới trang thanh toán có sẵn...
47
+ console.log(pr.hostedUrl);
48
+ // ...hoặc tự vẽ mã QR trên trang của bạn (vd. npm install qrcode)
49
+ // const dataUrl = await QRCode.toDataURL(pr.qr!.payload);
50
+ // pr.transfer: ngân hàng, số tài khoản, số tiền, nội dung chuyển khoản (mã TT…) để hiện kèm QR
51
+
52
+ // 3. Tiền về đúng mã: BankOpenAPI gửi webhook payment_request.paid (xem mục Webhook)
53
+ ```
54
+
55
+ CommonJS: `const { BankOpenAPI } = require('bankopenapi');`
56
+
57
+ ## Webhook
58
+
59
+ BankOpenAPI `POST` tới URL bạn đăng ký mỗi khi có sự kiện. Luôn verify chữ ký trên **body thô** trước khi tin dữ liệu, trả `2xx` thật nhanh, và chống xử lý trùng theo `event.id` (một sự kiện có thể tới nhiều lần khi được gửi lại).
60
+
61
+ ### Next.js (App Router)
62
+
63
+ ```ts
64
+ // app/api/webhooks/bankopenapi/route.ts
65
+ import { verifyWebhook, WebhookVerificationError } from 'bankopenapi';
66
+
67
+ export async function POST(req: Request) {
68
+ const body = await req.text(); // body thô, đừng dùng req.json() trước khi verify
69
+ let event;
70
+ try {
71
+ event = await verifyWebhook(body, req.headers, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
72
+ } catch (err) {
73
+ if (err instanceof WebhookVerificationError) return new Response('Invalid signature', { status: 400 });
74
+ throw err;
75
+ }
76
+
77
+ if (await alreadyProcessed(event.id)) return new Response(null, { status: 200 });
78
+
79
+ switch (event.type) {
80
+ case 'payment_request.paid':
81
+ await markOrderPaid(event.data.orderId, event.data.amountReceived); // event.data là PaymentRequest
82
+ break;
83
+ case 'transaction.received':
84
+ console.log('Tiền về', event.data.amount, event.data.content); // event.data là Transaction
85
+ break;
86
+ }
87
+
88
+ await markProcessed(event.id);
89
+ return new Response(null, { status: 200 });
90
+ }
91
+ ```
92
+
93
+ ### Express
94
+
95
+ ```ts
96
+ import express from 'express';
97
+ import { verifyWebhook } from 'bankopenapi';
98
+
99
+ const app = express();
100
+
101
+ // express.raw giữ nguyên body thô; đặt route này trước app.use(express.json())
102
+ app.post('/webhooks/bankopenapi', express.raw({ type: 'application/json' }), async (req, res) => {
103
+ let event;
104
+ try {
105
+ event = await verifyWebhook(req.body, req.headers, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
106
+ } catch {
107
+ return res.status(400).send('Invalid signature');
108
+ }
109
+ if (event.type === 'payment_request.paid') await markOrderPaid(event.data.orderId);
110
+ res.sendStatus(200);
111
+ });
112
+ ```
113
+
114
+ `verifyWebhook` không cần API key, chỉ cần signing secret. Nếu đã có client thì dùng `boa.webhooks.verify(body, headers)` (đọc `BANKOPENAPI_WEBHOOK_SECRET`).
115
+
116
+ ### Các loại sự kiện
117
+
118
+ | `event.type` | `event.data` | Khi nào |
119
+ | --- | --- | --- |
120
+ | `payment_request.paid` | `PaymentRequest` | Yêu cầu nhận đủ tiền (`status` là `paid`, hoặc `overpaid` nếu chuyển thừa) |
121
+ | `payment_request.underpaid` | `PaymentRequest` | Nhận thiếu tiền; có thể đến nhiều lần khi người trả chuyển thêm |
122
+ | `transaction.received` | `Transaction` | Tiền vào một tài khoản đã liên kết, kể cả không thuộc đơn nào |
123
+ | `bank_account.linked`, `bank_account.removed` | `BankAccount` | Liên kết hoặc hủy liên kết tài khoản ngân hàng |
124
+ | `webhook.test` | `{ message, endpointId, livemode }` | Tin gửi thử |
125
+
126
+ ### Viết test cho endpoint webhook
127
+
128
+ ```ts
129
+ import { signWebhook } from 'bankopenapi';
130
+
131
+ const body = JSON.stringify({ id: 'evt_test_1', type: 'payment_request.paid', livemode: false, timestamp: new Date().toISOString(), data: { orderId: 'DH1028' } });
132
+ const headers = await signWebhook(body, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
133
+ await fetch('http://localhost:3000/api/webhooks/bankopenapi', { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body });
134
+ ```
135
+
136
+ ## Sandbox
137
+
138
+ Dùng API key `boa_test_…` để thử toàn bộ luồng mà không cần tài khoản ngân hàng thật, không tốn phí. Webhook vẫn được gửi thật với `livemode: false`.
139
+
140
+ ```ts
141
+ const boa = new BankOpenAPI({ apiKey: process.env.BANKOPENAPI_TEST_KEY });
142
+
143
+ await boa.sandbox.createBankAccount(); // tài khoản ngân hàng thử, liên kết xong ngay
144
+ const pr = await boa.paymentRequests.create({ amount: 150000, orderId: 'DH1028' });
145
+ await boa.sandbox.payPaymentRequest(pr.id); // người mua "chuyển khoản": yêu cầu thành paid, webhook được gửi
146
+ await boa.sandbox.createTransaction({ amount: 50000, content: 'chuyen tien' }); // tiền vào không thuộc đơn nào
147
+ ```
148
+
149
+ ## Danh sách và phân trang
150
+
151
+ Hàm `list()` trả một trang khi `await`, hoặc duyệt hết mọi trang bằng `for await`:
152
+
153
+ ```ts
154
+ const page = await boa.transactions.list({ type: 'credit', limit: 20 });
155
+ console.log(page.data, page.hasMore);
156
+
157
+ for await (const tx of boa.transactions.list({ type: 'credit', from: '2026-11-01' })) {
158
+ console.log(tx.transactedAt, tx.amount, tx.content);
159
+ }
160
+ ```
161
+
162
+ ## Các hàm
163
+
164
+ | Nhóm | Hàm |
165
+ | --- | --- |
166
+ | `boa.paymentRequests` | `create`, `retrieve`, `list({ status, orderId })`, `cancel` |
167
+ | `boa.transactions` | `list({ bankAccountId, type, from, to })`, `retrieve` |
168
+ | `boa.bankAccounts` | `list`, `retrieve` (liên kết tài khoản mới làm trong app vì cần OTP của ngân hàng) |
169
+ | `boa.webhookEndpoints` | `create`, `retrieve`, `update`, `delete`, `list`, `retrieveSecret`, `rotateSecret`, `sendTest`, `testUrl`, `listDeliveries`, `retrieveDelivery`, `retryDelivery`, `retryFailed` |
170
+ | `boa.events` | `list({ type })`, `retrieve`, `resend` |
171
+ | `boa.account` | `retrieve` (thử API key) |
172
+ | `boa.sandbox` | `createBankAccount`, `createTransaction`, `payPaymentRequest` |
173
+ | `boa.webhooks` | `verify`, `sign` |
174
+
175
+ Tham số và đối tượng trả về có đủ kiểu TypeScript; chi tiết từng trường: [tài liệu API](https://bankopenapi.com/tai-lieu).
176
+
177
+ ## Lỗi
178
+
179
+ Mọi lỗi từ API là `BankOpenAPIError` (hoặc lớp con), có `code` (vd. `INVALID_AMOUNT`), `status`, `message` tiếng Việt và `requestId` để gửi kèm khi cần hỗ trợ.
180
+
181
+ ```ts
182
+ import { BankOpenAPIError, NotFoundError } from 'bankopenapi';
183
+
184
+ try {
185
+ await boa.paymentRequests.retrieve(id);
186
+ } catch (err) {
187
+ if (err instanceof NotFoundError) return null;
188
+ if (err instanceof BankOpenAPIError) console.error(err.code, err.message, err.requestId);
189
+ throw err;
190
+ }
191
+ ```
192
+
193
+ Lớp con: `InvalidRequestError` (400, 422), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429), `InternalServerError` (5xx), `APIConnectionError`, `APITimeoutError`. Danh sách mã lỗi: [bankopenapi.com/tai-lieu/loi](https://bankopenapi.com/tai-lieu/loi).
194
+
195
+ ## Cấu hình
196
+
197
+ ```ts
198
+ const boa = new BankOpenAPI({
199
+ apiKey: env.BANKOPENAPI_API_KEY, // bắt buộc truyền khi không có process.env (vd. Cloudflare Workers)
200
+ webhookSecret: env.BANKOPENAPI_WEBHOOK_SECRET,
201
+ timeout: 30_000, // mili giây mỗi lần gọi
202
+ maxRetries: 2, // tự thử lại khi lỗi mạng, 429, 5xx
203
+ });
204
+ ```
205
+
206
+ Mỗi hàm nhận thêm tham số cuối `{ idempotencyKey, signal, timeout, maxRetries }`. Giới hạn: 100 request mỗi phút cho mỗi API key.
207
+
208
+ ## Dùng với AI agent
209
+
210
+ Cài skill BankOpenAPI để Claude Code, Cursor, Codex viết code tích hợp đúng tài liệu: `npx skills add bankopenapi/skills`. MCP server và cách cấu hình: [bankopenapi.com/tai-lieu/ai-agent](https://bankopenapi.com/tai-lieu/ai-agent).
211
+
212
+ ## Hỗ trợ
213
+
214
+ Tài liệu: [bankopenapi.com/tai-lieu](https://bankopenapi.com/tai-lieu). Góp ý, báo lỗi: [teams@bankopenapi.com](mailto:teams@bankopenapi.com).
215
+
216
+ ## License
217
+
218
+ MIT
@@ -0,0 +1,52 @@
1
+ export declare const VERSION = "0.2.0";
2
+ export declare const DEFAULT_BASE_URL = "https://app.bankopenapi.com/api/v1";
3
+ export interface ClientOptions {
4
+ /** API key `boa_live_…` (tiền thật) hoặc `boa_test_…` (Sandbox). Mặc định đọc biến môi trường `BANKOPENAPI_API_KEY` */
5
+ apiKey?: string;
6
+ /** Signing secret của webhook endpoint (`whsec_…`), dùng cho `webhooks.verify`. Mặc định đọc `BANKOPENAPI_WEBHOOK_SECRET` */
7
+ webhookSecret?: string;
8
+ /** Mặc định `https://app.bankopenapi.com/api/v1` (hoặc biến môi trường `BANKOPENAPI_BASE_URL`) */
9
+ baseURL?: string;
10
+ /** Thời gian chờ mỗi lần gọi, mili giây. Mặc định 30 000 */
11
+ timeout?: number;
12
+ /** Số lần tự thử lại khi lỗi mạng, 429 hoặc 5xx. Mặc định 2 */
13
+ maxRetries?: number;
14
+ /** Hàm fetch riêng (vd. để test). Mặc định `globalThis.fetch` */
15
+ fetch?: typeof fetch;
16
+ /**
17
+ * API key là bí mật, chỉ dùng ở backend. Thư viện báo lỗi khi chạy trên trình duyệt; đặt `true` nếu bạn hiểu rủi ro
18
+ * (vd. công cụ nội bộ chạy trên máy của chính bạn).
19
+ */
20
+ dangerouslyAllowBrowser?: boolean;
21
+ }
22
+ export interface RequestOptions {
23
+ /**
24
+ * Khóa chống trùng cho lệnh tạo (POST). Gửi lại cùng khóa trong 24 giờ thì nhận lại đúng kết quả lần đầu, không tạo
25
+ * thêm. Không truyền thì thư viện tự sinh một khóa cho mỗi lần gọi (dùng lại khi tự thử lại). Nên truyền khóa gắn với
26
+ * đơn hàng của bạn, vd. `order-${orderId}`, để bấm hai lần cũng chỉ tạo một yêu cầu thanh toán.
27
+ */
28
+ idempotencyKey?: string;
29
+ /** Hủy request */
30
+ signal?: AbortSignal;
31
+ timeout?: number;
32
+ maxRetries?: number;
33
+ }
34
+ type QueryValue = string | number | boolean | Date | null | undefined;
35
+ export type Query = Record<string, QueryValue>;
36
+ interface InternalRequest extends RequestOptions {
37
+ query?: Query;
38
+ body?: unknown;
39
+ }
40
+ export declare class APIClient {
41
+ readonly apiKey: string;
42
+ readonly baseURL: string;
43
+ readonly webhookSecret: string | undefined;
44
+ readonly timeout: number;
45
+ readonly maxRetries: number;
46
+ private readonly fetchImpl;
47
+ constructor(options?: ClientOptions);
48
+ /** true với khóa `boa_live_` (tiền thật), false với khóa Sandbox `boa_test_` */
49
+ get livemode(): boolean;
50
+ request<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, options?: InternalRequest): Promise<T>;
51
+ }
52
+ export {};
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.APIClient = exports.DEFAULT_BASE_URL = exports.VERSION = void 0;
4
+ const errors_ts_1 = require("./errors.js");
5
+ exports.VERSION = '0.2.0';
6
+ exports.DEFAULT_BASE_URL = 'https://app.bankopenapi.com/api/v1';
7
+ function readEnv(name) {
8
+ const g = globalThis;
9
+ try {
10
+ return g.process?.env?.[name]?.trim() || g.Deno?.env?.get(name)?.trim() || undefined;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
17
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
+ /** Chờ trước lần thử lại thứ `attempt` (0, 1, …): theo Retry-After nếu có, không thì 0,5 s · 2^n kèm nhiễu, tối đa 8 s */
19
+ function retryDelay(attempt, headers) {
20
+ const retryAfter = Number(headers?.get('retry-after'));
21
+ if (Number.isFinite(retryAfter) && retryAfter > 0 && retryAfter <= 60)
22
+ return retryAfter * 1000;
23
+ const base = Math.min(500 * 2 ** attempt, 8000);
24
+ return base * (0.75 + Math.random() * 0.5);
25
+ }
26
+ const shouldRetry = (status) => status === 408 || status === 429 || status >= 500;
27
+ function serializeQuery(query) {
28
+ const params = new URLSearchParams();
29
+ for (const [key, value] of Object.entries(query ?? {})) {
30
+ if (value === undefined || value === null)
31
+ continue;
32
+ params.set(key, value instanceof Date ? value.toISOString() : String(value));
33
+ }
34
+ const s = params.toString();
35
+ return s ? `?${s}` : '';
36
+ }
37
+ class APIClient {
38
+ apiKey;
39
+ baseURL;
40
+ webhookSecret;
41
+ timeout;
42
+ maxRetries;
43
+ fetchImpl;
44
+ constructor(options = {}) {
45
+ const apiKey = options.apiKey ?? readEnv('BANKOPENAPI_API_KEY');
46
+ if (!apiKey)
47
+ throw new errors_ts_1.BankOpenAPIError('Thiếu API key. Truyền { apiKey } hoặc đặt biến môi trường BANKOPENAPI_API_KEY (tạo khóa ở https://app.bankopenapi.com/api-key). / Missing API key.', { code: 'MISSING_API_KEY' });
48
+ if (!/^boa_(live|test)_[0-9A-Za-z]+$/.test(apiKey))
49
+ throw new errors_ts_1.BankOpenAPIError('API key phải có dạng boa_live_… hoặc boa_test_…. / API key must start with boa_live_ or boa_test_.', { code: 'INVALID_API_KEY' });
50
+ if (isBrowser() && !options.dangerouslyAllowBrowser)
51
+ throw new errors_ts_1.BankOpenAPIError('Không dùng API key BankOpenAPI trên trình duyệt: ai mở trang cũng đọc được khóa. Gọi API từ backend (route handler, server action, API route). / Do not use your API key in the browser.', { code: 'BROWSER_NOT_ALLOWED' });
52
+ const fetchImpl = options.fetch ?? globalThis.fetch;
53
+ if (typeof fetchImpl !== 'function')
54
+ throw new errors_ts_1.BankOpenAPIError('Môi trường này không có fetch: cần Node.js 20 trở lên. / fetch is not available: use Node.js 20+.', { code: 'NO_FETCH' });
55
+ this.apiKey = apiKey;
56
+ this.baseURL = (options.baseURL ?? readEnv('BANKOPENAPI_BASE_URL') ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
57
+ this.webhookSecret = options.webhookSecret ?? readEnv('BANKOPENAPI_WEBHOOK_SECRET');
58
+ this.timeout = options.timeout ?? 30_000;
59
+ this.maxRetries = options.maxRetries ?? 2;
60
+ this.fetchImpl = fetchImpl.bind(globalThis);
61
+ }
62
+ /** true với khóa `boa_live_` (tiền thật), false với khóa Sandbox `boa_test_` */
63
+ get livemode() {
64
+ return this.apiKey.startsWith('boa_live_');
65
+ }
66
+ async request(method, path, options = {}) {
67
+ const url = this.baseURL + path + serializeQuery(options.query);
68
+ const headers = {
69
+ Authorization: `Bearer ${this.apiKey}`,
70
+ Accept: 'application/json',
71
+ };
72
+ if (!isBrowser())
73
+ headers['User-Agent'] = `bankopenapi-js/${exports.VERSION}`;
74
+ if (options.body !== undefined)
75
+ headers['Content-Type'] = 'application/json';
76
+ // Một khóa cho mọi lần thử lại của cùng một lệnh tạo: thử lại không bao giờ tạo bản ghi thứ hai
77
+ if (method === 'POST')
78
+ headers['Idempotency-Key'] = options.idempotencyKey ?? `bankopenapi-js-${crypto.randomUUID()}`;
79
+ const body = options.body === undefined ? undefined : JSON.stringify(options.body);
80
+ const maxRetries = options.maxRetries ?? this.maxRetries;
81
+ const timeout = options.timeout ?? this.timeout;
82
+ for (let attempt = 0;; attempt++) {
83
+ const controller = new AbortController();
84
+ let timedOut = false;
85
+ const timer = setTimeout(() => {
86
+ timedOut = true;
87
+ controller.abort();
88
+ }, timeout);
89
+ const onAbort = () => controller.abort();
90
+ options.signal?.addEventListener('abort', onAbort, { once: true });
91
+ let res;
92
+ try {
93
+ res = await this.fetchImpl(url, { method, headers, body, signal: controller.signal });
94
+ }
95
+ catch (cause) {
96
+ if (options.signal?.aborted)
97
+ throw cause;
98
+ const err = timedOut
99
+ ? new errors_ts_1.APITimeoutError(`Quá ${timeout / 1000} giây không có phản hồi từ BankOpenAPI. / Request timed out.`, { code: 'TIMEOUT', cause })
100
+ : new errors_ts_1.APIConnectionError('Không kết nối được tới BankOpenAPI. Kiểm tra mạng rồi thử lại. / Connection error.', { code: 'CONNECTION_ERROR', cause });
101
+ if (attempt < maxRetries) {
102
+ await sleep(retryDelay(attempt));
103
+ continue;
104
+ }
105
+ throw err;
106
+ }
107
+ finally {
108
+ clearTimeout(timer);
109
+ options.signal?.removeEventListener('abort', onAbort);
110
+ }
111
+ if (res.ok) {
112
+ if (res.status === 204)
113
+ return undefined;
114
+ return (await res.json());
115
+ }
116
+ const json = (await res.json().catch(() => null));
117
+ const message = json?.error?.message ?? `BankOpenAPI trả HTTP ${res.status}.`;
118
+ const err = (0, errors_ts_1.errorForStatus)(res.status, message, {
119
+ code: json?.error?.code ?? `HTTP_${res.status}`,
120
+ requestId: res.headers.get('request-id') ?? undefined,
121
+ headers: res.headers,
122
+ });
123
+ if (shouldRetry(res.status) && attempt < maxRetries) {
124
+ await sleep(retryDelay(attempt, res.headers));
125
+ continue;
126
+ }
127
+ throw err;
128
+ }
129
+ }
130
+ }
131
+ exports.APIClient = APIClient;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Lỗi của thư viện. Mọi lỗi từ API đều là `BankOpenAPIError` (hoặc lớp con theo mã HTTP), có `code` giống trường
3
+ * `error.code` trong phản hồi (vd. `INVALID_API_KEY`, `NOT_FOUND`), `message` là câu tiếng Việt từ BankOpenAPI.
4
+ *
5
+ * Errors thrown by the library. API errors are `BankOpenAPIError` (or a subclass by HTTP status) with `code` matching
6
+ * the response's `error.code`.
7
+ */
8
+ export interface ErrorDetails {
9
+ status?: number;
10
+ code?: string;
11
+ requestId?: string;
12
+ headers?: Headers;
13
+ cause?: unknown;
14
+ }
15
+ export declare class BankOpenAPIError extends Error {
16
+ /** Mã HTTP, không có với lỗi kết nối */
17
+ readonly status: number | undefined;
18
+ /** Mã lỗi, vd. `INVALID_API_KEY`, `VALIDATION_ERROR`, `RATE_LIMITED`; lỗi kết nối là `CONNECTION_ERROR` */
19
+ readonly code: string;
20
+ /** Header `Request-ID` của request lỗi: gửi kèm khi cần hỗ trợ */
21
+ readonly requestId: string | undefined;
22
+ readonly headers: Headers | undefined;
23
+ constructor(message: string, details?: ErrorDetails);
24
+ }
25
+ /** 400, 422: tham số sai */
26
+ export declare class InvalidRequestError extends BankOpenAPIError {
27
+ }
28
+ /** 401: thiếu hoặc sai API key, khóa hết hạn */
29
+ export declare class AuthenticationError extends BankOpenAPIError {
30
+ }
31
+ /** 403: khóa chỉ đọc gọi lệnh ghi, IP ngoài danh sách cho phép */
32
+ export declare class PermissionDeniedError extends BankOpenAPIError {
33
+ }
34
+ /** 404 */
35
+ export declare class NotFoundError extends BankOpenAPIError {
36
+ }
37
+ /** 409: trạng thái không cho phép (vd. hủy yêu cầu đã thanh toán), Idempotency-Key dùng lại với body khác */
38
+ export declare class ConflictError extends BankOpenAPIError {
39
+ }
40
+ /** 429: gọi quá nhanh; thư viện đã tự thử lại theo `Retry-After` trước khi ném lỗi này */
41
+ export declare class RateLimitError extends BankOpenAPIError {
42
+ }
43
+ /** 5xx */
44
+ export declare class InternalServerError extends BankOpenAPIError {
45
+ }
46
+ /** Không kết nối được tới BankOpenAPI (mạng, DNS…) */
47
+ export declare class APIConnectionError extends BankOpenAPIError {
48
+ }
49
+ /** Quá thời gian chờ phản hồi (`timeout`) */
50
+ export declare class APITimeoutError extends APIConnectionError {
51
+ }
52
+ /** Webhook sai chữ ký, thiếu header hoặc timestamp quá cũ */
53
+ export declare class WebhookVerificationError extends Error {
54
+ constructor(message: string);
55
+ }
56
+ export declare function errorForStatus(status: number, message: string, details: ErrorDetails): BankOpenAPIError;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * Lỗi của thư viện. Mọi lỗi từ API đều là `BankOpenAPIError` (hoặc lớp con theo mã HTTP), có `code` giống trường
4
+ * `error.code` trong phản hồi (vd. `INVALID_API_KEY`, `NOT_FOUND`), `message` là câu tiếng Việt từ BankOpenAPI.
5
+ *
6
+ * Errors thrown by the library. API errors are `BankOpenAPIError` (or a subclass by HTTP status) with `code` matching
7
+ * the response's `error.code`.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.WebhookVerificationError = exports.APITimeoutError = exports.APIConnectionError = exports.InternalServerError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.InvalidRequestError = exports.BankOpenAPIError = void 0;
11
+ exports.errorForStatus = errorForStatus;
12
+ class BankOpenAPIError extends Error {
13
+ /** Mã HTTP, không có với lỗi kết nối */
14
+ status;
15
+ /** Mã lỗi, vd. `INVALID_API_KEY`, `VALIDATION_ERROR`, `RATE_LIMITED`; lỗi kết nối là `CONNECTION_ERROR` */
16
+ code;
17
+ /** Header `Request-ID` của request lỗi: gửi kèm khi cần hỗ trợ */
18
+ requestId;
19
+ headers;
20
+ constructor(message, details = {}) {
21
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
22
+ this.name = new.target.name;
23
+ this.status = details.status;
24
+ this.code = details.code ?? 'UNKNOWN_ERROR';
25
+ this.requestId = details.requestId;
26
+ this.headers = details.headers;
27
+ }
28
+ }
29
+ exports.BankOpenAPIError = BankOpenAPIError;
30
+ /** 400, 422: tham số sai */
31
+ class InvalidRequestError extends BankOpenAPIError {
32
+ }
33
+ exports.InvalidRequestError = InvalidRequestError;
34
+ /** 401: thiếu hoặc sai API key, khóa hết hạn */
35
+ class AuthenticationError extends BankOpenAPIError {
36
+ }
37
+ exports.AuthenticationError = AuthenticationError;
38
+ /** 403: khóa chỉ đọc gọi lệnh ghi, IP ngoài danh sách cho phép */
39
+ class PermissionDeniedError extends BankOpenAPIError {
40
+ }
41
+ exports.PermissionDeniedError = PermissionDeniedError;
42
+ /** 404 */
43
+ class NotFoundError extends BankOpenAPIError {
44
+ }
45
+ exports.NotFoundError = NotFoundError;
46
+ /** 409: trạng thái không cho phép (vd. hủy yêu cầu đã thanh toán), Idempotency-Key dùng lại với body khác */
47
+ class ConflictError extends BankOpenAPIError {
48
+ }
49
+ exports.ConflictError = ConflictError;
50
+ /** 429: gọi quá nhanh; thư viện đã tự thử lại theo `Retry-After` trước khi ném lỗi này */
51
+ class RateLimitError extends BankOpenAPIError {
52
+ }
53
+ exports.RateLimitError = RateLimitError;
54
+ /** 5xx */
55
+ class InternalServerError extends BankOpenAPIError {
56
+ }
57
+ exports.InternalServerError = InternalServerError;
58
+ /** Không kết nối được tới BankOpenAPI (mạng, DNS…) */
59
+ class APIConnectionError extends BankOpenAPIError {
60
+ }
61
+ exports.APIConnectionError = APIConnectionError;
62
+ /** Quá thời gian chờ phản hồi (`timeout`) */
63
+ class APITimeoutError extends APIConnectionError {
64
+ }
65
+ exports.APITimeoutError = APITimeoutError;
66
+ /** Webhook sai chữ ký, thiếu header hoặc timestamp quá cũ */
67
+ class WebhookVerificationError extends Error {
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = 'WebhookVerificationError';
71
+ }
72
+ }
73
+ exports.WebhookVerificationError = WebhookVerificationError;
74
+ function errorForStatus(status, message, details) {
75
+ const d = { ...details, status };
76
+ if (status === 400 || status === 422)
77
+ return new InvalidRequestError(message, d);
78
+ if (status === 401)
79
+ return new AuthenticationError(message, d);
80
+ if (status === 403)
81
+ return new PermissionDeniedError(message, d);
82
+ if (status === 404)
83
+ return new NotFoundError(message, d);
84
+ if (status === 409)
85
+ return new ConflictError(message, d);
86
+ if (status === 429)
87
+ return new RateLimitError(message, d);
88
+ if (status >= 500)
89
+ return new InternalServerError(message, d);
90
+ return new BankOpenAPIError(message, d);
91
+ }
@@ -0,0 +1,60 @@
1
+ import { type ClientOptions } from './core.js';
2
+ import { AccountResource, BankAccounts, Events, PaymentRequests, Sandbox, Transactions, WebhookEndpoints } from './resources.js';
3
+ import type { WebhookEvent } from './types.js';
4
+ import { type VerifyOptions, type WebhookHeaders } from './webhooks.js';
5
+ /**
6
+ * Thư viện chính thức của BankOpenAPI: nhận tiền chuyển khoản vào tài khoản ngân hàng Việt Nam, hiện VietQR, nhận
7
+ * webhook khi tiền về. Tài liệu: https://bankopenapi.com/tai-lieu
8
+ *
9
+ * @example
10
+ * import BankOpenAPI from 'bankopenapi';
11
+ *
12
+ * const boa = new BankOpenAPI(); // đọc BANKOPENAPI_API_KEY
13
+ * const pr = await boa.paymentRequests.create({ amount: 150000, orderId: 'DH1028' }, { idempotencyKey: 'order-DH1028' });
14
+ * // Hiện pr.qr.payload thành mã QR, hoặc chuyển người mua tới pr.hostedUrl
15
+ */
16
+ export declare class BankOpenAPI {
17
+ readonly account: AccountResource;
18
+ readonly paymentRequests: PaymentRequests;
19
+ readonly transactions: Transactions;
20
+ readonly bankAccounts: BankAccounts;
21
+ readonly webhookEndpoints: WebhookEndpoints;
22
+ readonly events: Events;
23
+ /** Giả lập tiền về, thanh toán, tài khoản ngân hàng thử: chỉ với API key `boa_test_…` */
24
+ readonly sandbox: Sandbox;
25
+ readonly webhooks: Webhooks;
26
+ private readonly client;
27
+ /**
28
+ * @param options API key (mặc định biến môi trường `BANKOPENAPI_API_KEY`), signing secret webhook, timeout, số lần thử lại.
29
+ * Truyền chuỗi thì coi là API key.
30
+ */
31
+ constructor(options?: ClientOptions | string);
32
+ /** true với khóa `boa_live_` (tiền thật), false với khóa Sandbox `boa_test_` */
33
+ get livemode(): boolean;
34
+ }
35
+ export declare class Webhooks {
36
+ private readonly secret;
37
+ constructor(secret: string | undefined);
38
+ private secretOrThrow;
39
+ /**
40
+ * Kiểm chữ ký webhook rồi trả sự kiện. Truyền **body thô** (`await req.text()`, `express.raw()`), không parse trước.
41
+ * Sai chữ ký thì ném `WebhookVerificationError`: trả HTTP 400.
42
+ */
43
+ verify(payload: string | ArrayBuffer | Uint8Array, headers: WebhookHeaders, secret?: string, options?: VerifyOptions): Promise<WebhookEvent>;
44
+ /** Ký payload như BankOpenAPI gửi, để viết test cho endpoint nhận webhook */
45
+ sign(payload: string, secret?: string, options?: {
46
+ id?: string;
47
+ timestamp?: Date;
48
+ }): Promise<{
49
+ 'webhook-id': string;
50
+ 'webhook-timestamp': string;
51
+ 'webhook-signature': string;
52
+ }>;
53
+ }
54
+ export default BankOpenAPI;
55
+ export { VERSION, type ClientOptions, type RequestOptions } from './core.js';
56
+ export * from './errors.js';
57
+ export type { PagePromise } from './pagination.js';
58
+ export type * from './resources.js';
59
+ export type * from './types.js';
60
+ export { signWebhook, verifyWebhook, type VerifyOptions, type WebhookHeaders } from './webhooks.js';