@bepago/sdk 0.0.0-stage → 1.0.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 +98 -2
  3. package/index.mjs +79 -0
  4. package/package.json +33 -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,99 @@
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. Verificá la firma antes de procesar el evento:
66
+
67
+ ```js
68
+ import BePago from 'bepago';
69
+
70
+ const bp = BePago('sk_live_…');
71
+
72
+ // En tu handler HTTP (body como string crudo, sin re-serializar):
73
+ const timestamp = req.headers['x-timestamp'];
74
+ const signature = req.headers['x-signature'];
75
+ const rawBody = req.rawBody; // el cuerpo tal cual llegó
76
+
77
+ const ok = bp.webhooks.verify(
78
+ 'whsec_tu_secreto_de_webhook',
79
+ timestamp,
80
+ rawBody,
81
+ signature,
82
+ );
83
+
84
+ if (!ok) {
85
+ return res.status(400).send('firma inválida');
86
+ }
87
+
88
+ const evento = JSON.parse(rawBody);
89
+ // procesar evento.type …
90
+ ```
91
+
92
+ ## Documentación
93
+
94
+ Referencia completa de la API, tipos de eventos y ejemplos:
95
+ **https://bepago.com/docs**
96
+
97
+ ## Licencia
98
+
99
+ MIT
package/index.mjs ADDED
@@ -0,0 +1,79 @@
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
+ verify: (webhookSecret, timestamp, body, signature) => {
74
+ const expected = createHmac('sha256', webhookSecret).update(timestamp + body, 'utf8').digest('hex');
75
+ return timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(signature, 'hex'));
76
+ },
77
+ },
78
+ };
79
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
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.0.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": { "node": ">=18" },
33
+ "author": "bePago",
34
+ "license": "MIT"
35
+ }