@miguelmorales13/nestkit 0.29.0 → 0.30.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/README.md CHANGED
@@ -1221,6 +1221,54 @@ Es una clase sin dependencia de Nest: envolvela en tu propio servicio para el pl
1221
1221
  dominio. El formato de las credenciales guardadas (`MercadoPagoCredentials`: `accessToken`, `refreshToken`,
1222
1222
  `mpUserId`, `expira`, `mpStoreId`, `mpPosId`) es el persistido: no lo renombres si ya tenés filas.
1223
1223
 
1224
+ #### Cobro con Openpay: el comercio inicia sesión y listo (`OpenpayConnections`)
1225
+
1226
+ Para que **cada comercio cobre en su propia cuenta de Openpay (BBVA) sin copiar llaves**: el comercio toca «Conectar»,
1227
+ Openpay le deja elegir «usar mi cuenta» (inicia sesión y autoriza) o «cuenta nueva» (se registra ahí mismo) y vuelve a tu
1228
+ app ya conectado. Es el esquema de *partners* con OAuth 2 de Openpay: recibís el `merchant_id` y las llaves del comercio,
1229
+ y cobrás **a su nombre**; el dinero cae en su cuenta, nunca pasa por la tuya.
1230
+
1231
+ ```ts
1232
+ import { OpenpayConnections, CredentialsCipher } from '@miguelmorales13/nestkit/payments';
1233
+
1234
+ const openpay = new OpenpayConnections({
1235
+ store, // tu tabla: find / upsert / update / delete / findByWebhookToken
1236
+ cipher: () => CredentialsCipher.fromHex(process.env.APP_ENCRYPTION_KEY),
1237
+ partner: () => ({ clientId, clientSecret, redirectUri }), // el correo que manda Openpay al registrarte como integrador
1238
+ sandbox: () => process.env.OPENPAY_SANDBOX === 'true',
1239
+ stateSecret: () => process.env.JWT_SECRET,
1240
+ publicWebhookUrl: (token) => `https://api.tuapp.mx/api/v1/openpay/avisos/${token}`,
1241
+ fetchImpl: () => fetchResiliente, // tiempos límite / reintentos / alertas
1242
+ });
1243
+
1244
+ openpay.authorizationUrl(tiendaId, { returnTo: '/ajustes' }); // → redirige al comercio
1245
+ await openpay.complete({ code, state, error }); // callback: guarda llaves cifradas + registra el webhook
1246
+ const p = await openpay.createPayment(tiendaId, {
1247
+ method: 'transfer', // o 'card'
1248
+ reference: pedido.id, description: 'Pedido 123', amountCents: 25_000,
1249
+ returnUrl, // solo tarjeta
1250
+ });
1251
+ // card → p.url es el formulario de Openpay (se manda por WhatsApp, correo, QR…)
1252
+ // transfer → p.transfer = { clabe, reference (20 dígitos), bank, agreement, dueDate }; p.url = recibo imprimible
1253
+ await openpay.lookup(tiendaId, p.chargeId); // estado leído de Openpay: paid | pending | failed | refunded
1254
+ await openpay.refund(tiendaId, chargeId, centavos?); // solo tarjeta (Openpay no devuelve SPEI)
1255
+ await openpay.handleNotice(token, req.headers.authorization, req.body); // webhook: nunca le cree al cuerpo, relee el cargo
1256
+ ```
1257
+
1258
+ Cosas que conviene saber:
1259
+
1260
+ - **La transferencia es SPEI con CLABE + referencia de 20 dígitos**; la referencia va en el concepto y es lo que Openpay
1261
+ usa para saber de qué cobro es. Vence a los días que pongas (máximo 30) y Openpay expira en días hábiles.
1262
+ - **El webhook lo registra la librería** con la llave del comercio y autenticación Basic (usuario = token de la URL,
1263
+ contraseña = una por comercio). Si no se pudo registrar, la conexión queda y `lookup` sigue diciendo la verdad;
1264
+ `ensureNotices(tiendaId)` lo reintenta.
1265
+ - `handleNotice` responde siempre algo que debes contestar con 200; solo lanza ante una contraseña mala. Un abono de saldo
1266
+ del propio comercio (`spei.received` sin pedido) se ignora.
1267
+ - Las llaves del comercio van **cifradas** con `CredentialsCipher`; el sandbox y producción no se mezclan (cada conexión
1268
+ recuerda de cuál es).
1269
+ - Las cifras y flujos salen de la documentación pública de Openpay; el registro como *partner* y el paso a producción son
1270
+ trámites tuyos con Openpay.
1271
+
1224
1272
  #### Agregar un tercer proveedor
1225
1273
 
1226
1274
  Una clase que implemente `TerminalPaymentsPort`, un `case` en `createTerminalPaymentsAdapter`, su
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-KVBQBT3D.cjs');
2
+
2
3
 
3
4
 
4
5
 
5
6
  var _chunk47IYXZHWcjs = require('./chunk-47IYXZHW.cjs');
6
- require('./chunk-KVBQBT3D.cjs');
7
7
 
8
8
 
9
9
 
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
+ import "./chunk-EPVKCBPT.js";
1
2
  import {
2
3
  PG_POOL,
3
4
  PgModule,
4
5
  withTenantScope
5
6
  } from "./chunk-ENZ7LQRE.js";
6
- import "./chunk-EPVKCBPT.js";
7
7
  import {
8
8
  SUPABASE_ANON_CLIENT,
9
9
  SUPABASE_SERVICE_ROLE_CLIENT,
@@ -1807,6 +1807,499 @@ var TerminalConnections = class {
1807
1807
  }
1808
1808
  };
1809
1809
 
1810
+ // src/payments/openpay/openpay-api.ts
1811
+ var PROVIDER4 = "openpay";
1812
+ var API_PRODUCTION = "https://api.openpay.mx";
1813
+ var API_SANDBOX = "https://sandbox-api.openpay.mx";
1814
+ var DASHBOARD_PRODUCTION = "https://dashboard.openpay.mx";
1815
+ var DASHBOARD_SANDBOX = "https://sandbox-dashboard.openpay.mx";
1816
+ var DEFAULT_MESSAGES2 = {
1817
+ notOpened: "Openpay no abri\xF3 el cobro.",
1818
+ noAnswer: "Openpay no respondi\xF3."
1819
+ };
1820
+ var OPENPAY_PROVIDER_ERROR = "PAGO_PROVEEDOR_ERROR";
1821
+ var pesos3 = (cents) => Number((cents / 100).toFixed(2));
1822
+ var toCents = (amount) => Math.round(Number(_nullishCoalesce(amount, () => ( 0))) * 100);
1823
+ function openpayState(status) {
1824
+ switch ((_nullishCoalesce(status, () => ( ""))).toLowerCase()) {
1825
+ case "completed":
1826
+ return "paid";
1827
+ case "cancelled":
1828
+ case "failed":
1829
+ case "expired":
1830
+ return "failed";
1831
+ case "refunded":
1832
+ case "chargeback_accepted":
1833
+ case "chargeback_adjustment":
1834
+ return "refunded";
1835
+ default:
1836
+ return "pending";
1837
+ }
1838
+ }
1839
+ var OpenpayApi = class {
1840
+ constructor(cred, o = {}) {
1841
+ this.cred = cred;
1842
+ this.msg = { ...DEFAULT_MESSAGES2, ...o.messages };
1843
+ this.http = _nullishCoalesce(o.fetchImpl, () => ( fetch));
1844
+ this.base = (_nullishCoalesce(o.apiBaseUrl, () => ( (o.sandbox ? API_SANDBOX : API_PRODUCTION)))).replace(/\/$/, "");
1845
+ this.dashboard = (_nullishCoalesce(o.dashboardBaseUrl, () => ( (o.sandbox ? DASHBOARD_SANDBOX : DASHBOARD_PRODUCTION)))).replace(/\/$/, "");
1846
+ }
1847
+ url(path) {
1848
+ return `${this.base}/v1/${encodeURIComponent(this.cred.merchantId)}${path}`;
1849
+ }
1850
+ headers(extra = {}) {
1851
+ return {
1852
+ authorization: `Basic ${Buffer.from(`${this.cred.secretKey}:`).toString("base64")}`,
1853
+ "content-type": "application/json",
1854
+ ...extra
1855
+ };
1856
+ }
1857
+ customerBody(c) {
1858
+ return {
1859
+ name: c.name,
1860
+ ...c.lastName ? { last_name: c.lastName } : {},
1861
+ ...c.email ? { email: c.email } : {},
1862
+ ...c.phone ? { phone_number: c.phone } : {}
1863
+ };
1864
+ }
1865
+ /** `requestJson` with the error shaped for the app: provider failures keep their body; duplicates keep their code. */
1866
+ async call(path, init, failure) {
1867
+ try {
1868
+ return await requestJson(PROVIDER4, this.http, this.url(path), init);
1869
+ } catch (e) {
1870
+ if (e instanceof TerminalPaymentProviderException) {
1871
+ throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(failure, _nullishCoalesce(e.details, () => ( { provider: PROVIDER4 })), OPENPAY_PROVIDER_ERROR);
1872
+ }
1873
+ throw e;
1874
+ }
1875
+ }
1876
+ /** Card: Openpay's hosted form (a "virtual terminal" charge). Pays with any card; the buyer never touches your server. */
1877
+ async createCardLink(c) {
1878
+ const r = await this.call(
1879
+ "/charges",
1880
+ {
1881
+ method: "POST",
1882
+ headers: this.headers(c.clientIp ? { "x-forwarded-for": c.clientIp } : {}),
1883
+ body: JSON.stringify({
1884
+ method: "card",
1885
+ amount: pesos3(c.amountCents),
1886
+ currency: "MXN",
1887
+ description: c.description.slice(0, 250),
1888
+ order_id: c.orderId.slice(0, 100),
1889
+ customer: this.customerBody(c.customer),
1890
+ confirm: false,
1891
+ send_email: _nullishCoalesce(c.sendEmail, () => ( false)),
1892
+ redirect_url: c.redirectUrl
1893
+ })
1894
+ },
1895
+ this.msg.notOpened
1896
+ );
1897
+ const url = _optionalChain([r, 'access', _107 => _107.payment_method, 'optionalAccess', _108 => _108.url]);
1898
+ if (!r.id || !url) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notOpened, { provider: PROVIDER4 }, OPENPAY_PROVIDER_ERROR);
1899
+ return { chargeId: r.id, url };
1900
+ }
1901
+ /** Bank: a CLABE plus a 20-digit reference. The buyer pays from any bank by SPEI; Openpay confirms it by webhook. */
1902
+ async createBankTransfer(c) {
1903
+ const r = await this.call(
1904
+ "/charges",
1905
+ {
1906
+ method: "POST",
1907
+ headers: this.headers(),
1908
+ body: JSON.stringify({
1909
+ method: "bank_account",
1910
+ amount: pesos3(c.amountCents),
1911
+ currency: "MXN",
1912
+ description: c.description.slice(0, 250),
1913
+ order_id: c.orderId.slice(0, 100),
1914
+ ...c.customer ? { customer: this.customerBody(c.customer) } : {},
1915
+ ...c.dueDate ? { due_date: c.dueDate.toISOString() } : {}
1916
+ })
1917
+ },
1918
+ this.msg.notOpened
1919
+ );
1920
+ const pm = r.payment_method;
1921
+ if (!r.id || !_optionalChain([pm, 'optionalAccess', _109 => _109.clabe]) || !pm.name)
1922
+ throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notOpened, { provider: PROVIDER4 }, OPENPAY_PROVIDER_ERROR);
1923
+ return {
1924
+ chargeId: r.id,
1925
+ clabe: pm.clabe,
1926
+ reference: pm.name,
1927
+ bank: _nullishCoalesce(pm.bank, () => ( "BBVA")),
1928
+ agreement: _nullishCoalesce(pm.agreement, () => ( "")),
1929
+ receiptUrl: `${this.dashboard}/spei-pdf/${encodeURIComponent(this.cred.merchantId)}/${encodeURIComponent(r.id)}`,
1930
+ dueDate: r.due_date ? new Date(r.due_date) : _nullishCoalesce(c.dueDate, () => ( null))
1931
+ };
1932
+ }
1933
+ shape(r) {
1934
+ const state = openpayState(r.status);
1935
+ const type = _optionalChain([r, 'access', _110 => _110.payment_method, 'optionalAccess', _111 => _111.type]);
1936
+ const method = r.method === "card" ? "card" : r.method === "bank_account" || type === "bank_transfer" ? "transfer" : r.method === "store" ? "store" : "other";
1937
+ return {
1938
+ id: _nullishCoalesce(r.id, () => ( "")),
1939
+ state,
1940
+ status: _nullishCoalesce(r.status, () => ( "")),
1941
+ method,
1942
+ orderId: _nullishCoalesce(r.order_id, () => ( null)),
1943
+ amountCents: toCents(r.amount),
1944
+ paidCents: state === "paid" ? toCents(r.amount) : null,
1945
+ dueDate: r.due_date ? new Date(r.due_date) : null
1946
+ };
1947
+ }
1948
+ async getCharge(chargeId) {
1949
+ const r = await this.call(`/charges/${encodeURIComponent(chargeId)}`, { headers: this.headers() }, this.msg.noAnswer);
1950
+ return this.shape(r);
1951
+ }
1952
+ /** Your own id is the way back when you only have the sale (the notice carries both). */
1953
+ async findByOrderId(orderId) {
1954
+ const r = await this.call(
1955
+ `/charges?order_id=${encodeURIComponent(orderId)}&limit=1`,
1956
+ { headers: this.headers() },
1957
+ this.msg.noAnswer
1958
+ );
1959
+ return Array.isArray(r) && r[0] ? this.shape(r[0]) : null;
1960
+ }
1961
+ /** Card charges only: Openpay does not refund SPEI. `amountCents` omitted = the whole charge. */
1962
+ async refundCard(chargeId, amountCents, description) {
1963
+ const r = await this.call(
1964
+ `/charges/${encodeURIComponent(chargeId)}/refund`,
1965
+ {
1966
+ method: "POST",
1967
+ headers: this.headers(),
1968
+ body: JSON.stringify({
1969
+ ...description ? { description: description.slice(0, 250) } : {},
1970
+ ...amountCents !== void 0 ? { amount: pesos3(amountCents) } : {}
1971
+ })
1972
+ },
1973
+ this.msg.noAnswer
1974
+ );
1975
+ return this.shape(r);
1976
+ }
1977
+ /** Notices go to `url` with HTTP Basic (`user`/`password`), the only authentication Openpay supports. */
1978
+ async createWebhook(w) {
1979
+ const r = await this.call(
1980
+ "/webhooks",
1981
+ {
1982
+ method: "POST",
1983
+ headers: this.headers(),
1984
+ body: JSON.stringify({ url: w.url, user: w.user, password: w.password, event_types: w.eventTypes })
1985
+ },
1986
+ this.msg.noAnswer
1987
+ );
1988
+ if (!r.id) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.noAnswer, { provider: PROVIDER4 }, OPENPAY_PROVIDER_ERROR);
1989
+ return { id: r.id, status: _nullishCoalesce(r.status, () => ( "unverified")) };
1990
+ }
1991
+ /** Activates a webhook with the code Openpay sent to its URL in the `verification` notice. */
1992
+ async verifyWebhook(webhookId, code) {
1993
+ await this.call(
1994
+ `/webhooks/${encodeURIComponent(webhookId)}/verify/${encodeURIComponent(code)}`,
1995
+ { method: "POST", headers: this.headers() },
1996
+ this.msg.noAnswer
1997
+ );
1998
+ }
1999
+ async deleteWebhook(webhookId) {
2000
+ await this.call(`/webhooks/${encodeURIComponent(webhookId)}`, { method: "DELETE", headers: this.headers() }, this.msg.noAnswer);
2001
+ }
2002
+ };
2003
+
2004
+ // src/payments/openpay/openpay-connections.ts
2005
+
2006
+
2007
+ var PROVIDER5 = "openpay";
2008
+ var DASHBOARD_PRODUCTION2 = "https://dashboard.openpay.mx";
2009
+ var DASHBOARD_SANDBOX2 = "https://sandbox-dashboard.openpay.mx";
2010
+ var WEBHOOK_EVENTS = [
2011
+ "charge.succeeded",
2012
+ "charge.failed",
2013
+ "charge.cancelled",
2014
+ "charge.refunded",
2015
+ "chargeback.accepted",
2016
+ "spei.received"
2017
+ ];
2018
+ var DEFAULT_MESSAGES3 = {
2019
+ notConfigured: "Openpay no est\xE1 configurado.",
2020
+ notConnected: "Esta tienda no tiene Openpay conectado.",
2021
+ badState: "El enlace de conexi\xF3n con Openpay no es v\xE1lido o venci\xF3. Vuelve a intentarlo.",
2022
+ notAuthorized: "Openpay no autoriz\xF3 la conexi\xF3n.",
2023
+ refundUnsupported: "Openpay solo devuelve cobros con tarjeta; una transferencia se devuelve directo al cliente.",
2024
+ minimumAmount: "El monto es menor al m\xEDnimo que acepta Openpay."
2025
+ };
2026
+ var STATE_PURPOSE = "openpay-connect";
2027
+ var OpenpayConnections = class {
2028
+ constructor(o) {
2029
+ this.o = o;
2030
+ this.log = new (0, _common.Logger)("OpenpayConnections");
2031
+ this.msg = { ...DEFAULT_MESSAGES3, ...o.messages };
2032
+ }
2033
+ // ── plumbing ───────────────────────────────────────────────────────────────
2034
+ get cipher() {
2035
+ return typeof this.o.cipher === "function" ? this.o.cipher() : this.o.cipher;
2036
+ }
2037
+ get partner() {
2038
+ return typeof this.o.partner === "function" ? this.o.partner() : this.o.partner;
2039
+ }
2040
+ get sandbox() {
2041
+ return typeof this.o.sandbox === "function" ? this.o.sandbox() : _nullishCoalesce(this.o.sandbox, () => ( false));
2042
+ }
2043
+ get stateSecret() {
2044
+ return typeof this.o.stateSecret === "function" ? this.o.stateSecret() : this.o.stateSecret;
2045
+ }
2046
+ dashboard(sandbox = this.sandbox) {
2047
+ return (_nullishCoalesce(this.o.dashboardBaseUrl, () => ( (sandbox ? DASHBOARD_SANDBOX2 : DASHBOARD_PRODUCTION2)))).replace(/\/$/, "");
2048
+ }
2049
+ http(scopeId) {
2050
+ return _nullishCoalesce(_optionalChain([this, 'access', _112 => _112.o, 'access', _113 => _113.fetchImpl, 'optionalCall', _114 => _114(scopeId)]), () => ( fetch));
2051
+ }
2052
+ apiOptions(sandbox, scopeId) {
2053
+ return {
2054
+ sandbox,
2055
+ fetchImpl: this.http(scopeId),
2056
+ ...this.o.apiBaseUrl ? { apiBaseUrl: this.o.apiBaseUrl } : {},
2057
+ ...this.o.dashboardBaseUrl ? { dashboardBaseUrl: this.o.dashboardBaseUrl } : {}
2058
+ };
2059
+ }
2060
+ /** The feature is on: a cipher, a partner application and a signing secret are configured. */
2061
+ get available() {
2062
+ return Boolean(this.cipher && this.partner && this.stateSecret);
2063
+ }
2064
+ requireCipher() {
2065
+ const c = this.cipher;
2066
+ if (!c) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notConfigured, void 0, "OPENPAY_NO_CONFIGURADO");
2067
+ return c;
2068
+ }
2069
+ credentialsOf(rec) {
2070
+ return this.requireCipher().decryptJson(rec.encryptedCredentials);
2071
+ }
2072
+ async recordOf(scopeId) {
2073
+ const rec = await this.o.store.find(scopeId);
2074
+ if (!rec || !rec.active) throw new (0, _chunkHDFPSA2Vcjs.NotFoundAppException)(this.msg.notConnected, void 0, "OPENPAY_NO_CONECTADO");
2075
+ return rec;
2076
+ }
2077
+ apiOf(rec) {
2078
+ return new OpenpayApi(this.credentialsOf(rec), this.apiOptions(rec.sandbox, rec.scopeId));
2079
+ }
2080
+ // ── connect (OAuth) ────────────────────────────────────────────────────────
2081
+ /**
2082
+ * Where to send the merchant: Openpay lets them pick "use my account" (they sign in and authorize) or "new account"
2083
+ * (they register right there). `extra` rides in the signed `state` and comes back from {@link complete}.
2084
+ */
2085
+ authorizationUrl(scopeId, extra = {}) {
2086
+ const partner = this.partner;
2087
+ const secret = this.stateSecret;
2088
+ if (!this.cipher || !partner || !secret) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notConfigured, void 0, "OPENPAY_NO_CONFIGURADO");
2089
+ const state = _chunk33KFVAUZcjs.signState.call(void 0, { ...extra, scopeId, purpose: STATE_PURPOSE }, { secret });
2090
+ const params = new URLSearchParams({
2091
+ client_id: partner.clientId,
2092
+ redirect_uri: partner.redirectUri,
2093
+ response_type: "code",
2094
+ scope: "read write",
2095
+ state
2096
+ });
2097
+ return `${this.dashboard()}/oauth/authorize?${params.toString()}`;
2098
+ }
2099
+ /** Reads the callback's `state` without trading the code: who started the flow (and what they sent along). */
2100
+ readState(state) {
2101
+ const secret = this.stateSecret;
2102
+ if (!secret) return null;
2103
+ const s = _chunk33KFVAUZcjs.readState.call(void 0, state, { secret });
2104
+ return s && s.purpose === STATE_PURPOSE && s.scopeId ? s : null;
2105
+ }
2106
+ /**
2107
+ * Trades the callback's `code` for the merchant's keys, saves them encrypted and registers the webhook that
2108
+ * confirms payments. A failure of the webhook does not undo the connection: charges still work and `lookup` reads
2109
+ * the truth; call {@link ensureNotices} to retry.
2110
+ */
2111
+ async complete(input) {
2112
+ const st = this.readState(input.state);
2113
+ if (!st) throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)(this.msg.badState, void 0, "OPENPAY_ESTADO_INVALIDO");
2114
+ const { scopeId, purpose: _purpose, ts: _ts, nonce: _nonce, ...extra } = st;
2115
+ if (input.error || !input.code) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notAuthorized, { error: input.error }, "OPENPAY_NO_AUTORIZADO");
2116
+ const partner = this.partner;
2117
+ if (!partner) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notConfigured, void 0, "OPENPAY_NO_CONFIGURADO");
2118
+ const cipher = this.requireCipher();
2119
+ const sandbox = this.sandbox;
2120
+ const fetchImpl = this.http(scopeId);
2121
+ const base = this.dashboard(sandbox);
2122
+ const token = await this.oauth(
2123
+ fetchImpl,
2124
+ `${base}/oauth/token?${new URLSearchParams({
2125
+ code: input.code,
2126
+ client_id: partner.clientId,
2127
+ client_secret: partner.clientSecret,
2128
+ grant_type: "authorization_code",
2129
+ redirect_uri: partner.redirectUri
2130
+ }).toString()}`
2131
+ );
2132
+ if (!token.access_token) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notAuthorized, void 0, "OPENPAY_NO_AUTORIZADO");
2133
+ const merchant = await this.oauth(
2134
+ fetchImpl,
2135
+ `${base}/oauth/merchant?${new URLSearchParams({ access_token: token.access_token }).toString()}`
2136
+ );
2137
+ if (!merchant.merchant_id || !merchant.secret_key || !merchant.public_key)
2138
+ throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notAuthorized, void 0, "OPENPAY_NO_AUTORIZADO");
2139
+ const credentials = {
2140
+ merchantId: merchant.merchant_id,
2141
+ secretKey: merchant.secret_key,
2142
+ publicKey: merchant.public_key,
2143
+ ...token.refresh_token ? { refreshToken: token.refresh_token } : {},
2144
+ webhookPassword: _crypto.randomBytes.call(void 0, 24).toString("base64url"),
2145
+ ...merchant.merchant_status ? { merchantStatus: merchant.merchant_status } : {}
2146
+ };
2147
+ const previous = await this.o.store.find(scopeId);
2148
+ const rec = await this.o.store.upsert({
2149
+ scopeId,
2150
+ encryptedCredentials: cipher.encryptJson(credentials),
2151
+ webhookToken: _crypto.randomBytes.call(void 0, 24).toString("base64url"),
2152
+ webhookId: null,
2153
+ verificationCode: null,
2154
+ sandbox,
2155
+ active: true
2156
+ });
2157
+ if (_optionalChain([previous, 'optionalAccess', _115 => _115.webhookId])) await this.dropWebhook(previous).catch(() => void 0);
2158
+ await this.ensureNotices(scopeId).catch(
2159
+ (e) => this.log.warn(`Openpay: no se pudo registrar el webhook de ${scopeId}: ${e instanceof Error ? e.message : String(e)}`)
2160
+ );
2161
+ return { scopeId, extra, view: await this.view(scopeId, rec) };
2162
+ }
2163
+ async oauth(fetchImpl, url) {
2164
+ try {
2165
+ return await requestJson(PROVIDER5, fetchImpl, url, { headers: { accept: "application/json" } });
2166
+ } catch (e) {
2167
+ if (e instanceof TerminalPaymentProviderException)
2168
+ throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notAuthorized, e.details, "OPENPAY_NO_AUTORIZADO");
2169
+ throw e;
2170
+ }
2171
+ }
2172
+ /** Registers (or repairs) the webhook so paid sales confirm by themselves. Safe to call again. */
2173
+ async ensureNotices(scopeId) {
2174
+ const rec = await this.recordOf(scopeId);
2175
+ if (rec.webhookId && !rec.verificationCode) return true;
2176
+ const cred = this.credentialsOf(rec);
2177
+ const api = this.apiOf(rec);
2178
+ let id = rec.webhookId;
2179
+ if (!id) {
2180
+ const created = await api.createWebhook({
2181
+ url: this.o.publicWebhookUrl(rec.webhookToken),
2182
+ user: rec.webhookToken,
2183
+ password: cred.webhookPassword,
2184
+ eventTypes: WEBHOOK_EVENTS
2185
+ });
2186
+ id = created.id;
2187
+ await this.o.store.update(scopeId, { webhookId: id });
2188
+ if (created.status === "verified") return true;
2189
+ }
2190
+ const fresh = await _asyncNullishCoalesce(await this.o.store.find(scopeId), async () => ( rec));
2191
+ if (!fresh.verificationCode) return false;
2192
+ await api.verifyWebhook(id, fresh.verificationCode);
2193
+ await this.o.store.update(scopeId, { verificationCode: null });
2194
+ return true;
2195
+ }
2196
+ async dropWebhook(rec) {
2197
+ if (rec.webhookId) await this.apiOf(rec).deleteWebhook(rec.webhookId);
2198
+ }
2199
+ async view(scopeId, known) {
2200
+ const rec = known === void 0 ? await this.o.store.find(scopeId) : known;
2201
+ if (!rec || !rec.active) return { connected: false, ready: false, sandbox: this.sandbox, merchantId: null, merchantStatus: null, notices: false };
2202
+ const cred = this.cipher ? this.credentialsOf(rec) : null;
2203
+ const status = _nullishCoalesce(_optionalChain([cred, 'optionalAccess', _116 => _116.merchantStatus]), () => ( null));
2204
+ return {
2205
+ connected: true,
2206
+ ready: status === null || status === "active",
2207
+ sandbox: rec.sandbox,
2208
+ merchantId: _nullishCoalesce(_optionalChain([cred, 'optionalAccess', _117 => _117.merchantId]), () => ( null)),
2209
+ merchantStatus: status,
2210
+ notices: Boolean(rec.webhookId) && !rec.verificationCode
2211
+ };
2212
+ }
2213
+ /** Disconnects: removes the webhook (best effort) and forgets the keys. */
2214
+ async disconnect(scopeId) {
2215
+ const rec = await this.o.store.find(scopeId);
2216
+ if (!rec) return false;
2217
+ await this.dropWebhook(rec).catch(() => void 0);
2218
+ return this.o.store.delete(scopeId);
2219
+ }
2220
+ // ── charge ─────────────────────────────────────────────────────────────────
2221
+ /** Opens a charge on the merchant's account: a card link or a bank transfer with CLABE. */
2222
+ async createPayment(scopeId, p) {
2223
+ const min = _nullishCoalesce(this.o.minimumCents, () => ( 1e3));
2224
+ if (!Number.isInteger(p.amountCents) || p.amountCents < min) throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)(this.msg.minimumAmount, { minimumCents: min }, "OPENPAY_MONTO_MINIMO");
2225
+ const rec = await this.recordOf(scopeId);
2226
+ const api = this.apiOf(rec);
2227
+ if (p.method === "card") {
2228
+ if (!p.returnUrl) throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("returnUrl is required for card payments", void 0, "OPENPAY_FALTA_RETORNO");
2229
+ const link = await api.createCardLink({
2230
+ orderId: p.reference,
2231
+ description: p.description,
2232
+ amountCents: p.amountCents,
2233
+ customer: _nullishCoalesce(p.customer, () => ( { name: "Cliente" })),
2234
+ redirectUrl: p.returnUrl,
2235
+ ...p.sendEmail !== void 0 ? { sendEmail: p.sendEmail } : {},
2236
+ ...p.clientIp ? { clientIp: p.clientIp } : {}
2237
+ });
2238
+ return { method: "card", chargeId: link.chargeId, reference: p.reference, state: "pending", url: link.url, transfer: null };
2239
+ }
2240
+ const transfer = await api.createBankTransfer({
2241
+ orderId: p.reference,
2242
+ description: p.description,
2243
+ amountCents: p.amountCents,
2244
+ ...p.customer ? { customer: p.customer } : {},
2245
+ dueDate: _nullishCoalesce(p.dueDate, () => ( new Date(Date.now() + 3 * 864e5)))
2246
+ });
2247
+ return { method: "transfer", chargeId: transfer.chargeId, reference: p.reference, state: "pending", url: transfer.receiptUrl, transfer };
2248
+ }
2249
+ /** The state of a charge according to Openpay. */
2250
+ async lookup(scopeId, chargeId) {
2251
+ const rec = await this.recordOf(scopeId);
2252
+ const c = await this.apiOf(rec).getCharge(chargeId);
2253
+ return { chargeId: c.id, method: c.method, reference: c.orderId, state: c.state, paidCents: c.paidCents };
2254
+ }
2255
+ /** Gives money back on a card charge (Openpay does not refund SPEI). `amountCents` omitted = all of it. */
2256
+ async refund(scopeId, chargeId, amountCents, description) {
2257
+ const rec = await this.recordOf(scopeId);
2258
+ const api = this.apiOf(rec);
2259
+ const charge = await api.getCharge(chargeId);
2260
+ if (charge.method !== "card") throw new UnsupportedByProviderException(PROVIDER5, this.text(this.msg.refundUnsupported));
2261
+ const r = await api.refundCard(chargeId, amountCents, description);
2262
+ return { chargeId: r.id, method: r.method, reference: r.orderId, state: r.state, paidCents: r.paidCents };
2263
+ }
2264
+ text(m) {
2265
+ return typeof m === "string" ? m : m.toJSON();
2266
+ }
2267
+ // ── notices ────────────────────────────────────────────────────────────────
2268
+ /**
2269
+ * Handles a webhook call. `token` is the last segment of the URL, `authorization` the `Authorization` header (HTTP
2270
+ * Basic, user = token, password = the one stored for the merchant). A payment notice is never believed: the charge
2271
+ * is read again from Openpay and only that answer counts. Always answer 200 to what this returns; throw only for a
2272
+ * wrong password so a forged call learns nothing.
2273
+ */
2274
+ async handleNotice(token, authorization, body) {
2275
+ const rec = await this.o.store.findByWebhookToken(token);
2276
+ if (!rec || !rec.active) return { kind: "ignored" };
2277
+ const cred = this.credentialsOf(rec);
2278
+ if (!this.validBasic(authorization, rec.webhookToken, cred.webhookPassword)) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid notice", void 0, "OPENPAY_AVISO_INVALIDO");
2279
+ const n = _nullishCoalesce(body, () => ( {}));
2280
+ if (n.type === "verification" && n.verification_code) {
2281
+ await this.o.store.update(rec.scopeId, { verificationCode: n.verification_code });
2282
+ if (rec.webhookId) await this.ensureNotices(rec.scopeId).catch(() => void 0);
2283
+ return { kind: "verification", scopeId: rec.scopeId };
2284
+ }
2285
+ const id = _optionalChain([n, 'access', _118 => _118.transaction, 'optionalAccess', _119 => _119.id]);
2286
+ if (!id || !n.type || !/^(charge\.|chargeback\.|spei\.)/.test(n.type)) return { kind: "ignored" };
2287
+ const c = await this.apiOf(rec).getCharge(id);
2288
+ if (!c.orderId) return { kind: "ignored" };
2289
+ return { kind: "payment", scopeId: rec.scopeId, chargeId: c.id, reference: c.orderId, state: openpayState(c.status), paidCents: c.paidCents, method: c.method };
2290
+ }
2291
+ validBasic(header, user, password) {
2292
+ if (!_optionalChain([header, 'optionalAccess', _120 => _120.startsWith, 'call', _121 => _121("Basic ")])) return false;
2293
+ const given = Buffer.from(header.slice(6), "base64");
2294
+ const want = Buffer.from(`${user}:${password}`);
2295
+ return given.length === want.length && _crypto.timingSafeEqual.call(void 0, given, want);
2296
+ }
2297
+ };
2298
+
2299
+
2300
+
2301
+
2302
+
1810
2303
 
1811
2304
 
1812
2305
 
@@ -1843,4 +2336,4 @@ var TerminalConnections = class {
1843
2336
 
1844
2337
 
1845
2338
 
1846
- exports.ALWAYS_OPEN = ALWAYS_OPEN; exports.ClipTerminalPayments = ClipTerminalPayments; exports.CredentialsCipher = CredentialsCipher; exports.DEFAULT_REFUND_MESSAGES = DEFAULT_REFUND_MESSAGES; exports.DEFINITIVE_REFUND_REJECTIONS = DEFINITIVE_REFUND_REJECTIONS; exports.IDEMPOTENCY_WINDOW_MS = IDEMPOTENCY_WINDOW_MS; exports.MercadoPagoConnect = MercadoPagoConnect; exports.MercadoPagoRefunds = MercadoPagoRefunds; exports.MercadoPagoTerminalPayments = MercadoPagoTerminalPayments; exports.OnlineCheckoutClient = OnlineCheckoutClient; exports.PAYMENTS_OPTIONS = PAYMENTS_OPTIONS; exports.PaymentsModule = PaymentsModule; exports.TERMINAL_PAYMENTS = TERMINAL_PAYMENTS; exports.TerminalConnections = TerminalConnections; exports.TerminalPaymentProviderException = TerminalPaymentProviderException; exports.UnsupportedByProviderException = UnsupportedByProviderException; exports.assertCents = assertCents; exports.centsOf = centsOf; exports.centsToDecimalString = centsToDecimalString; exports.classifyRefundError = classifyRefundError; exports.clipStatus = clipStatus; exports.createTerminalPaymentsAdapter = createTerminalPaymentsAdapter; exports.createTerminalPaymentsWebhookController = createTerminalPaymentsWebhookController; exports.decimalToCents = decimalToCents; exports.defaultStoreLocation = defaultStoreLocation; exports.interpretOrder = interpretOrder; exports.isIntegrableTerminalModel = isIntegrableTerminalModel; exports.isTransientStatus = isTransientStatus; exports.mercadoPagoStatus = mercadoPagoStatus; exports.paymentOfOrder = paymentOfOrder; exports.refundErrorCode = refundErrorCode; exports.refundErrorMessage = refundErrorMessage; exports.resolvePaymentsOptions = resolvePaymentsOptions; exports.resolveTerminalStatus = resolveTerminalStatus; exports.summarizeProviderRejection = summarizeProviderRejection; exports.verifyMercadoPagoSignature = verifyMercadoPagoSignature;
2339
+ exports.ALWAYS_OPEN = ALWAYS_OPEN; exports.ClipTerminalPayments = ClipTerminalPayments; exports.CredentialsCipher = CredentialsCipher; exports.DEFAULT_REFUND_MESSAGES = DEFAULT_REFUND_MESSAGES; exports.DEFINITIVE_REFUND_REJECTIONS = DEFINITIVE_REFUND_REJECTIONS; exports.IDEMPOTENCY_WINDOW_MS = IDEMPOTENCY_WINDOW_MS; exports.MercadoPagoConnect = MercadoPagoConnect; exports.MercadoPagoRefunds = MercadoPagoRefunds; exports.MercadoPagoTerminalPayments = MercadoPagoTerminalPayments; exports.OPENPAY_PROVIDER_ERROR = OPENPAY_PROVIDER_ERROR; exports.OnlineCheckoutClient = OnlineCheckoutClient; exports.OpenpayApi = OpenpayApi; exports.OpenpayConnections = OpenpayConnections; exports.PAYMENTS_OPTIONS = PAYMENTS_OPTIONS; exports.PaymentsModule = PaymentsModule; exports.TERMINAL_PAYMENTS = TERMINAL_PAYMENTS; exports.TerminalConnections = TerminalConnections; exports.TerminalPaymentProviderException = TerminalPaymentProviderException; exports.UnsupportedByProviderException = UnsupportedByProviderException; exports.assertCents = assertCents; exports.centsOf = centsOf; exports.centsToDecimalString = centsToDecimalString; exports.classifyRefundError = classifyRefundError; exports.clipStatus = clipStatus; exports.createTerminalPaymentsAdapter = createTerminalPaymentsAdapter; exports.createTerminalPaymentsWebhookController = createTerminalPaymentsWebhookController; exports.decimalToCents = decimalToCents; exports.defaultStoreLocation = defaultStoreLocation; exports.interpretOrder = interpretOrder; exports.isIntegrableTerminalModel = isIntegrableTerminalModel; exports.isTransientStatus = isTransientStatus; exports.mercadoPagoStatus = mercadoPagoStatus; exports.openpayState = openpayState; exports.paymentOfOrder = paymentOfOrder; exports.refundErrorCode = refundErrorCode; exports.refundErrorMessage = refundErrorMessage; exports.resolvePaymentsOptions = resolvePaymentsOptions; exports.resolveTerminalStatus = resolveTerminalStatus; exports.summarizeProviderRejection = summarizeProviderRejection; exports.verifyMercadoPagoSignature = verifyMercadoPagoSignature;
@@ -22,3 +22,7 @@ export { OnlineCheckoutClient } from './connect/online-checkout.js';
22
22
  export type { OnlineCheckoutProvider, OnlineCheckoutCredentials, CreateOnlineCheckout, OnlineCheckout, OnlinePaymentState, OnlineCheckoutLookup, OnlineCheckoutMessages, OnlineCheckoutOptions, } from './connect/online-checkout.js';
23
23
  export { TerminalConnections, ALWAYS_OPEN, defaultStoreLocation } from './connect/terminal-connections.js';
24
24
  export type { ConnectionProvider, MercadoPagoCredentials, ClipCredentials, ConnectionCredentials, ConnectionRecord, TerminalConnectionStore, ConnectionView, TerminalSummary, TerminalCharge, TerminalConnectionsOptions, OAuthStatePayload, } from './connect/terminal-connections.js';
25
+ export { OpenpayApi, openpayState, OPENPAY_PROVIDER_ERROR } from './openpay/openpay-api.js';
26
+ export type { OpenpayCredentials, OpenpayMethod, OpenpayPaymentState, OpenpayCustomer, OpenpayApiOptions, OpenpayApiMessages, CreateCardLink, CardLink, CreateBankTransfer, BankTransfer, OpenpayCharge, OpenpayWebhook, } from './openpay/openpay-api.js';
27
+ export { OpenpayConnections } from './openpay/openpay-connections.js';
28
+ export type { OpenpayStoredCredentials, OpenpayConnectionRecord, OpenpayConnectionStore, OpenpayPartner, OpenpayMessageKey, OpenpayConnectionsOptions, OpenpayConnectionView, OpenpayPaymentInput, OpenpayPayment, OpenpayLookup, OpenpayNotice, } from './openpay/openpay-connections.js';