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.
@@ -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,3 @@
1
+ // Kiểu dữ liệu của API BankOpenAPI v1, khớp với apps/app/worker (serializer của từng đối tượng).
2
+ // Trường camelCase, thời gian là chuỗi ISO 8601 (UTC), tiền là số nguyên VND.
3
+ 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,94 @@
1
+ import { WebhookVerificationError } from "./errors.js";
2
+ const encoder = new TextEncoder();
3
+ function header(headers, name) {
4
+ if (typeof headers.get === 'function')
5
+ return headers.get(name) ?? undefined;
6
+ const record = headers;
7
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name);
8
+ const value = key === undefined ? undefined : record[key];
9
+ return Array.isArray(value) ? value.join(' ') : (value ?? undefined);
10
+ }
11
+ function payloadText(payload) {
12
+ if (typeof payload === 'string')
13
+ return payload;
14
+ if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload))
15
+ return new TextDecoder().decode(payload);
16
+ throw new 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.');
17
+ }
18
+ function secretBytes(secret) {
19
+ if (!secret)
20
+ throw new WebhookVerificationError('Thiếu signing secret (dạng whsec_…). / Missing webhook signing secret.');
21
+ const base64 = secret.startsWith('whsec_') ? secret.slice('whsec_'.length) : secret;
22
+ try {
23
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
24
+ }
25
+ catch {
26
+ throw new WebhookVerificationError('Signing secret không hợp lệ: phải là chuỗi whsec_… lấy ở trang Webhook. / Invalid webhook signing secret.');
27
+ }
28
+ }
29
+ const toBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
30
+ /** So sánh hai chuỗi trong thời gian không phụ thuộc vị trí khác nhau đầu tiên */
31
+ function safeEqual(a, b) {
32
+ if (a.length !== b.length)
33
+ return false;
34
+ let diff = 0;
35
+ for (let i = 0; i < a.length; i++)
36
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
37
+ return diff === 0;
38
+ }
39
+ async function hmac(secret, content) {
40
+ const key = await crypto.subtle.importKey('raw', secretBytes(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
41
+ return toBase64(new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(content))));
42
+ }
43
+ /**
44
+ * Kiểm tra chữ ký rồi trả sự kiện đã parse. Sai thì ném `WebhookVerificationError`: trả HTTP 400 cho BankOpenAPI.
45
+ *
46
+ * @example
47
+ * const event = await verifyWebhook(rawBody, req.headers, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
48
+ * if (event.type === 'payment_request.paid') markOrderPaid(event.data.orderId);
49
+ */
50
+ export async function verifyWebhook(payload, headers, secret, options = {}) {
51
+ const body = payloadText(payload);
52
+ const id = header(headers, 'webhook-id');
53
+ const timestamp = header(headers, 'webhook-timestamp');
54
+ const signatures = header(headers, 'webhook-signature');
55
+ if (!id || !timestamp || !signatures)
56
+ throw new WebhookVerificationError('Thiếu header webhook-id, webhook-timestamp hoặc webhook-signature. / Missing Standard Webhooks headers.');
57
+ const seconds = Number(timestamp);
58
+ if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(seconds))
59
+ throw new WebhookVerificationError('Header webhook-timestamp không hợp lệ. / Invalid webhook-timestamp.');
60
+ const tolerance = options.tolerance ?? 300;
61
+ const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
62
+ if (now - seconds > tolerance)
63
+ throw new WebhookVerificationError('Webhook quá cũ (timestamp lệch quá 5 phút). / Webhook timestamp too old.');
64
+ if (seconds - now > tolerance)
65
+ throw new WebhookVerificationError('Timestamp của webhook ở tương lai. / Webhook timestamp too new.');
66
+ const expected = await hmac(secret, `${id}.${timestamp}.${body}`);
67
+ const ok = signatures.split(' ').some((part) => {
68
+ const [version, signature] = part.split(',', 2);
69
+ return version === 'v1' && signature !== undefined && safeEqual(signature, expected);
70
+ });
71
+ if (!ok)
72
+ throw new WebhookVerificationError('Chữ ký webhook không khớp: kiểm tra signing secret và body thô. / Webhook signature mismatch.');
73
+ try {
74
+ return JSON.parse(body);
75
+ }
76
+ catch {
77
+ throw new WebhookVerificationError('Body của webhook không phải JSON. / Webhook body is not JSON.');
78
+ }
79
+ }
80
+ /**
81
+ * 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.
82
+ * Trả về ba header để gửi kèm body.
83
+ *
84
+ * @example
85
+ * const body = JSON.stringify({ id: 'evt_test', type: 'webhook.test', livemode: false, timestamp: new Date().toISOString(), data: {} });
86
+ * const headers = await signWebhook(body, process.env.BANKOPENAPI_WEBHOOK_SECRET!);
87
+ * await fetch('http://localhost:3000/webhooks/bankopenapi', { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body });
88
+ */
89
+ export async function signWebhook(payload, secret, options = {}) {
90
+ const id = options.id ?? `msg_${crypto.randomUUID().replaceAll('-', '')}`;
91
+ const timestamp = String(Math.floor((options.timestamp ?? new Date()).getTime() / 1000));
92
+ const signature = await hmac(secret, `${id}.${timestamp}.${payload}`);
93
+ return { 'webhook-id': id, 'webhook-timestamp': timestamp, 'webhook-signature': `v1,${signature}` };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "bankopenapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Thư viện chính thức của BankOpenAPI cho Node.js, Next.js, Cloudflare Workers, Bun: tạo yêu cầu thanh toán chuyển khoản, VietQR, verify webhook báo có. Official BankOpenAPI SDK for Vietnamese bank-transfer payments.",
5
+ "keywords": [
6
+ "bankopenapi",
7
+ "vietqr",
8
+ "bank transfer",
9
+ "chuyen khoan",
10
+ "payment",
11
+ "webhook",
12
+ "vietnam",
13
+ "napas"
14
+ ],
15
+ "homepage": "https://bankopenapi.com/tai-lieu",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/bankopenapi/bankopenapi-js.git"
19
+ },
20
+ "bugs": {
21
+ "email": "teams@bankopenapi.com"
22
+ },
23
+ "license": "MIT",
24
+ "author": "BankOpenAPI <teams@bankopenapi.com>",
25
+ "type": "module",
26
+ "main": "./dist/cjs/index.js",
27
+ "module": "./dist/esm/index.js",
28
+ "types": "./dist/esm/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/esm/index.d.ts",
33
+ "default": "./dist/esm/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/cjs/index.d.ts",
37
+ "default": "./dist/cjs/index.js"
38
+ }
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "sideEffects": false,
48
+ "engines": {
49
+ "node": ">=20"
50
+ },
51
+ "scripts": {
52
+ "build": "node scripts/build.mjs",
53
+ "typecheck": "tsc -p tsconfig.json",
54
+ "test": "node --test --experimental-strip-types \"test/*.test.ts\"",
55
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
56
+ },
57
+ "devDependencies": {
58
+ "typescript": "^5.9.3"
59
+ }
60
+ }