@bepago/sdk 0.0.0-stage → 1.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/index.mjs +107 -0
  4. package/package.json +35 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bePago
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,110 @@
1
- # Temporary Holding Version
1
+ # bePago — SDK para Node.js
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
+ SDK oficial de [bePago](https://bepago.com) para Node.js 18+. Sin dependencias.
4
+
5
+ Cobros, pagos masivos (payouts) y verificación de webhooks con firma HMAC v2.
6
+
7
+ ## Instalación
8
+
9
+ ```bash
10
+ npm install bepago
11
+ ```
12
+
13
+ ## Uso
14
+
15
+ ```js
16
+ import BePago from 'bepago';
17
+
18
+ const bp = BePago('sk_live_tu_secreto');
19
+ ```
20
+
21
+ La clave (`sk_…`) la obtenés en tu panel de bePago. El key ID público (`pk_…`)
22
+ se deriva solo; si necesitás pasarlo aparte: `BePago(secret, { keyId: 'pk_…' })`.
23
+
24
+ ### Crear un cobro
25
+
26
+ ```js
27
+ const cobro = await bp.charges.create({
28
+ reference: 'pedido-001',
29
+ currency: 'PYG',
30
+ amount: 150000,
31
+ description: 'Pedido #001',
32
+ });
33
+
34
+ console.log(cobro.checkout_url); // link de pago para el cliente
35
+ ```
36
+
37
+ Consultar, reembolsar y ver saldo:
38
+
39
+ ```js
40
+ await bp.charges.get('pedido-001');
41
+ await bp.charges.refund('pedido-001', 'cliente canceló');
42
+ await bp.charges.balance();
43
+ ```
44
+
45
+ ### Pago masivo (payout)
46
+
47
+ ```js
48
+ const payout = await bp.payouts.create(
49
+ {
50
+ currency: 'PYG',
51
+ amount: 500000,
52
+ destination: { alias: 'juan.perez', holder_name: 'Juan Pérez' },
53
+ },
54
+ 'idem-key-unica', // clave de idempotencia (opcional pero recomendada)
55
+ );
56
+
57
+ await bp.payouts.get(payout.id);
58
+ await bp.payouts.cancel(payout.id);
59
+ await bp.payouts.balance();
60
+ ```
61
+
62
+ ### Verificar un webhook
63
+
64
+ bePago firma cada webhook con `HMAC-SHA256` sobre `timestamp + body` usando el
65
+ secreto del webhook. `verify` chequea la firma **y la frescura del timestamp**
66
+ (rechaza entregas fuera de ±5 minutos por defecto, configurable) y devuelve el
67
+ evento ya parseado, con su `id`:
68
+
69
+ ```js
70
+ import BePago from 'bepago';
71
+
72
+ const bp = BePago('sk_live_…');
73
+
74
+ // En tu handler HTTP (body como string crudo, sin re-serializar):
75
+ let evt;
76
+ try {
77
+ evt = bp.webhooks.verify('whsec_tu_secreto_de_webhook', {
78
+ id: req.headers['x-bepago-event-id'],
79
+ timestamp: req.headers['x-webhook-timestamp'],
80
+ signature: req.headers['x-webhook-signature'],
81
+ body: req.rawBody, // el cuerpo tal cual llegó, sin re-serializar
82
+ });
83
+ } catch (e) {
84
+ return res.status(400).send('webhook inválido'); // firma o timestamp fuera de ventana
85
+ }
86
+
87
+ // Anti-replay: cada evento trae un id ESTABLE entre reintentos. Guardá los ids
88
+ // ya procesados y descartá los duplicados (los reintentos reenvían el mismo id
89
+ // con un timestamp nuevo).
90
+ if (await yaProcesado(evt.id)) return res.status(200).end();
91
+ await marcarProcesado(evt.id);
92
+
93
+ // procesar evt.event / evt.data …
94
+ res.status(200).end();
95
+ ```
96
+
97
+ Tolerancia configurable (ej. ±10 minutos):
98
+
99
+ ```js
100
+ bp.webhooks.verify(secret, { id, timestamp, signature, body }, { toleranceSeconds: 600 });
101
+ ```
102
+
103
+ ## Documentación
104
+
105
+ Referencia completa de la API, tipos de eventos y ejemplos:
106
+ **https://bepago.com/docs**
107
+
108
+ ## Licencia
109
+
110
+ MIT
package/index.mjs ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * bePago SDK — Node.js (18+, zero dependencies).
3
+ *
4
+ * Usage:
5
+ * import BePago from 'bepago';
6
+ * const bp = BePago('sk_test_…');
7
+ * const charge = await bp.charges.create({ reference: 'order-1', currency: 'PYG', amount: 150000, description: 'Test' });
8
+ */
9
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
10
+
11
+ /**
12
+ * Firma canónica v2 de un request (misma que valida la API).
13
+ * `body` es el cuerpo YA serializado (string); cadena vacía si no hay body.
14
+ */
15
+ export function computeSignatureV2({ secret, timestamp, nonce, method, path, idempotencyKey = '', body = '' }) {
16
+ const bodyHash = createHash('sha256').update(body, 'utf8').digest('hex');
17
+ const canonical = ['v2', timestamp, nonce, method.toUpperCase(), path, idempotencyKey ?? '', bodyHash].join('\n');
18
+ return createHmac('sha256', secret).update(canonical, 'utf8').digest('hex');
19
+ }
20
+
21
+ export default function BePago(secret, opts = {}) {
22
+ const base = opts.baseUrl ?? 'https://bepago.com/api';
23
+ // The key ID is the part before the first underscore pair: pk_test_xxx or sk_test_xxx
24
+ // But for the API, X-Api-Key is the full key ID (pk_test_…), and the secret is sk_test_…
25
+ // Convention: the user passes the secret (sk_), and the key ID (pk_) is derived or passed separately.
26
+ const keyId = opts.keyId ?? secret.replace(/^sk_/, 'pk_');
27
+
28
+ function sign(method, path, body, idempotencyKey) {
29
+ const timestamp = String(Date.now());
30
+ const nonce = randomUUID().replaceAll('-', '');
31
+ const bodyStr = body != null ? JSON.stringify(body) : '';
32
+ const signature = computeSignatureV2({ secret, timestamp, nonce, method, path, idempotencyKey, body: bodyStr });
33
+ return { timestamp, nonce, signature, bodyStr };
34
+ }
35
+
36
+ async function request(method, path, body, extra = {}) {
37
+ const { timestamp, nonce, signature, bodyStr } = sign(method, path, body, extra.idempotencyKey);
38
+ const headers = {
39
+ 'Content-Type': 'application/json',
40
+ 'X-Api-Key': keyId,
41
+ 'X-Timestamp': timestamp,
42
+ 'X-Nonce': nonce,
43
+ 'X-Signature-Version': '2',
44
+ 'X-Signature': signature,
45
+ };
46
+ if (extra.idempotencyKey) headers['X-Idempotency-Key'] = extra.idempotencyKey;
47
+ const res = await fetch(base + path, { method, headers, body: bodyStr || undefined });
48
+ const data = await res.json();
49
+ if (!res.ok) {
50
+ const err = new Error(data?.error?.message ?? `HTTP ${res.status}`);
51
+ err.code = data?.error?.code;
52
+ err.status = res.status;
53
+ err.response = data;
54
+ throw err;
55
+ }
56
+ return data;
57
+ }
58
+
59
+ return {
60
+ charges: {
61
+ create: (params) => request('POST', '/v1/charges', params),
62
+ get: (ref) => request('GET', `/v1/charges/${encodeURIComponent(ref)}`),
63
+ refund: (ref, reason) => request('POST', `/v1/charges/${encodeURIComponent(ref)}/refund`, { reason }),
64
+ balance: () => request('GET', '/v1/charges/balance'),
65
+ },
66
+ payouts: {
67
+ create: (params, idempotencyKey) => request('POST', '/v1/payouts', params, { idempotencyKey }),
68
+ get: (id) => request('GET', `/v1/payouts/${encodeURIComponent(id)}`),
69
+ cancel: (id) => request('POST', `/v1/payouts/${encodeURIComponent(id)}/cancel`),
70
+ balance: () => request('GET', '/v1/balance'),
71
+ },
72
+ webhooks: {
73
+ /**
74
+ * Verifica un webhook de bePago y devuelve el evento parseado.
75
+ *
76
+ * Chequea la firma HMAC y la FRESCURA del timestamp: por defecto rechaza
77
+ * entregas fuera de ±5 minutos (configurable con `toleranceSeconds`). Lanza
78
+ * si la firma no valida o el timestamp está fuera de la ventana.
79
+ *
80
+ * Expone `id` (header X-BePago-Event-Id, estable entre reintentos): guardá
81
+ * los ids ya procesados para descartar duplicados de forma idempotente.
82
+ *
83
+ * const evt = bp.webhooks.verify(secret, {
84
+ * id: req.headers['x-bepago-event-id'],
85
+ * timestamp: req.headers['x-webhook-timestamp'],
86
+ * signature: req.headers['x-webhook-signature'],
87
+ * body: rawBody, // el cuerpo EXACTO recibido, sin reserializar
88
+ * });
89
+ * if (seen.has(evt.id)) return; // duplicado
90
+ * seen.add(evt.id);
91
+ *
92
+ * @returns {{ id: string, event: string, livemode: boolean, data: object }}
93
+ */
94
+ verify(webhookSecret, { id, timestamp, body, signature }, opts = {}) {
95
+ const toleranceMs = (opts.toleranceSeconds ?? 300) * 1000;
96
+ const expected = createHmac('sha256', webhookSecret).update(String(timestamp) + body, 'utf8').digest('hex');
97
+ const a = Buffer.from(expected, 'hex');
98
+ const b = Buffer.from(String(signature ?? ''), 'hex');
99
+ if (a.length !== b.length || !timingSafeEqual(a, b)) throw new Error('bePago webhook: firma inválida');
100
+ const age = Math.abs(Date.now() - Number(timestamp));
101
+ if (!Number.isFinite(age) || age > toleranceMs) throw new Error('bePago webhook: timestamp fuera de la ventana permitida');
102
+ const payload = JSON.parse(body);
103
+ return { id: id ?? payload.id, event: payload.event, livemode: payload.livemode, data: payload.data };
104
+ },
105
+ },
106
+ };
107
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@bepago/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "SDK oficial de bePago para Node.js (18+, sin dependencias)",
5
+ "type": "module",
6
+ "main": "index.mjs",
7
+ "exports": {
8
+ ".": "./index.mjs"
9
+ },
10
+ "files": [
11
+ "index.mjs",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "keywords": [
16
+ "bepago",
17
+ "pagos",
18
+ "payments",
19
+ "paraguay",
20
+ "cobros",
21
+ "payouts",
22
+ "webhooks"
23
+ ],
24
+ "homepage": "https://bepago.com/docs",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/bepago/sdk-node.git"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/bepago/sdk-node/issues"
31
+ },
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
35
+ "author": "bePago",
36
+ "license": "MIT"
37
+ }