@miguelmorales13/nestkit 0.29.0 → 0.31.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 +49 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/payments/index.cjs +494 -1
- package/dist/payments/index.d.ts +4 -0
- package/dist/payments/index.js +493 -0
- package/dist/payments/openpay/openpay-api.d.ts +127 -0
- package/dist/payments/openpay/openpay-connections.d.ts +201 -0
- package/dist/printing/escpos.d.ts +26 -0
- package/dist/printing/index.cjs +302 -0
- package/dist/printing/index.d.ts +7 -0
- package/dist/printing/index.js +302 -0
- package/dist/printing/memory.store.d.ts +58 -0
- package/dist/printing/print-queue.d.ts +28 -0
- package/dist/printing/printer-status.d.ts +10 -0
- package/dist/printing/printing.types.d.ts +96 -0
- package/package.json +6 -1
package/dist/payments/index.js
CHANGED
|
@@ -1806,6 +1806,495 @@ var TerminalConnections = class {
|
|
|
1806
1806
|
});
|
|
1807
1807
|
}
|
|
1808
1808
|
};
|
|
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(amount ?? 0) * 100);
|
|
1823
|
+
function openpayState(status) {
|
|
1824
|
+
switch ((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 = o.fetchImpl ?? fetch;
|
|
1844
|
+
this.base = (o.apiBaseUrl ?? (o.sandbox ? API_SANDBOX : API_PRODUCTION)).replace(/\/$/, "");
|
|
1845
|
+
this.dashboard = (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 ConflictAppException(failure, 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: c.sendEmail ?? false,
|
|
1892
|
+
redirect_url: c.redirectUrl
|
|
1893
|
+
})
|
|
1894
|
+
},
|
|
1895
|
+
this.msg.notOpened
|
|
1896
|
+
);
|
|
1897
|
+
const url = r.payment_method?.url;
|
|
1898
|
+
if (!r.id || !url) throw new 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 || !pm?.clabe || !pm.name)
|
|
1922
|
+
throw new 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: pm.bank ?? "BBVA",
|
|
1928
|
+
agreement: 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) : c.dueDate ?? null
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
shape(r) {
|
|
1934
|
+
const state = openpayState(r.status);
|
|
1935
|
+
const type = r.payment_method?.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: r.id ?? "",
|
|
1939
|
+
state,
|
|
1940
|
+
status: r.status ?? "",
|
|
1941
|
+
method,
|
|
1942
|
+
orderId: 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 ConflictAppException(this.msg.noAnswer, { provider: PROVIDER4 }, OPENPAY_PROVIDER_ERROR);
|
|
1989
|
+
return { id: r.id, status: 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
|
+
import { Logger as Logger2 } from "@nestjs/common";
|
|
2006
|
+
import { randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
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 Logger2("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() : 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 (this.o.dashboardBaseUrl ?? (sandbox ? DASHBOARD_SANDBOX2 : DASHBOARD_PRODUCTION2)).replace(/\/$/, "");
|
|
2048
|
+
}
|
|
2049
|
+
http(scopeId) {
|
|
2050
|
+
return this.o.fetchImpl?.(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 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 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 ConflictAppException(this.msg.notConfigured, void 0, "OPENPAY_NO_CONFIGURADO");
|
|
2089
|
+
const state = signState({ ...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 = readState(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 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 ConflictAppException(this.msg.notAuthorized, { error: input.error }, "OPENPAY_NO_AUTORIZADO");
|
|
2116
|
+
const partner = this.partner;
|
|
2117
|
+
if (!partner) throw new 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 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 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: randomBytes3(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: randomBytes3(24).toString("base64url"),
|
|
2152
|
+
webhookId: null,
|
|
2153
|
+
verificationCode: null,
|
|
2154
|
+
sandbox,
|
|
2155
|
+
active: true
|
|
2156
|
+
});
|
|
2157
|
+
if (previous?.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 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 this.o.store.find(scopeId) ?? 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 = cred?.merchantStatus ?? null;
|
|
2204
|
+
return {
|
|
2205
|
+
connected: true,
|
|
2206
|
+
ready: status === null || status === "active",
|
|
2207
|
+
sandbox: rec.sandbox,
|
|
2208
|
+
merchantId: cred?.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 = this.o.minimumCents ?? 1e3;
|
|
2224
|
+
if (!Number.isInteger(p.amountCents) || p.amountCents < min) throw new 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 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: 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: 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 UnauthorizedAppException("Invalid notice", void 0, "OPENPAY_AVISO_INVALIDO");
|
|
2279
|
+
const n = 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 = n.transaction?.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 (!header?.startsWith("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 && timingSafeEqual5(given, want);
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
1809
2298
|
export {
|
|
1810
2299
|
ALWAYS_OPEN,
|
|
1811
2300
|
ClipTerminalPayments,
|
|
@@ -1816,7 +2305,10 @@ export {
|
|
|
1816
2305
|
MercadoPagoConnect,
|
|
1817
2306
|
MercadoPagoRefunds,
|
|
1818
2307
|
MercadoPagoTerminalPayments,
|
|
2308
|
+
OPENPAY_PROVIDER_ERROR,
|
|
1819
2309
|
OnlineCheckoutClient,
|
|
2310
|
+
OpenpayApi,
|
|
2311
|
+
OpenpayConnections,
|
|
1820
2312
|
PAYMENTS_OPTIONS,
|
|
1821
2313
|
PaymentsModule,
|
|
1822
2314
|
TERMINAL_PAYMENTS,
|
|
@@ -1836,6 +2328,7 @@ export {
|
|
|
1836
2328
|
isIntegrableTerminalModel,
|
|
1837
2329
|
isTransientStatus,
|
|
1838
2330
|
mercadoPagoStatus,
|
|
2331
|
+
openpayState,
|
|
1839
2332
|
paymentOfOrder,
|
|
1840
2333
|
refundErrorCode,
|
|
1841
2334
|
refundErrorMessage,
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { I18nMessage } from '../../i18n/message.js';
|
|
2
|
+
/** A merchant's own Openpay keys, as `/oauth/merchant` returns them. The money goes to THEIR account. */
|
|
3
|
+
export interface OpenpayCredentials {
|
|
4
|
+
merchantId: string;
|
|
5
|
+
secretKey: string;
|
|
6
|
+
publicKey: string;
|
|
7
|
+
}
|
|
8
|
+
export type OpenpayMethod = 'card' | 'transfer';
|
|
9
|
+
/** What a charge is, seen from the seller. `refunded` covers a chargeback too: the money went back. */
|
|
10
|
+
export type OpenpayPaymentState = 'paid' | 'pending' | 'failed' | 'refunded';
|
|
11
|
+
export interface OpenpayCustomer {
|
|
12
|
+
name: string;
|
|
13
|
+
lastName?: string;
|
|
14
|
+
email?: string;
|
|
15
|
+
phone?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface OpenpayApiOptions {
|
|
18
|
+
sandbox?: boolean;
|
|
19
|
+
/** Pass the fetch you use for Openpay (timeouts, retries, alerts). Defaults to the global `fetch`. */
|
|
20
|
+
fetchImpl?: typeof fetch;
|
|
21
|
+
/** Test doubles. */
|
|
22
|
+
apiBaseUrl?: string;
|
|
23
|
+
dashboardBaseUrl?: string;
|
|
24
|
+
messages?: Partial<OpenpayApiMessages>;
|
|
25
|
+
}
|
|
26
|
+
/** Error messages. Override to translate; defaults are Spanish. */
|
|
27
|
+
export interface OpenpayApiMessages {
|
|
28
|
+
notOpened: string | I18nMessage;
|
|
29
|
+
noAnswer: string | I18nMessage;
|
|
30
|
+
}
|
|
31
|
+
/** Fixed code so the front decides by code, not by text. */
|
|
32
|
+
export declare const OPENPAY_PROVIDER_ERROR = "PAGO_PROVEEDOR_ERROR";
|
|
33
|
+
export interface CreateCardLink {
|
|
34
|
+
/** Your id for the sale. Openpay refuses a second charge with the same one (error 1006), so a retry cannot charge twice. */
|
|
35
|
+
orderId: string;
|
|
36
|
+
description: string;
|
|
37
|
+
amountCents: number;
|
|
38
|
+
customer: OpenpayCustomer;
|
|
39
|
+
/** Where the buyer lands after paying. */
|
|
40
|
+
redirectUrl: string;
|
|
41
|
+
/** Openpay emails the link to `customer.email`. */
|
|
42
|
+
sendEmail?: boolean;
|
|
43
|
+
/** Openpay asks for the buyer's IP on card charges (anti-fraud). Send it when you have it. */
|
|
44
|
+
clientIp?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface CardLink {
|
|
47
|
+
chargeId: string;
|
|
48
|
+
/** Openpay's hosted card form. */
|
|
49
|
+
url: string;
|
|
50
|
+
}
|
|
51
|
+
export interface CreateBankTransfer {
|
|
52
|
+
orderId: string;
|
|
53
|
+
description: string;
|
|
54
|
+
amountCents: number;
|
|
55
|
+
customer?: OpenpayCustomer;
|
|
56
|
+
/** Last day to pay. Openpay expires on business days, so a Friday ends on Monday. Max 30 days. */
|
|
57
|
+
dueDate?: Date;
|
|
58
|
+
}
|
|
59
|
+
export interface BankTransfer {
|
|
60
|
+
chargeId: string;
|
|
61
|
+
/** Destination account for the SPEI transfer (18 digits). */
|
|
62
|
+
clabe: string;
|
|
63
|
+
/** What the buyer types as the concept (20 digits). Openpay matches the payment with it. */
|
|
64
|
+
reference: string;
|
|
65
|
+
bank: string;
|
|
66
|
+
/** CIE agreement number, for paying from BBVA online banking. */
|
|
67
|
+
agreement: string;
|
|
68
|
+
/** Openpay's printable receipt. Only available while the charge is pending. */
|
|
69
|
+
receiptUrl: string;
|
|
70
|
+
dueDate: Date | null;
|
|
71
|
+
}
|
|
72
|
+
export interface OpenpayCharge {
|
|
73
|
+
id: string;
|
|
74
|
+
state: OpenpayPaymentState;
|
|
75
|
+
/** Raw Openpay status (`completed`, `in_progress`, `charge_pending`, `cancelled`, `failed`, `refunded`…). */
|
|
76
|
+
status: string;
|
|
77
|
+
method: OpenpayMethod | 'store' | 'other';
|
|
78
|
+
orderId: string | null;
|
|
79
|
+
amountCents: number;
|
|
80
|
+
/** What was collected, in cents; `null` until it is paid. */
|
|
81
|
+
paidCents: number | null;
|
|
82
|
+
dueDate: Date | null;
|
|
83
|
+
}
|
|
84
|
+
export interface OpenpayWebhook {
|
|
85
|
+
id: string;
|
|
86
|
+
status: 'verified' | 'unverified' | string;
|
|
87
|
+
}
|
|
88
|
+
/** Openpay's charge status → what the seller needs to know. Anything unknown stays `pending`: never invent a payment. */
|
|
89
|
+
export declare function openpayState(status: string | undefined): OpenpayPaymentState;
|
|
90
|
+
/**
|
|
91
|
+
* Openpay's REST API for ONE merchant, with that merchant's own keys. Creates the card link and the bank (SPEI)
|
|
92
|
+
* transfer, reads a charge, refunds a card charge and manages the webhook. The state of a payment is always read
|
|
93
|
+
* from Openpay, never from what a buyer or a notification body says.
|
|
94
|
+
*/
|
|
95
|
+
export declare class OpenpayApi {
|
|
96
|
+
private readonly cred;
|
|
97
|
+
private readonly msg;
|
|
98
|
+
private readonly http;
|
|
99
|
+
private readonly base;
|
|
100
|
+
private readonly dashboard;
|
|
101
|
+
constructor(cred: OpenpayCredentials, o?: OpenpayApiOptions);
|
|
102
|
+
private url;
|
|
103
|
+
private headers;
|
|
104
|
+
private customerBody;
|
|
105
|
+
/** `requestJson` with the error shaped for the app: provider failures keep their body; duplicates keep their code. */
|
|
106
|
+
private call;
|
|
107
|
+
/** Card: Openpay's hosted form (a "virtual terminal" charge). Pays with any card; the buyer never touches your server. */
|
|
108
|
+
createCardLink(c: CreateCardLink): Promise<CardLink>;
|
|
109
|
+
/** Bank: a CLABE plus a 20-digit reference. The buyer pays from any bank by SPEI; Openpay confirms it by webhook. */
|
|
110
|
+
createBankTransfer(c: CreateBankTransfer): Promise<BankTransfer>;
|
|
111
|
+
private shape;
|
|
112
|
+
getCharge(chargeId: string): Promise<OpenpayCharge>;
|
|
113
|
+
/** Your own id is the way back when you only have the sale (the notice carries both). */
|
|
114
|
+
findByOrderId(orderId: string): Promise<OpenpayCharge | null>;
|
|
115
|
+
/** Card charges only: Openpay does not refund SPEI. `amountCents` omitted = the whole charge. */
|
|
116
|
+
refundCard(chargeId: string, amountCents?: number, description?: string): Promise<OpenpayCharge>;
|
|
117
|
+
/** Notices go to `url` with HTTP Basic (`user`/`password`), the only authentication Openpay supports. */
|
|
118
|
+
createWebhook(w: {
|
|
119
|
+
url: string;
|
|
120
|
+
user: string;
|
|
121
|
+
password: string;
|
|
122
|
+
eventTypes: string[];
|
|
123
|
+
}): Promise<OpenpayWebhook>;
|
|
124
|
+
/** Activates a webhook with the code Openpay sent to its URL in the `verification` notice. */
|
|
125
|
+
verifyWebhook(webhookId: string, code: string): Promise<void>;
|
|
126
|
+
deleteWebhook(webhookId: string): Promise<void>;
|
|
127
|
+
}
|