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 +21 -0
- package/README.md +217 -2
- package/dist/cjs/core.d.ts +52 -0
- package/dist/cjs/core.js +131 -0
- package/dist/cjs/errors.d.ts +56 -0
- package/dist/cjs/errors.js +91 -0
- package/dist/cjs/index.d.ts +60 -0
- package/dist/cjs/index.js +95 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +13 -0
- package/dist/cjs/pagination.js +18 -0
- package/dist/cjs/resources.d.ts +219 -0
- package/dist/cjs/resources.js +192 -0
- package/dist/cjs/types.d.ts +198 -0
- package/dist/cjs/types.js +4 -0
- package/dist/cjs/webhooks.d.ts +42 -0
- package/dist/cjs/webhooks.js +98 -0
- package/dist/esm/core.d.ts +52 -0
- package/dist/esm/core.js +127 -0
- package/dist/esm/errors.d.ts +56 -0
- package/dist/esm/errors.js +76 -0
- package/dist/esm/index.d.ts +60 -0
- package/dist/esm/index.js +73 -0
- package/dist/esm/pagination.d.ts +13 -0
- package/dist/esm/pagination.js +15 -0
- package/dist/esm/resources.d.ts +219 -0
- package/dist/esm/resources.js +182 -0
- package/dist/esm/types.d.ts +198 -0
- package/dist/esm/types.js +3 -0
- package/dist/esm/webhooks.d.ts +42 -0
- package/dist/esm/webhooks.js +94 -0
- package/package.json +58 -4
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** Danh sách. `hasMore` chỉ có ở danh sách phân trang (yêu cầu thanh toán, giao dịch, sự kiện, lần gửi webhook) */
|
|
2
|
+
export interface List<T> {
|
|
3
|
+
object: 'list';
|
|
4
|
+
data: T[];
|
|
5
|
+
hasMore?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** Tài khoản ngân hàng gắn kèm trong yêu cầu thanh toán và giao dịch */
|
|
8
|
+
export interface BankAccountRef {
|
|
9
|
+
id: string;
|
|
10
|
+
bank: {
|
|
11
|
+
bin: string;
|
|
12
|
+
name: string | null;
|
|
13
|
+
};
|
|
14
|
+
accountNumber: string | null;
|
|
15
|
+
/** vd. "MB Bank •••• 6789" */
|
|
16
|
+
label: string;
|
|
17
|
+
}
|
|
18
|
+
export type PaymentRequestStatus = 'pending' | 'paid' | 'underpaid' | 'overpaid' | 'expired' | 'canceled';
|
|
19
|
+
export interface PaymentRequest {
|
|
20
|
+
/** pr_… */
|
|
21
|
+
id: string;
|
|
22
|
+
object: 'payment_request';
|
|
23
|
+
livemode: boolean;
|
|
24
|
+
amount: number;
|
|
25
|
+
amountReceived: number;
|
|
26
|
+
currency: 'VND';
|
|
27
|
+
/** `expired`: quá `expiresAt` mà chưa nhận đủ tiền */
|
|
28
|
+
status: PaymentRequestStatus;
|
|
29
|
+
/** Mã ghi trong nội dung chuyển khoản, vd. "TT7K3M9Q" */
|
|
30
|
+
code: string;
|
|
31
|
+
orderId: string | null;
|
|
32
|
+
description: string | null;
|
|
33
|
+
bankAccount: BankAccountRef;
|
|
34
|
+
/** Thông tin chuyển khoản (số tiền còn thiếu, nội dung = code) để hiện cho người trả hoặc tự dựng VietQR */
|
|
35
|
+
transfer: {
|
|
36
|
+
bankBin: string;
|
|
37
|
+
accountNumber: string;
|
|
38
|
+
accountName: string | null;
|
|
39
|
+
/** Số tiền còn phải trả */
|
|
40
|
+
amount: number;
|
|
41
|
+
content: string;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Chuỗi QR để vẽ ảnh (vd. `qrcode.toDataURL(qr.payload)`): QR động một lần của ngân hàng nếu tài khoản hỗ trợ, không thì
|
|
45
|
+
* VietQR tĩnh. null khi yêu cầu không còn nhận tiền.
|
|
46
|
+
*/
|
|
47
|
+
qr: {
|
|
48
|
+
type: 'dynamic';
|
|
49
|
+
payload: string;
|
|
50
|
+
expiresAt: string;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'static';
|
|
53
|
+
payload: string;
|
|
54
|
+
expiresAt: null;
|
|
55
|
+
} | null;
|
|
56
|
+
/** Trang thanh toán của BankOpenAPI để gửi cho người trả (QR, thông tin chuyển khoản, tự cập nhật khi tiền về) */
|
|
57
|
+
hostedUrl: string;
|
|
58
|
+
/** Link quay lại website người bán sau khi trả xong (đặt lúc tạo); null nếu không đặt */
|
|
59
|
+
returnUrl: string | null;
|
|
60
|
+
paymentLinkId: string | null;
|
|
61
|
+
expiresAt: string;
|
|
62
|
+
paidAt: string | null;
|
|
63
|
+
canceledAt: string | null;
|
|
64
|
+
createdAt: string;
|
|
65
|
+
/** Giao dịch đã khớp. Chỉ có khi `retrieve`, `cancel` và `sandbox.payPaymentRequest` */
|
|
66
|
+
transactions?: {
|
|
67
|
+
id: string;
|
|
68
|
+
amount: number;
|
|
69
|
+
content: string | null;
|
|
70
|
+
transactedAt: string;
|
|
71
|
+
}[];
|
|
72
|
+
}
|
|
73
|
+
export interface Transaction {
|
|
74
|
+
/** txn_… */
|
|
75
|
+
id: string;
|
|
76
|
+
object: 'transaction';
|
|
77
|
+
livemode: boolean;
|
|
78
|
+
/** credit: tiền vào, debit: tiền ra */
|
|
79
|
+
type: 'credit' | 'debit';
|
|
80
|
+
amount: number;
|
|
81
|
+
currency: 'VND';
|
|
82
|
+
/** Nội dung chuyển khoản */
|
|
83
|
+
content: string | null;
|
|
84
|
+
/** Mã giao dịch của ngân hàng */
|
|
85
|
+
reference: string;
|
|
86
|
+
/** Số nhận báo có (tài khoản định danh hoặc số tài khoản) */
|
|
87
|
+
receivingNumber: string | null;
|
|
88
|
+
/** Yêu cầu thanh toán đã khớp, nếu có */
|
|
89
|
+
paymentRequestId: string | null;
|
|
90
|
+
/** Lúc đã báo có (webhook, kênh). null: chưa báo vì đang tạm dừng báo có */
|
|
91
|
+
notifiedAt: string | null;
|
|
92
|
+
bankAccount: BankAccountRef;
|
|
93
|
+
transactedAt: string;
|
|
94
|
+
createdAt: string;
|
|
95
|
+
}
|
|
96
|
+
export interface BankAccount {
|
|
97
|
+
/** ba_… */
|
|
98
|
+
id: string;
|
|
99
|
+
object: 'bank_account';
|
|
100
|
+
livemode: boolean;
|
|
101
|
+
bank: {
|
|
102
|
+
bin: string;
|
|
103
|
+
code: string | null;
|
|
104
|
+
name: string | null;
|
|
105
|
+
};
|
|
106
|
+
accountType: 'personal-account' | 'business-household-account' | 'business-account';
|
|
107
|
+
accountNumber: string | null;
|
|
108
|
+
accountName: string | null;
|
|
109
|
+
receivingNumber: string | null;
|
|
110
|
+
notifyRealAccount: boolean;
|
|
111
|
+
status: 'pending' | 'active' | 'failed' | 'removed';
|
|
112
|
+
pendingStep: 'link' | 'notify' | 'unlink' | 'bank-app' | 'bank-web' | 'unlink-web' | null;
|
|
113
|
+
linkedAt: string | null;
|
|
114
|
+
createdAt: string;
|
|
115
|
+
}
|
|
116
|
+
export interface Account {
|
|
117
|
+
object: 'account';
|
|
118
|
+
id: string;
|
|
119
|
+
email: string;
|
|
120
|
+
name: string;
|
|
121
|
+
createdAt: string;
|
|
122
|
+
}
|
|
123
|
+
export type WebhookEventType = 'transaction.received' | 'payment_request.paid' | 'payment_request.underpaid' | 'bank_account.linked' | 'bank_account.removed';
|
|
124
|
+
export interface WebhookEndpoint {
|
|
125
|
+
/** we_… */
|
|
126
|
+
id: string;
|
|
127
|
+
object: 'webhook_endpoint';
|
|
128
|
+
livemode: boolean;
|
|
129
|
+
url: string;
|
|
130
|
+
description: string | null;
|
|
131
|
+
/** `['*']` là mọi loại sự kiện */
|
|
132
|
+
events: (WebhookEventType | '*')[];
|
|
133
|
+
/** null: mọi tài khoản ngân hàng */
|
|
134
|
+
bankAccountIds: string[] | null;
|
|
135
|
+
/** Tên header tùy chỉnh (giá trị không bao giờ trả về) */
|
|
136
|
+
headerNames: string[];
|
|
137
|
+
status: 'enabled' | 'disabled';
|
|
138
|
+
/** manual: tự tắt; gone: endpoint trả 410; failing: lỗi liên tục 5 ngày */
|
|
139
|
+
disabledReason: 'manual' | 'gone' | 'failing' | null;
|
|
140
|
+
statusChangedAt: string | null;
|
|
141
|
+
/** Secret cũ còn ký song song tới lúc này (sau khi rotate) */
|
|
142
|
+
previousSecretExpiresAt: string | null;
|
|
143
|
+
createdAt: string;
|
|
144
|
+
}
|
|
145
|
+
export interface WebhookDelivery {
|
|
146
|
+
/** whd_… */
|
|
147
|
+
id: string;
|
|
148
|
+
object: 'webhook_delivery';
|
|
149
|
+
endpointId: string;
|
|
150
|
+
eventId: string;
|
|
151
|
+
eventType: string;
|
|
152
|
+
status: 'pending' | 'succeeded' | 'failed';
|
|
153
|
+
attempts: number;
|
|
154
|
+
responseStatus: number | null;
|
|
155
|
+
error: string | null;
|
|
156
|
+
durationMs: number | null;
|
|
157
|
+
nextAttemptAt: string | null;
|
|
158
|
+
createdAt: string;
|
|
159
|
+
updatedAt: string;
|
|
160
|
+
/** Body JSON đã ký (chuỗi), chỉ có ở xem chi tiết */
|
|
161
|
+
payload?: string;
|
|
162
|
+
/** 1 KB đầu phản hồi của endpoint, chỉ có ở xem chi tiết */
|
|
163
|
+
responseBody?: string | null;
|
|
164
|
+
endpointUrl?: string;
|
|
165
|
+
}
|
|
166
|
+
/** Sự kiện đọc qua API (`events.list`, `events.retrieve`). Khác payload webhook: có `object`, `createdAt` */
|
|
167
|
+
export interface Event {
|
|
168
|
+
/** evt_… */
|
|
169
|
+
id: string;
|
|
170
|
+
object: 'event';
|
|
171
|
+
type: WebhookEventType | 'webhook.test';
|
|
172
|
+
livemode: boolean;
|
|
173
|
+
data: Record<string, unknown> | null;
|
|
174
|
+
createdAt: string;
|
|
175
|
+
}
|
|
176
|
+
interface WebhookEventBase<T extends string, D> {
|
|
177
|
+
/** evt_…, giữ nguyên qua mọi lần gửi lại (cũng là header webhook-id): dùng để chống xử lý trùng */
|
|
178
|
+
id: string;
|
|
179
|
+
type: T;
|
|
180
|
+
livemode: boolean;
|
|
181
|
+
/** Thời điểm sự kiện, ISO 8601 */
|
|
182
|
+
timestamp: string;
|
|
183
|
+
data: D;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Sự kiện nhận qua webhook. Kiểm `event.type` để TypeScript biết kiểu của `event.data`:
|
|
187
|
+
* - `transaction.received`: tiền vào một tài khoản đã liên kết (`Transaction`)
|
|
188
|
+
* - `payment_request.paid`: yêu cầu thanh toán đã nhận đủ hoặc thừa tiền (`status` là `paid` hoặc `overpaid`)
|
|
189
|
+
* - `payment_request.underpaid`: nhận thiếu tiền, có thể đến nhiều lần khi người trả chuyển thêm
|
|
190
|
+
* - `bank_account.linked`, `bank_account.removed`
|
|
191
|
+
* - `webhook.test`: tin gửi thử từ app hoặc `webhookEndpoints.sendTest`
|
|
192
|
+
*/
|
|
193
|
+
export type WebhookEvent = WebhookEventBase<'transaction.received', Transaction> | WebhookEventBase<'payment_request.paid', PaymentRequest> | WebhookEventBase<'payment_request.underpaid', PaymentRequest> | WebhookEventBase<'bank_account.linked', BankAccount> | WebhookEventBase<'bank_account.removed', BankAccount> | WebhookEventBase<'webhook.test', {
|
|
194
|
+
message: string;
|
|
195
|
+
endpointId: string;
|
|
196
|
+
livemode: boolean;
|
|
197
|
+
}>;
|
|
198
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { WebhookEvent } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Verify webhook BankOpenAPI theo chuẩn Standard Webhooks (https://www.standardwebhooks.com), viết bằng Web Crypto nên
|
|
4
|
+
* chạy được trên Node.js 20+, Next.js (cả Edge), Cloudflare Workers, Bun, Deno.
|
|
5
|
+
*
|
|
6
|
+
* - Ba header: `webhook-id`, `webhook-timestamp` (giây Unix), `webhook-signature` (`v1,<base64>`, có thể nhiều chữ ký
|
|
7
|
+
* cách nhau dấu cách khi đang đổi secret).
|
|
8
|
+
* - Chữ ký: HMAC-SHA256 của chuỗi `<webhook-id>.<webhook-timestamp>.<body thô>`, khóa là phần sau `whsec_` (base64).
|
|
9
|
+
* - Phải verify trên **body thô** (chuỗi hoặc bytes nhận được), không phải object đã parse rồi stringify lại.
|
|
10
|
+
*/
|
|
11
|
+
export type WebhookHeaders = Headers | Record<string, string | string[] | undefined | null>;
|
|
12
|
+
export interface VerifyOptions {
|
|
13
|
+
/** Độ lệch tối đa giữa `webhook-timestamp` và giờ hiện tại, tính bằng giây. Mặc định 300 (5 phút) */
|
|
14
|
+
tolerance?: number;
|
|
15
|
+
/** Giờ hiện tại (để test) */
|
|
16
|
+
now?: Date;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Kiểm tra chữ ký rồi trả sự kiện đã parse. Sai thì ném `WebhookVerificationError`: trả HTTP 400 cho BankOpenAPI.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* const event = await verifyWebhook(rawBody, req.headers, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
|
|
23
|
+
* if (event.type === 'payment_request.paid') markOrderPaid(event.data.orderId);
|
|
24
|
+
*/
|
|
25
|
+
export declare function verifyWebhook(payload: string | ArrayBuffer | Uint8Array, headers: WebhookHeaders, secret: string, options?: VerifyOptions): Promise<WebhookEvent>;
|
|
26
|
+
/**
|
|
27
|
+
* Ký một payload như BankOpenAPI gửi, để viết test cho endpoint nhận webhook của bạn mà không cần webhook thật.
|
|
28
|
+
* Trả về ba header để gửi kèm body.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* const body = JSON.stringify({ id: 'evt_test', type: 'webhook.test', livemode: false, timestamp: new Date().toISOString(), data: {} });
|
|
32
|
+
* const headers = await signWebhook(body, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
|
|
33
|
+
* await fetch('http://localhost:3000/webhooks/bankopenapi', { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body });
|
|
34
|
+
*/
|
|
35
|
+
export declare function signWebhook(payload: string, secret: string, options?: {
|
|
36
|
+
id?: string;
|
|
37
|
+
timestamp?: Date;
|
|
38
|
+
}): Promise<{
|
|
39
|
+
'webhook-id': string;
|
|
40
|
+
'webhook-timestamp': string;
|
|
41
|
+
'webhook-signature': string;
|
|
42
|
+
}>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyWebhook = verifyWebhook;
|
|
4
|
+
exports.signWebhook = signWebhook;
|
|
5
|
+
const errors_ts_1 = require("./errors.js");
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
function header(headers, name) {
|
|
8
|
+
if (typeof headers.get === 'function')
|
|
9
|
+
return headers.get(name) ?? undefined;
|
|
10
|
+
const record = headers;
|
|
11
|
+
const key = Object.keys(record).find((k) => k.toLowerCase() === name);
|
|
12
|
+
const value = key === undefined ? undefined : record[key];
|
|
13
|
+
return Array.isArray(value) ? value.join(' ') : (value ?? undefined);
|
|
14
|
+
}
|
|
15
|
+
function payloadText(payload) {
|
|
16
|
+
if (typeof payload === 'string')
|
|
17
|
+
return payload;
|
|
18
|
+
if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload))
|
|
19
|
+
return new TextDecoder().decode(payload);
|
|
20
|
+
throw new errors_ts_1.WebhookVerificationError('Payload phải là body thô (string, Buffer hoặc Uint8Array). Đừng parse JSON trước khi verify. / Payload must be the raw request body.');
|
|
21
|
+
}
|
|
22
|
+
function secretBytes(secret) {
|
|
23
|
+
if (!secret)
|
|
24
|
+
throw new errors_ts_1.WebhookVerificationError('Thiếu signing secret (dạng whsec_…). / Missing webhook signing secret.');
|
|
25
|
+
const base64 = secret.startsWith('whsec_') ? secret.slice('whsec_'.length) : secret;
|
|
26
|
+
try {
|
|
27
|
+
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new errors_ts_1.WebhookVerificationError('Signing secret không hợp lệ: phải là chuỗi whsec_… lấy ở trang Webhook. / Invalid webhook signing secret.');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const toBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
|
|
34
|
+
/** So sánh hai chuỗi trong thời gian không phụ thuộc vị trí khác nhau đầu tiên */
|
|
35
|
+
function safeEqual(a, b) {
|
|
36
|
+
if (a.length !== b.length)
|
|
37
|
+
return false;
|
|
38
|
+
let diff = 0;
|
|
39
|
+
for (let i = 0; i < a.length; i++)
|
|
40
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
41
|
+
return diff === 0;
|
|
42
|
+
}
|
|
43
|
+
async function hmac(secret, content) {
|
|
44
|
+
const key = await crypto.subtle.importKey('raw', secretBytes(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
45
|
+
return toBase64(new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(content))));
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Kiểm tra chữ ký rồi trả sự kiện đã parse. Sai thì ném `WebhookVerificationError`: trả HTTP 400 cho BankOpenAPI.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const event = await verifyWebhook(rawBody, req.headers, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
|
|
52
|
+
* if (event.type === 'payment_request.paid') markOrderPaid(event.data.orderId);
|
|
53
|
+
*/
|
|
54
|
+
async function verifyWebhook(payload, headers, secret, options = {}) {
|
|
55
|
+
const body = payloadText(payload);
|
|
56
|
+
const id = header(headers, 'webhook-id');
|
|
57
|
+
const timestamp = header(headers, 'webhook-timestamp');
|
|
58
|
+
const signatures = header(headers, 'webhook-signature');
|
|
59
|
+
if (!id || !timestamp || !signatures)
|
|
60
|
+
throw new errors_ts_1.WebhookVerificationError('Thiếu header webhook-id, webhook-timestamp hoặc webhook-signature. / Missing Standard Webhooks headers.');
|
|
61
|
+
const seconds = Number(timestamp);
|
|
62
|
+
if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(seconds))
|
|
63
|
+
throw new errors_ts_1.WebhookVerificationError('Header webhook-timestamp không hợp lệ. / Invalid webhook-timestamp.');
|
|
64
|
+
const tolerance = options.tolerance ?? 300;
|
|
65
|
+
const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
|
|
66
|
+
if (now - seconds > tolerance)
|
|
67
|
+
throw new errors_ts_1.WebhookVerificationError('Webhook quá cũ (timestamp lệch quá 5 phút). / Webhook timestamp too old.');
|
|
68
|
+
if (seconds - now > tolerance)
|
|
69
|
+
throw new errors_ts_1.WebhookVerificationError('Timestamp của webhook ở tương lai. / Webhook timestamp too new.');
|
|
70
|
+
const expected = await hmac(secret, `${id}.${timestamp}.${body}`);
|
|
71
|
+
const ok = signatures.split(' ').some((part) => {
|
|
72
|
+
const [version, signature] = part.split(',', 2);
|
|
73
|
+
return version === 'v1' && signature !== undefined && safeEqual(signature, expected);
|
|
74
|
+
});
|
|
75
|
+
if (!ok)
|
|
76
|
+
throw new errors_ts_1.WebhookVerificationError('Chữ ký webhook không khớp: kiểm tra signing secret và body thô. / Webhook signature mismatch.');
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(body);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new errors_ts_1.WebhookVerificationError('Body của webhook không phải JSON. / Webhook body is not JSON.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Ký một payload như BankOpenAPI gửi, để viết test cho endpoint nhận webhook của bạn mà không cần webhook thật.
|
|
86
|
+
* Trả về ba header để gửi kèm body.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* const body = JSON.stringify({ id: 'evt_test', type: 'webhook.test', livemode: false, timestamp: new Date().toISOString(), data: {} });
|
|
90
|
+
* const headers = await signWebhook(body, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
|
|
91
|
+
* await fetch('http://localhost:3000/webhooks/bankopenapi', { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body });
|
|
92
|
+
*/
|
|
93
|
+
async function signWebhook(payload, secret, options = {}) {
|
|
94
|
+
const id = options.id ?? `msg_${crypto.randomUUID().replaceAll('-', '')}`;
|
|
95
|
+
const timestamp = String(Math.floor((options.timestamp ?? new Date()).getTime() / 1000));
|
|
96
|
+
const signature = await hmac(secret, `${id}.${timestamp}.${payload}`);
|
|
97
|
+
return { 'webhook-id': id, 'webhook-timestamp': timestamp, 'webhook-signature': `v1,${signature}` };
|
|
98
|
+
}
|
|
@@ -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 {};
|
package/dist/esm/core.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { APIConnectionError, APITimeoutError, BankOpenAPIError, errorForStatus } from "./errors.js";
|
|
2
|
+
export const VERSION = '0.2.0';
|
|
3
|
+
export const DEFAULT_BASE_URL = 'https://app.bankopenapi.com/api/v1';
|
|
4
|
+
function readEnv(name) {
|
|
5
|
+
const g = globalThis;
|
|
6
|
+
try {
|
|
7
|
+
return g.process?.env?.[name]?.trim() || g.Deno?.env?.get(name)?.trim() || undefined;
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
|
|
14
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
|
+
/** 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 */
|
|
16
|
+
function retryDelay(attempt, headers) {
|
|
17
|
+
const retryAfter = Number(headers?.get('retry-after'));
|
|
18
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0 && retryAfter <= 60)
|
|
19
|
+
return retryAfter * 1000;
|
|
20
|
+
const base = Math.min(500 * 2 ** attempt, 8000);
|
|
21
|
+
return base * (0.75 + Math.random() * 0.5);
|
|
22
|
+
}
|
|
23
|
+
const shouldRetry = (status) => status === 408 || status === 429 || status >= 500;
|
|
24
|
+
function serializeQuery(query) {
|
|
25
|
+
const params = new URLSearchParams();
|
|
26
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
27
|
+
if (value === undefined || value === null)
|
|
28
|
+
continue;
|
|
29
|
+
params.set(key, value instanceof Date ? value.toISOString() : String(value));
|
|
30
|
+
}
|
|
31
|
+
const s = params.toString();
|
|
32
|
+
return s ? `?${s}` : '';
|
|
33
|
+
}
|
|
34
|
+
export class APIClient {
|
|
35
|
+
apiKey;
|
|
36
|
+
baseURL;
|
|
37
|
+
webhookSecret;
|
|
38
|
+
timeout;
|
|
39
|
+
maxRetries;
|
|
40
|
+
fetchImpl;
|
|
41
|
+
constructor(options = {}) {
|
|
42
|
+
const apiKey = options.apiKey ?? readEnv('BANKOPENAPI_API_KEY');
|
|
43
|
+
if (!apiKey)
|
|
44
|
+
throw new 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' });
|
|
45
|
+
if (!/^boa_(live|test)_[0-9A-Za-z]+$/.test(apiKey))
|
|
46
|
+
throw new 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' });
|
|
47
|
+
if (isBrowser() && !options.dangerouslyAllowBrowser)
|
|
48
|
+
throw new 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' });
|
|
49
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
50
|
+
if (typeof fetchImpl !== 'function')
|
|
51
|
+
throw new 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' });
|
|
52
|
+
this.apiKey = apiKey;
|
|
53
|
+
this.baseURL = (options.baseURL ?? readEnv('BANKOPENAPI_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
54
|
+
this.webhookSecret = options.webhookSecret ?? readEnv('BANKOPENAPI_WEBHOOK_SECRET');
|
|
55
|
+
this.timeout = options.timeout ?? 30_000;
|
|
56
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
57
|
+
this.fetchImpl = fetchImpl.bind(globalThis);
|
|
58
|
+
}
|
|
59
|
+
/** true với khóa `boa_live_` (tiền thật), false với khóa Sandbox `boa_test_` */
|
|
60
|
+
get livemode() {
|
|
61
|
+
return this.apiKey.startsWith('boa_live_');
|
|
62
|
+
}
|
|
63
|
+
async request(method, path, options = {}) {
|
|
64
|
+
const url = this.baseURL + path + serializeQuery(options.query);
|
|
65
|
+
const headers = {
|
|
66
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
67
|
+
Accept: 'application/json',
|
|
68
|
+
};
|
|
69
|
+
if (!isBrowser())
|
|
70
|
+
headers['User-Agent'] = `bankopenapi-js/${VERSION}`;
|
|
71
|
+
if (options.body !== undefined)
|
|
72
|
+
headers['Content-Type'] = 'application/json';
|
|
73
|
+
// 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
|
|
74
|
+
if (method === 'POST')
|
|
75
|
+
headers['Idempotency-Key'] = options.idempotencyKey ?? `bankopenapi-js-${crypto.randomUUID()}`;
|
|
76
|
+
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
|
|
77
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
78
|
+
const timeout = options.timeout ?? this.timeout;
|
|
79
|
+
for (let attempt = 0;; attempt++) {
|
|
80
|
+
const controller = new AbortController();
|
|
81
|
+
let timedOut = false;
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
timedOut = true;
|
|
84
|
+
controller.abort();
|
|
85
|
+
}, timeout);
|
|
86
|
+
const onAbort = () => controller.abort();
|
|
87
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
88
|
+
let res;
|
|
89
|
+
try {
|
|
90
|
+
res = await this.fetchImpl(url, { method, headers, body, signal: controller.signal });
|
|
91
|
+
}
|
|
92
|
+
catch (cause) {
|
|
93
|
+
if (options.signal?.aborted)
|
|
94
|
+
throw cause;
|
|
95
|
+
const err = timedOut
|
|
96
|
+
? new APITimeoutError(`Quá ${timeout / 1000} giây không có phản hồi từ BankOpenAPI. / Request timed out.`, { code: 'TIMEOUT', cause })
|
|
97
|
+
: new 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 });
|
|
98
|
+
if (attempt < maxRetries) {
|
|
99
|
+
await sleep(retryDelay(attempt));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
107
|
+
}
|
|
108
|
+
if (res.ok) {
|
|
109
|
+
if (res.status === 204)
|
|
110
|
+
return undefined;
|
|
111
|
+
return (await res.json());
|
|
112
|
+
}
|
|
113
|
+
const json = (await res.json().catch(() => null));
|
|
114
|
+
const message = json?.error?.message ?? `BankOpenAPI trả HTTP ${res.status}.`;
|
|
115
|
+
const err = errorForStatus(res.status, message, {
|
|
116
|
+
code: json?.error?.code ?? `HTTP_${res.status}`,
|
|
117
|
+
requestId: res.headers.get('request-id') ?? undefined,
|
|
118
|
+
headers: res.headers,
|
|
119
|
+
});
|
|
120
|
+
if (shouldRetry(res.status) && attempt < maxRetries) {
|
|
121
|
+
await sleep(retryDelay(attempt, res.headers));
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
throw err;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -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,76 @@
|
|
|
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 class BankOpenAPIError extends Error {
|
|
9
|
+
/** Mã HTTP, không có với lỗi kết nối */
|
|
10
|
+
status;
|
|
11
|
+
/** Mã lỗi, vd. `INVALID_API_KEY`, `VALIDATION_ERROR`, `RATE_LIMITED`; lỗi kết nối là `CONNECTION_ERROR` */
|
|
12
|
+
code;
|
|
13
|
+
/** Header `Request-ID` của request lỗi: gửi kèm khi cần hỗ trợ */
|
|
14
|
+
requestId;
|
|
15
|
+
headers;
|
|
16
|
+
constructor(message, details = {}) {
|
|
17
|
+
super(message, details.cause === undefined ? undefined : { cause: details.cause });
|
|
18
|
+
this.name = new.target.name;
|
|
19
|
+
this.status = details.status;
|
|
20
|
+
this.code = details.code ?? 'UNKNOWN_ERROR';
|
|
21
|
+
this.requestId = details.requestId;
|
|
22
|
+
this.headers = details.headers;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** 400, 422: tham số sai */
|
|
26
|
+
export class InvalidRequestError extends BankOpenAPIError {
|
|
27
|
+
}
|
|
28
|
+
/** 401: thiếu hoặc sai API key, khóa hết hạn */
|
|
29
|
+
export 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 class PermissionDeniedError extends BankOpenAPIError {
|
|
33
|
+
}
|
|
34
|
+
/** 404 */
|
|
35
|
+
export 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 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 class RateLimitError extends BankOpenAPIError {
|
|
42
|
+
}
|
|
43
|
+
/** 5xx */
|
|
44
|
+
export class InternalServerError extends BankOpenAPIError {
|
|
45
|
+
}
|
|
46
|
+
/** Không kết nối được tới BankOpenAPI (mạng, DNS…) */
|
|
47
|
+
export class APIConnectionError extends BankOpenAPIError {
|
|
48
|
+
}
|
|
49
|
+
/** Quá thời gian chờ phản hồi (`timeout`) */
|
|
50
|
+
export class APITimeoutError extends APIConnectionError {
|
|
51
|
+
}
|
|
52
|
+
/** Webhook sai chữ ký, thiếu header hoặc timestamp quá cũ */
|
|
53
|
+
export class WebhookVerificationError extends Error {
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.name = 'WebhookVerificationError';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export function errorForStatus(status, message, details) {
|
|
60
|
+
const d = { ...details, status };
|
|
61
|
+
if (status === 400 || status === 422)
|
|
62
|
+
return new InvalidRequestError(message, d);
|
|
63
|
+
if (status === 401)
|
|
64
|
+
return new AuthenticationError(message, d);
|
|
65
|
+
if (status === 403)
|
|
66
|
+
return new PermissionDeniedError(message, d);
|
|
67
|
+
if (status === 404)
|
|
68
|
+
return new NotFoundError(message, d);
|
|
69
|
+
if (status === 409)
|
|
70
|
+
return new ConflictError(message, d);
|
|
71
|
+
if (status === 429)
|
|
72
|
+
return new RateLimitError(message, d);
|
|
73
|
+
if (status >= 500)
|
|
74
|
+
return new InternalServerError(message, d);
|
|
75
|
+
return new BankOpenAPIError(message, d);
|
|
76
|
+
}
|