@miguelmorales13/nestkit 0.28.0 → 0.29.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 +69 -0
- package/dist/chunk-33KFVAUZ.cjs +151 -0
- package/dist/chunk-LU3HO7B3.js +151 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/payments/connect/credentials-cipher.d.ts +14 -0
- package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
- package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
- package/dist/payments/connect/online-checkout.d.ts +69 -0
- package/dist/payments/connect/rejection.d.ts +7 -0
- package/dist/payments/connect/status.d.ts +20 -0
- package/dist/payments/connect/terminal-connections.d.ts +291 -0
- package/dist/payments/index.cjs +901 -3
- package/dist/payments/index.d.ts +10 -0
- package/dist/payments/index.js +899 -1
- package/dist/security/index.cjs +27 -152
- package/dist/security/index.js +13 -138
- package/package.json +2 -2
package/dist/payments/index.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
|
+
readState,
|
|
3
|
+
signState
|
|
4
|
+
} from "../chunk-LU3HO7B3.js";
|
|
5
|
+
import "../chunk-DQYAIQQ5.js";
|
|
6
|
+
import "../chunk-5LVGCTJ3.js";
|
|
7
|
+
import "../chunk-X4PQJZ4G.js";
|
|
8
|
+
import "../chunk-TCAMLNUZ.js";
|
|
9
|
+
import "../chunk-ETRUVZTJ.js";
|
|
10
|
+
import {
|
|
11
|
+
ConflictAppException,
|
|
12
|
+
NotFoundAppException,
|
|
2
13
|
UnauthorizedAppException,
|
|
3
14
|
ValidationAppException
|
|
4
15
|
} from "../chunk-ZFIDAX7K.js";
|
|
@@ -929,20 +940,907 @@ var MercadoPagoConnect = class {
|
|
|
929
940
|
};
|
|
930
941
|
}
|
|
931
942
|
};
|
|
943
|
+
|
|
944
|
+
// src/payments/connect/status.ts
|
|
945
|
+
var APPROVED = ["COMPLETED", "APPROVED", "PAID", "SUCCESS", "SUCCEEDED", "SUCCESSFUL", "AUTHORIZED"];
|
|
946
|
+
var REJECTED = ["FAILED", "DECLINED", "REJECTED", "DENIED", "ERROR"];
|
|
947
|
+
var CANCELLED = ["CANCELLED", "CANCELED", "VOIDED"];
|
|
948
|
+
var EXPIRED = ["EXPIRED", "TIMEOUT", "TIMED_OUT"];
|
|
949
|
+
var PENDING = ["PENDING", "PROCESSING", "IN_PROGRESS", "CREATED", "QUEUED", "SENT"];
|
|
950
|
+
function clipStatus(p) {
|
|
951
|
+
if (p.status !== "unknown") return p.status;
|
|
952
|
+
const raw = p.raw ?? {};
|
|
953
|
+
const text = typeof raw.status === "string" ? raw.status.trim().toUpperCase().replace(/[\s-]+/g, "_") : "";
|
|
954
|
+
if (APPROVED.includes(text)) return "approved";
|
|
955
|
+
if (REJECTED.includes(text)) return "rejected";
|
|
956
|
+
if (CANCELLED.includes(text)) return "cancelled";
|
|
957
|
+
if (EXPIRED.includes(text)) return "expired";
|
|
958
|
+
if (PENDING.includes(text)) return "pending";
|
|
959
|
+
if ((p.paidCents ?? 0) > 0) return "approved";
|
|
960
|
+
return "unknown";
|
|
961
|
+
}
|
|
962
|
+
function mercadoPagoStatus(p) {
|
|
963
|
+
if (p.status !== "unknown") return p.status;
|
|
964
|
+
const order = p.raw ?? {};
|
|
965
|
+
const text = typeof order.status === "string" ? order.status.trim().toLowerCase() : "";
|
|
966
|
+
if (text === "processing") return "at_terminal";
|
|
967
|
+
if (text === "partially_refunded" || text === "approved" || text === "paid") return "approved";
|
|
968
|
+
if (text === "cancelled") return "cancelled";
|
|
969
|
+
if (text === "rejected") return "rejected";
|
|
970
|
+
const payments = order.transactions?.payments ?? [];
|
|
971
|
+
const credited = payments.some(
|
|
972
|
+
(x) => ["processed", "approved", "accredited"].includes(String(x.status ?? "").toLowerCase())
|
|
973
|
+
);
|
|
974
|
+
if (credited && (p.paidCents ?? 0) > 0) return "approved";
|
|
975
|
+
return "unknown";
|
|
976
|
+
}
|
|
977
|
+
function resolveTerminalStatus(p) {
|
|
978
|
+
if (p.status !== "unknown") return p.status;
|
|
979
|
+
return p.provider === "clip" ? clipStatus(p) : mercadoPagoStatus(p);
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// src/payments/connect/rejection.ts
|
|
983
|
+
function summarizeProviderRejection(error, limit = 600) {
|
|
984
|
+
if (!(error instanceof TerminalPaymentProviderException)) return null;
|
|
985
|
+
const { provider, status, body } = error.details ?? {};
|
|
986
|
+
let text;
|
|
987
|
+
try {
|
|
988
|
+
text = typeof body === "string" ? body : JSON.stringify(body);
|
|
989
|
+
} catch {
|
|
990
|
+
text = String(body);
|
|
991
|
+
}
|
|
992
|
+
const cut = (text ?? "").length > limit ? `${text.slice(0, limit)}\u2026` : text ?? "";
|
|
993
|
+
return `${provider ?? "proveedor"} respondi\xF3 HTTP ${status ?? "sin respuesta"}: ${cut || "(sin cuerpo)"}`;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// src/payments/connect/mercadopago-signature.ts
|
|
997
|
+
import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
998
|
+
function verifyMercadoPagoSignature(secret, dataId, xSignature, xRequestId) {
|
|
999
|
+
if (!xSignature) return false;
|
|
1000
|
+
const parts = Object.fromEntries(
|
|
1001
|
+
xSignature.split(",").map((p) => {
|
|
1002
|
+
const i = p.indexOf("=");
|
|
1003
|
+
return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
|
|
1004
|
+
})
|
|
1005
|
+
);
|
|
1006
|
+
const { ts, v1 } = parts;
|
|
1007
|
+
if (!ts || !v1) return false;
|
|
1008
|
+
const manifest = (dataId ? `id:${dataId.toLowerCase()};` : "") + (xRequestId ? `request-id:${xRequestId};` : "") + `ts:${ts};`;
|
|
1009
|
+
const expected = Buffer.from(createHmac2("sha256", secret).update(manifest).digest("hex"));
|
|
1010
|
+
const received = Buffer.from(v1);
|
|
1011
|
+
return expected.length === received.length && timingSafeEqual3(expected, received);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// src/payments/connect/credentials-cipher.ts
|
|
1015
|
+
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
|
|
1016
|
+
var CredentialsCipher = class _CredentialsCipher {
|
|
1017
|
+
constructor(key) {
|
|
1018
|
+
this.key = key;
|
|
1019
|
+
if (key.length !== 32) throw new Error("CredentialsCipher: the key must be 32 bytes (64 hex characters).");
|
|
1020
|
+
}
|
|
1021
|
+
/** `null` when the value is missing or not 64 hex chars: the feature that needs it should switch itself off. */
|
|
1022
|
+
static fromHex(hex) {
|
|
1023
|
+
if (!hex || !/^[0-9a-fA-F]{64}$/.test(hex)) return null;
|
|
1024
|
+
return new _CredentialsCipher(Buffer.from(hex, "hex"));
|
|
1025
|
+
}
|
|
1026
|
+
encrypt(text) {
|
|
1027
|
+
const iv = randomBytes(12);
|
|
1028
|
+
const c = createCipheriv("aes-256-gcm", this.key, iv);
|
|
1029
|
+
const data = Buffer.concat([c.update(text, "utf8"), c.final()]);
|
|
1030
|
+
return [iv, c.getAuthTag(), data].map((b) => b.toString("base64")).join(".");
|
|
1031
|
+
}
|
|
1032
|
+
decrypt(packed) {
|
|
1033
|
+
const [iv, tag, data] = packed.split(".").map((p) => Buffer.from(p, "base64"));
|
|
1034
|
+
const d = createDecipheriv("aes-256-gcm", this.key, iv);
|
|
1035
|
+
d.setAuthTag(tag);
|
|
1036
|
+
return Buffer.concat([d.update(data), d.final()]).toString("utf8");
|
|
1037
|
+
}
|
|
1038
|
+
encryptJson(value) {
|
|
1039
|
+
return this.encrypt(JSON.stringify(value));
|
|
1040
|
+
}
|
|
1041
|
+
decryptJson(packed) {
|
|
1042
|
+
return JSON.parse(this.decrypt(packed));
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
// src/payments/connect/mercadopago-refund.ts
|
|
1047
|
+
var IDEMPOTENCY_WINDOW_MS = 23 * 36e5;
|
|
1048
|
+
var centsOf = (v) => Math.round(Number(v ?? 0) * 100);
|
|
1049
|
+
var pesos = (c) => (c / 100).toFixed(2);
|
|
1050
|
+
var CONFIRMED = /* @__PURE__ */ new Set(["processed", "approved", "refunded", "accredited"]);
|
|
1051
|
+
var REJECTED2 = /* @__PURE__ */ new Set(["failed", "rejected", "canceled", "cancelled", "expired"]);
|
|
1052
|
+
function paymentOfOrder(o) {
|
|
1053
|
+
const p = o.transactions?.payments?.[0];
|
|
1054
|
+
return {
|
|
1055
|
+
paymentId: typeof p?.id === "string" ? p.id : null,
|
|
1056
|
+
collectedCents: centsOf(p?.paid_amount ?? p?.amount ?? o.total_amount)
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
var DEFAULT_REFUND_MESSAGES = {
|
|
1060
|
+
notYetListed: "Mercado Pago todav\xEDa no muestra este reembolso.",
|
|
1061
|
+
processing: "Mercado Pago est\xE1 procesando el reembolso.",
|
|
1062
|
+
rejected: "Mercado Pago rechaz\xF3 el reembolso.",
|
|
1063
|
+
rejectedWith: (reason) => `Mercado Pago rechaz\xF3 el reembolso: ${reason}`
|
|
1064
|
+
};
|
|
1065
|
+
function interpretOrder(o, wanted, messages = DEFAULT_REFUND_MESSAGES) {
|
|
1066
|
+
const list = (o.transactions?.refunds ?? []).filter(
|
|
1067
|
+
(r) => typeof r?.id === "string"
|
|
1068
|
+
);
|
|
1069
|
+
const ours = wanted.providerRefundId ? list.find((r) => r.id === wanted.providerRefundId) : [...list].reverse().find((r) => !wanted.claimed.includes(r.id) && centsOf(r.amount) === wanted.amountCents);
|
|
1070
|
+
if (!ours) return { status: "pending", providerRefundId: wanted.providerRefundId, detail: messages.notYetListed };
|
|
1071
|
+
const st = String(ours.status ?? "").toLowerCase();
|
|
1072
|
+
if (CONFIRMED.has(st)) return { status: "confirmed", providerRefundId: ours.id, detail: null };
|
|
1073
|
+
if (REJECTED2.has(st)) return { status: "rejected", providerRefundId: ours.id, detail: messages.rejected };
|
|
1074
|
+
return { status: "pending", providerRefundId: ours.id, detail: messages.processing };
|
|
1075
|
+
}
|
|
1076
|
+
function refundErrorMessage(body, messages = DEFAULT_REFUND_MESSAGES) {
|
|
1077
|
+
const c = body ?? {};
|
|
1078
|
+
const m = c.errors?.[0]?.message ?? c.message;
|
|
1079
|
+
return typeof m === "string" && m.trim() ? messages.rejectedWith(m.trim().slice(0, 200)) : messages.rejected;
|
|
1080
|
+
}
|
|
1081
|
+
function refundErrorCode(body) {
|
|
1082
|
+
const c = body ?? {};
|
|
1083
|
+
const v = c.errors?.[0]?.code ?? c.error ?? c.code;
|
|
1084
|
+
return typeof v === "string" && v ? v : null;
|
|
1085
|
+
}
|
|
1086
|
+
var DEFINITIVE_REFUND_REJECTIONS = {
|
|
1087
|
+
unsupported_partially_refunds: "Mercado Pago no permite reembolsar solo una parte de este cobro. Devuelve el dinero desde tu app de Mercado Pago y m\xE1rcalo como manual.",
|
|
1088
|
+
partial_refund_forbidden_with_tips: "Este cobro llev\xF3 propina y Mercado Pago no permite reembolsos parciales con propina. Hazlo desde tu app de Mercado Pago y m\xE1rcalo como manual.",
|
|
1089
|
+
refund_amount_exceeds: "El monto excede lo que queda por reembolsar de este cobro en Mercado Pago.",
|
|
1090
|
+
amount_not_refundable: "Mercado Pago no puede reembolsar este monto. Revisa el cobro en tu cuenta.",
|
|
1091
|
+
payment_not_refundable: "Mercado Pago no permite reembolsar este pago (revisa el medio de pago).",
|
|
1092
|
+
max_refunds_exceeded: "Este cobro ya lleg\xF3 al m\xE1ximo de reembolsos que permite Mercado Pago.",
|
|
1093
|
+
order_already_refunded: "Mercado Pago indica que este cobro ya fue reembolsado por completo (quiz\xE1 desde su app). M\xE1rcalo como manual.",
|
|
1094
|
+
cannot_refund_order: "El estado de este cobro en Mercado Pago no permite reembolsarlo.",
|
|
1095
|
+
action_not_allowed_for_current_state: "El estado de este cobro en Mercado Pago no permite reembolsarlo.",
|
|
1096
|
+
refund_period_exceeded: "Pas\xF3 el plazo de 90 d\xEDas que da Mercado Pago para reembolsar este cobro. Devu\xE9lvelo por otro medio y m\xE1rcalo como manual.",
|
|
1097
|
+
insufficient_money_for_refund: "Tu cuenta de Mercado Pago no tiene saldo suficiente para este reembolso. Abona saldo y reintenta.",
|
|
1098
|
+
transaction_not_found: "Mercado Pago no encuentra el pago de este cobro.",
|
|
1099
|
+
order_not_found: "Mercado Pago no encuentra este cobro en la cuenta conectada.",
|
|
1100
|
+
invalid_path_param: "El identificador del cobro no es v\xE1lido para Mercado Pago.",
|
|
1101
|
+
unauthorized: "La conexi\xF3n con Mercado Pago ya no es v\xE1lida: vuelve a conectar la cuenta.",
|
|
1102
|
+
user_not_authorized: "La cuenta conectada de Mercado Pago no tiene permiso para este reembolso."
|
|
1103
|
+
};
|
|
1104
|
+
var TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
1105
|
+
"refund_in_progress",
|
|
1106
|
+
"movement_operations_pending",
|
|
1107
|
+
"order_payment_not_yet_enabled_for_refund",
|
|
1108
|
+
"idempotency_validation_failed",
|
|
1109
|
+
// Same key with another body within 24 h: the first may have gone through; verify on the order, do not reject.
|
|
1110
|
+
"idempotency_key_already_used"
|
|
1111
|
+
]);
|
|
1112
|
+
var isTransientStatus = (status) => status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
|
|
1113
|
+
function classifyRefundError(status, body, messages = DEFAULT_REFUND_MESSAGES) {
|
|
1114
|
+
const code = refundErrorCode(body);
|
|
1115
|
+
if (code && TRANSIENT_CODES.has(code)) return { transient: true };
|
|
1116
|
+
if (code && DEFINITIVE_REFUND_REJECTIONS[code]) return { transient: false, detail: DEFINITIVE_REFUND_REJECTIONS[code] };
|
|
1117
|
+
if (isTransientStatus(status)) return { transient: true };
|
|
1118
|
+
return { transient: false, detail: refundErrorMessage(body, messages) };
|
|
1119
|
+
}
|
|
1120
|
+
var MercadoPagoRefunds = class {
|
|
1121
|
+
constructor(o) {
|
|
1122
|
+
this.o = o;
|
|
1123
|
+
}
|
|
1124
|
+
get base() {
|
|
1125
|
+
return (this.o.baseUrl ?? "https://api.mercadopago.com").replace(/\/$/, "");
|
|
1126
|
+
}
|
|
1127
|
+
get http() {
|
|
1128
|
+
return this.o.fetchImpl ?? fetch;
|
|
1129
|
+
}
|
|
1130
|
+
headers(extra = {}) {
|
|
1131
|
+
return { authorization: `Bearer ${this.o.accessToken}`, "content-type": "application/json", ...extra };
|
|
1132
|
+
}
|
|
1133
|
+
/** The order, or `null` if it does not exist in this account (404). Throws if Mercado Pago does not answer. */
|
|
1134
|
+
async order(orderId) {
|
|
1135
|
+
const res = await this.http(`${this.base}/v1/orders/${encodeURIComponent(orderId)}`, {
|
|
1136
|
+
method: "GET",
|
|
1137
|
+
headers: this.headers()
|
|
1138
|
+
});
|
|
1139
|
+
const body = await res.json().catch(() => null);
|
|
1140
|
+
return { status: res.status, order: res.ok ? body : null };
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Asks for the refund. `amountCents` equal to everything collected = total refund (empty body, as documented);
|
|
1144
|
+
* less = partial with `transactions: [{ id, amount }]`. Returns the HTTP status and raw body: the caller decides.
|
|
1145
|
+
*/
|
|
1146
|
+
async refund(a) {
|
|
1147
|
+
if (!a.total && !a.paymentId) throw new Error("Partial refund without a payment id.");
|
|
1148
|
+
const body = a.total ? void 0 : JSON.stringify({ transactions: [{ id: a.paymentId, amount: pesos(a.amountCents) }] });
|
|
1149
|
+
const res = await this.http(`${this.base}/v1/orders/${encodeURIComponent(a.orderId)}/refund`, {
|
|
1150
|
+
method: "POST",
|
|
1151
|
+
headers: this.headers({ "x-idempotency-key": a.key }),
|
|
1152
|
+
...body ? { body } : {}
|
|
1153
|
+
});
|
|
1154
|
+
return { status: res.status, body: await res.json().catch(() => null) };
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
|
|
1158
|
+
// src/payments/connect/online-checkout.ts
|
|
1159
|
+
var DEFAULT_MESSAGES = {
|
|
1160
|
+
mercadoPagoNotOpened: "Mercado Pago no abri\xF3 el pago.",
|
|
1161
|
+
mercadoPagoNoAnswer: "Mercado Pago no respondi\xF3.",
|
|
1162
|
+
clipNotOpened: "Clip no abri\xF3 el pago.",
|
|
1163
|
+
clipNoAnswer: "Clip no respondi\xF3."
|
|
1164
|
+
};
|
|
1165
|
+
var pesos2 = (cents) => (cents / 100).toFixed(2);
|
|
1166
|
+
var PROVIDER_ERROR = "PAGO_PROVEEDOR_ERROR";
|
|
1167
|
+
var OnlineCheckoutClient = class {
|
|
1168
|
+
constructor(o = {}) {
|
|
1169
|
+
this.o = o;
|
|
1170
|
+
this.msg = { ...DEFAULT_MESSAGES, ...o.messages };
|
|
1171
|
+
}
|
|
1172
|
+
http(p) {
|
|
1173
|
+
return this.o.fetchImpl?.(p) ?? fetch;
|
|
1174
|
+
}
|
|
1175
|
+
get mpBase() {
|
|
1176
|
+
return (this.o.mercadoPagoBaseUrl ?? process.env.MERCADOPAGO_BASE_URL ?? "https://api.mercadopago.com").replace(/\/$/, "");
|
|
1177
|
+
}
|
|
1178
|
+
get clipBase() {
|
|
1179
|
+
return (this.o.clipBaseUrl ?? process.env.CLIP_CHECKOUT_BASE_URL ?? "https://api.payclip.com").replace(/\/$/, "");
|
|
1180
|
+
}
|
|
1181
|
+
clipAuth(c) {
|
|
1182
|
+
return `Basic ${Buffer.from(`${c.apiKey}:${c.secretKey}`).toString("base64")}`;
|
|
1183
|
+
}
|
|
1184
|
+
async create(cred, c) {
|
|
1185
|
+
if (cred.provider === "mercadopago") {
|
|
1186
|
+
const https = c.returnUrl.startsWith("https://");
|
|
1187
|
+
const r2 = await this.http("mercadopago")(`${this.mpBase}/checkout/preferences`, {
|
|
1188
|
+
method: "POST",
|
|
1189
|
+
headers: { authorization: `Bearer ${cred.accessToken}`, "content-type": "application/json" },
|
|
1190
|
+
body: JSON.stringify({
|
|
1191
|
+
items: [
|
|
1192
|
+
{ title: c.description.slice(0, 120), quantity: 1, currency_id: "MXN", unit_price: Number(pesos2(c.amountCents)) }
|
|
1193
|
+
],
|
|
1194
|
+
external_reference: c.reference,
|
|
1195
|
+
notification_url: c.noticeUrl,
|
|
1196
|
+
back_urls: { success: c.returnUrl, pending: c.returnUrl, failure: c.returnUrl },
|
|
1197
|
+
...https ? { auto_return: "approved" } : {},
|
|
1198
|
+
expires: true,
|
|
1199
|
+
expiration_date_to: new Date(Date.now() + c.validForMinutes * 6e4).toISOString()
|
|
1200
|
+
})
|
|
1201
|
+
});
|
|
1202
|
+
const j2 = await r2.json().catch(() => ({}));
|
|
1203
|
+
const url = j2.init_point ?? j2.sandbox_init_point;
|
|
1204
|
+
if (!r2.ok || !j2.id || !url)
|
|
1205
|
+
throw new ConflictAppException(this.msg.mercadoPagoNotOpened, { status: r2.status }, PROVIDER_ERROR);
|
|
1206
|
+
return { provider: "mercadopago", ref: j2.id, url };
|
|
1207
|
+
}
|
|
1208
|
+
const r = await this.http("clip")(`${this.clipBase}/v2/checkout`, {
|
|
1209
|
+
method: "POST",
|
|
1210
|
+
headers: { authorization: this.clipAuth(cred), "content-type": "application/json" },
|
|
1211
|
+
body: JSON.stringify({
|
|
1212
|
+
amount: Number(pesos2(c.amountCents)),
|
|
1213
|
+
currency: "MXN",
|
|
1214
|
+
purchase_description: c.description.slice(0, 250),
|
|
1215
|
+
redirection_url: { success: c.returnUrl, error: c.returnUrl, default: c.returnUrl },
|
|
1216
|
+
webhook_url: c.noticeUrl,
|
|
1217
|
+
// Documented: UTC, no milliseconds (Clip's default is three days; its status docs say 1 hour).
|
|
1218
|
+
expires_at: new Date(Date.now() + c.validForMinutes * 6e4).toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
1219
|
+
metadata: { external_reference: c.reference }
|
|
1220
|
+
})
|
|
1221
|
+
});
|
|
1222
|
+
const j = await r.json().catch(() => ({}));
|
|
1223
|
+
if (!r.ok || !j.payment_request_id || !j.payment_request_url)
|
|
1224
|
+
throw new ConflictAppException(this.msg.clipNotOpened, { status: r.status }, PROVIDER_ERROR);
|
|
1225
|
+
return { provider: "clip", ref: j.payment_request_id, url: j.payment_request_url };
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Current state of the payment according to the provider (`ref` = preference or payment_request_id).
|
|
1229
|
+
* `since`: when the current link was opened — a rejection older than that belongs to an earlier attempt.
|
|
1230
|
+
*/
|
|
1231
|
+
async lookup(cred, reference, ref, since) {
|
|
1232
|
+
if (cred.provider === "mercadopago") {
|
|
1233
|
+
const r2 = await this.http("mercadopago")(
|
|
1234
|
+
`${this.mpBase}/v1/payments/search?external_reference=${encodeURIComponent(reference)}&sort=date_created&criteria=desc`,
|
|
1235
|
+
{ headers: { authorization: `Bearer ${cred.accessToken}` } }
|
|
1236
|
+
);
|
|
1237
|
+
if (!r2.ok) throw new ConflictAppException(this.msg.mercadoPagoNoAnswer, { status: r2.status }, PROVIDER_ERROR);
|
|
1238
|
+
const j2 = await r2.json().catch(() => ({}));
|
|
1239
|
+
const own = (j2.results ?? []).filter((p) => p.external_reference === reference);
|
|
1240
|
+
const approved = own.find((p) => p.status === "approved");
|
|
1241
|
+
if (approved)
|
|
1242
|
+
return { state: "paid", paidCents: Math.round(Number(approved.transaction_amount ?? 0) * 100) };
|
|
1243
|
+
const limit = since ? since.getTime() : 0;
|
|
1244
|
+
const last = own.find((p) => !p.date_created || new Date(p.date_created).getTime() >= limit);
|
|
1245
|
+
if (last && ["rejected", "cancelled", "refunded", "charged_back"].includes(last.status ?? ""))
|
|
1246
|
+
return { state: "failed", paidCents: null };
|
|
1247
|
+
return { state: "pending", paidCents: null };
|
|
1248
|
+
}
|
|
1249
|
+
const r = await this.http("clip")(`${this.clipBase}/v2/checkout/${encodeURIComponent(ref)}`, {
|
|
1250
|
+
headers: { authorization: this.clipAuth(cred) }
|
|
1251
|
+
});
|
|
1252
|
+
if (!r.ok) throw new ConflictAppException(this.msg.clipNoAnswer, { status: r.status }, PROVIDER_ERROR);
|
|
1253
|
+
const j = await r.json().catch(() => ({}));
|
|
1254
|
+
const st = (j.status ?? "").toUpperCase();
|
|
1255
|
+
if (st === "CHECKOUT_COMPLETED") return { state: "paid", paidCents: Math.round(Number(j.amount ?? 0) * 100) };
|
|
1256
|
+
if (st === "CHECKOUT_CANCELLED" || st === "CHECKOUT_EXPIRED") return { state: "failed", paidCents: null };
|
|
1257
|
+
return { state: "pending", paidCents: null };
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
|
|
1261
|
+
// src/payments/connect/terminal-connections.ts
|
|
1262
|
+
import { Logger } from "@nestjs/common";
|
|
1263
|
+
import { randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
1264
|
+
var DEFAULT_MINIMUM = { mercadopago: 500, clip: 100 };
|
|
1265
|
+
var DEFAULT_NAMES = { mercadopago: "Mercado Pago", clip: "Clip" };
|
|
1266
|
+
var REFRESH_MARGIN_MS = 5 * 6e4;
|
|
1267
|
+
var STATE_TTL_MS = 20 * 60 * 1e3;
|
|
1268
|
+
var NO_ANSWER = "Mercado Pago no respondi\xF3. Consulta el estado en un momento.";
|
|
1269
|
+
var DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
|
|
1270
|
+
var ALWAYS_OPEN = Object.fromEntries(DAYS.map((d) => [d, [{ open: "00:00", close: "23:59" }]]));
|
|
1271
|
+
var defaultStoreLocation = (name) => ({
|
|
1272
|
+
streetNumber: "S/N",
|
|
1273
|
+
streetName: name.slice(0, 60),
|
|
1274
|
+
cityName: "Ciudad de M\xE9xico",
|
|
1275
|
+
stateName: "Ciudad de M\xE9xico",
|
|
1276
|
+
latitude: 19.4326,
|
|
1277
|
+
longitude: -99.1332
|
|
1278
|
+
});
|
|
1279
|
+
function terminalName(t) {
|
|
1280
|
+
const raw = t.raw;
|
|
1281
|
+
return raw?.name ?? raw?.external_pos_id ?? raw?.serial_number ?? t.id;
|
|
1282
|
+
}
|
|
1283
|
+
function summarize(t) {
|
|
1284
|
+
return { id: t.id, name: terminalName(t), online: t.online ?? null, mode: t.operatingMode ?? null };
|
|
1285
|
+
}
|
|
1286
|
+
var TerminalConnections = class {
|
|
1287
|
+
constructor(o) {
|
|
1288
|
+
this.o = o;
|
|
1289
|
+
this.lastStatus = /* @__PURE__ */ new Map();
|
|
1290
|
+
this.mpCache = null;
|
|
1291
|
+
this.log = o.logger ?? new Logger("TerminalConnections");
|
|
1292
|
+
}
|
|
1293
|
+
/** Resolved on every use so a key set after construction (env, secret manager) is picked up. */
|
|
1294
|
+
get cipher() {
|
|
1295
|
+
const c = this.o.cipher;
|
|
1296
|
+
return typeof c === "function" ? c() : c;
|
|
1297
|
+
}
|
|
1298
|
+
get available() {
|
|
1299
|
+
return this.cipher !== null;
|
|
1300
|
+
}
|
|
1301
|
+
requireCipher() {
|
|
1302
|
+
const cipher = this.cipher;
|
|
1303
|
+
if (!cipher)
|
|
1304
|
+
throw new ConflictAppException(
|
|
1305
|
+
"Los cobros con terminal no est\xE1n habilitados en este servidor.",
|
|
1306
|
+
{},
|
|
1307
|
+
"TERMINAL_NO_DISPONIBLE"
|
|
1308
|
+
);
|
|
1309
|
+
return cipher;
|
|
1310
|
+
}
|
|
1311
|
+
name(p) {
|
|
1312
|
+
return this.o.providerNames?.[p] ?? DEFAULT_NAMES[p];
|
|
1313
|
+
}
|
|
1314
|
+
fetchFor(p, scopeId) {
|
|
1315
|
+
return this.o.fetchImpl?.(p, scopeId);
|
|
1316
|
+
}
|
|
1317
|
+
sorted(rows) {
|
|
1318
|
+
return [...rows].sort((a, b) => Number(b.primary) - Number(a.primary));
|
|
1319
|
+
}
|
|
1320
|
+
// ── Read ────────────────────────────────────────────────────────────────────────────────
|
|
1321
|
+
view(r, includeWebhook = false) {
|
|
1322
|
+
return {
|
|
1323
|
+
...includeWebhook && r.webhookToken && this.o.publicWebhookUrl ? { webhookUrl: this.o.publicWebhookUrl(r.webhookToken) } : {},
|
|
1324
|
+
id: r.id,
|
|
1325
|
+
provider: r.provider,
|
|
1326
|
+
terminalId: r.terminalId,
|
|
1327
|
+
terminalName: r.terminalName,
|
|
1328
|
+
alias: r.alias,
|
|
1329
|
+
active: r.active,
|
|
1330
|
+
primary: r.primary,
|
|
1331
|
+
ready: Boolean(this.available && r.active && r.terminalId)
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
async list(scopeId, includeWebhook = false) {
|
|
1335
|
+
return (await this.o.store.list(scopeId)).map((r) => this.view(r, includeWebhook));
|
|
1336
|
+
}
|
|
1337
|
+
/** Providers with an active account: which one the merchant can charge online with. */
|
|
1338
|
+
async connectedProviders(scopeId) {
|
|
1339
|
+
if (!this.available) return [];
|
|
1340
|
+
const rows = this.sorted((await this.o.store.list(scopeId)).filter((r) => r.active));
|
|
1341
|
+
return [...new Set(rows.map((r) => r.provider))];
|
|
1342
|
+
}
|
|
1343
|
+
async one(scopeId, id) {
|
|
1344
|
+
const r = await this.o.store.find(id);
|
|
1345
|
+
if (!r || r.scopeId !== scopeId)
|
|
1346
|
+
throw new NotFoundAppException("Esa terminal no existe.", {}, "TERMINAL_NO_ENCONTRADA");
|
|
1347
|
+
return this.view(r);
|
|
1348
|
+
}
|
|
1349
|
+
// ── Connect ─────────────────────────────────────────────────────────────────────────────
|
|
1350
|
+
/** Connects Clip (API key + secret key) after checking them; adds a new terminal row. */
|
|
1351
|
+
async connectClip(scopeId, credentials) {
|
|
1352
|
+
if (!credentials.apiKey || !credentials.secretKey)
|
|
1353
|
+
throw new ValidationAppException("Faltan API key y secret key.", {}, "TERMINAL_CREDENCIALES");
|
|
1354
|
+
const adapter = this.adapter("clip", credentials, scopeId);
|
|
1355
|
+
const terminals = await adapter.listTerminals();
|
|
1356
|
+
const id = await this.save(scopeId, "clip", credentials, terminals);
|
|
1357
|
+
return { id, terminals: terminals.map(summarize) };
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* URL to send the owner to so they authorize. `state` binds the callback to this tenant, and `csrf` (to be set as an
|
|
1361
|
+
* httpOnly cookie by your controller) binds it to the browser that started the flow (OAuth CSRF, RFC 6749 §10.12).
|
|
1362
|
+
* Check your plan/permissions BEFORE calling this: the public callback cannot tell the original tab anything.
|
|
1363
|
+
*/
|
|
1364
|
+
mercadoPagoAuthorizationUrl(scopeId, actorId, destination = "web") {
|
|
1365
|
+
const connect = this.o.mercadoPagoConnect?.(scopeId);
|
|
1366
|
+
if (!connect)
|
|
1367
|
+
throw new ConflictAppException("Mercado Pago no est\xE1 configurado en el servidor.", {}, "MERCADOPAGO_NO_CONFIGURADO");
|
|
1368
|
+
const csrf = randomBytes2(16).toString("hex");
|
|
1369
|
+
const state = signState({ scopeId, actorId, csrf, destination }, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
|
|
1370
|
+
return { url: connect.authorizationUrl(state), csrf };
|
|
1371
|
+
}
|
|
1372
|
+
stateSecret() {
|
|
1373
|
+
const s = this.o.stateSecret;
|
|
1374
|
+
const secret = typeof s === "function" ? s() : s;
|
|
1375
|
+
if (!secret) throw new Error("TerminalConnections: `stateSecret` is required for Mercado Pago OAuth.");
|
|
1376
|
+
return secret;
|
|
1377
|
+
}
|
|
1378
|
+
readOAuthState(state) {
|
|
1379
|
+
return readState(state, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
|
|
1380
|
+
}
|
|
1381
|
+
/** Where to go back after the callback. An unreadable `state` goes back to `fallback`. */
|
|
1382
|
+
oauthDestination(state, fallback = "web") {
|
|
1383
|
+
return this.readOAuthState(state)?.destination ?? fallback;
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* The Mercado Pago callback (no session: only `code`/`state` plus the cookie set at the start). Exchanges the code,
|
|
1387
|
+
* adds a new terminal row with the encrypted credentials and says which tenant/user/row it ended in.
|
|
1388
|
+
* `cookieOptional` for native apps, whose system browser does not hold the cookie of the app's HTTP session: there
|
|
1389
|
+
* the signed `state` (tenant, user, validity) is all that binds the return.
|
|
1390
|
+
*/
|
|
1391
|
+
async completeMercadoPagoOAuth(code, state, nonceCookie, isCookieOptional = () => false) {
|
|
1392
|
+
const signed = this.readOAuthState(state);
|
|
1393
|
+
const noCookie = isCookieOptional(signed?.destination);
|
|
1394
|
+
if (!signed || !noCookie && (!nonceCookie || signed.csrf !== nonceCookie))
|
|
1395
|
+
throw new ConflictAppException(
|
|
1396
|
+
"El enlace de conexi\xF3n con Mercado Pago expir\xF3 o ya se us\xF3. Vuelve a intentar.",
|
|
1397
|
+
{},
|
|
1398
|
+
"MERCADOPAGO_STATE_INVALIDO"
|
|
1399
|
+
);
|
|
1400
|
+
const connect = this.o.mercadoPagoConnect?.(signed.scopeId);
|
|
1401
|
+
if (!connect)
|
|
1402
|
+
throw new ConflictAppException("Mercado Pago no est\xE1 configurado en el servidor.", {}, "MERCADOPAGO_NO_CONFIGURADO");
|
|
1403
|
+
const tokens = await connect.exchangeCode(code);
|
|
1404
|
+
const credentials = {
|
|
1405
|
+
accessToken: tokens.accessToken,
|
|
1406
|
+
refreshToken: tokens.refreshToken,
|
|
1407
|
+
mpUserId: tokens.userId,
|
|
1408
|
+
expira: tokens.expiresAt.toISOString()
|
|
1409
|
+
};
|
|
1410
|
+
const terminals = await this.adapter("mercadopago", credentials, signed.scopeId).listTerminals();
|
|
1411
|
+
const id = await this.save(signed.scopeId, "mercadopago", credentials, terminals);
|
|
1412
|
+
return { scopeId: signed.scopeId, actorId: signed.actorId, id, terminals: terminals.length };
|
|
1413
|
+
}
|
|
1414
|
+
/** Inserts a new row (never overwrites); the tenant's first terminal becomes primary on its own. */
|
|
1415
|
+
async save(scopeId, provider, credentials, terminals) {
|
|
1416
|
+
const cipher = this.requireCipher();
|
|
1417
|
+
const isFirst = (await this.o.store.list(scopeId)).length === 0;
|
|
1418
|
+
const row = await this.o.store.insert({
|
|
1419
|
+
scopeId,
|
|
1420
|
+
provider,
|
|
1421
|
+
encryptedCredentials: cipher.encryptJson(credentials),
|
|
1422
|
+
webhookToken: provider === "clip" ? randomBytes2(32).toString("hex") : null,
|
|
1423
|
+
terminalId: terminals.length === 1 ? terminals[0].id : null,
|
|
1424
|
+
terminalName: terminals.length === 1 ? terminalName(terminals[0]) : null,
|
|
1425
|
+
alias: null,
|
|
1426
|
+
active: true,
|
|
1427
|
+
primary: isFirst
|
|
1428
|
+
});
|
|
1429
|
+
return row.id;
|
|
1430
|
+
}
|
|
1431
|
+
// ── Manage ──────────────────────────────────────────────────────────────────────────────
|
|
1432
|
+
async terminals(scopeId, id) {
|
|
1433
|
+
const { adapter } = await this.adapterOf(scopeId, id);
|
|
1434
|
+
return (await adapter.listTerminals()).map(summarize);
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* The owner picks, from the real list, which terminal it is. For Mercado Pago it also makes sure the Store→POS
|
|
1438
|
+
* hierarchy its Point API requires exists and switches the terminal to PDV mode — without blocking if any of that
|
|
1439
|
+
* fails (uncertified account, freshly paired terminal): the choice is saved anyway.
|
|
1440
|
+
*/
|
|
1441
|
+
async chooseTerminal(scopeId, id, terminalId, name) {
|
|
1442
|
+
const { config, credentials } = await this.adapterOf(scopeId, id);
|
|
1443
|
+
if (config.provider === "mercadopago" && "mpUserId" in credentials)
|
|
1444
|
+
await this.provisionMercadoPago(scopeId, credentials, terminalId);
|
|
1445
|
+
await this.o.store.update(id, { terminalId, terminalName: name ?? terminalId, active: true });
|
|
1446
|
+
return this.one(scopeId, id);
|
|
1447
|
+
}
|
|
1448
|
+
async rename(scopeId, id, alias) {
|
|
1449
|
+
const r = await this.o.store.find(id);
|
|
1450
|
+
if (!r || r.scopeId !== scopeId)
|
|
1451
|
+
throw new NotFoundAppException("Esa terminal no existe.", {}, "TERMINAL_NO_ENCONTRADA");
|
|
1452
|
+
await this.o.store.update(id, { alias: alias.trim() || null });
|
|
1453
|
+
return this.one(scopeId, id);
|
|
1454
|
+
}
|
|
1455
|
+
async setPrimary(scopeId, id) {
|
|
1456
|
+
if (!await this.o.store.setPrimary(scopeId, id))
|
|
1457
|
+
throw new NotFoundAppException("Esa terminal no existe.", {}, "TERMINAL_NO_ENCONTRADA");
|
|
1458
|
+
}
|
|
1459
|
+
async disconnect(scopeId, id) {
|
|
1460
|
+
if (!await this.o.store.delete(scopeId, id))
|
|
1461
|
+
throw new NotFoundAppException("Esa terminal no existe.", {}, "TERMINAL_NO_ENCONTRADA");
|
|
1462
|
+
}
|
|
1463
|
+
async provisionMercadoPago(scopeId, credentials, terminalId) {
|
|
1464
|
+
if (!isIntegrableTerminalModel(terminalId)) {
|
|
1465
|
+
throw new ConflictAppException(
|
|
1466
|
+
"Esta terminal no se puede operar desde Caj\xF3n: Mercado Pago solo integra por API las Point Smart 1 y 2. C\xF3brala manualmente con su app, o conecta una Point Smart.",
|
|
1467
|
+
{},
|
|
1468
|
+
"MERCADOPAGO_TERMINAL_NO_SOPORTADA"
|
|
1469
|
+
);
|
|
1470
|
+
}
|
|
1471
|
+
const mp = this.mercadoPagoTerminals(credentials, scopeId);
|
|
1472
|
+
try {
|
|
1473
|
+
if (!credentials.mpStoreId || !credentials.mpPosId) {
|
|
1474
|
+
const terminals = await mp.listTerminals().catch(() => []);
|
|
1475
|
+
const chosen = terminals.find((t) => t.id === terminalId);
|
|
1476
|
+
if (chosen?.storeId && chosen.posId) {
|
|
1477
|
+
credentials.mpStoreId = chosen.storeId;
|
|
1478
|
+
credentials.mpPosId = chosen.posId;
|
|
1479
|
+
} else {
|
|
1480
|
+
const { name } = await this.o.describeScope?.(scopeId) ?? { name: scopeId };
|
|
1481
|
+
const storeId = await mp.createStore({
|
|
1482
|
+
userId: credentials.mpUserId,
|
|
1483
|
+
name: name.slice(0, 60),
|
|
1484
|
+
location: (this.o.storeLocation ?? defaultStoreLocation)(name),
|
|
1485
|
+
businessHours: ALWAYS_OPEN
|
|
1486
|
+
});
|
|
1487
|
+
const posId = await mp.createPos({
|
|
1488
|
+
storeId,
|
|
1489
|
+
name: name.slice(0, 60),
|
|
1490
|
+
externalId: `cajon-${scopeId}`.slice(0, 40)
|
|
1491
|
+
});
|
|
1492
|
+
credentials.mpStoreId = storeId;
|
|
1493
|
+
credentials.mpPosId = posId;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
await mp.setOperatingMode([terminalId], "PDV");
|
|
1497
|
+
} catch (error) {
|
|
1498
|
+
this.log.warn(`No se pudo aprovisionar Sucursal/Caja/PDV para ${terminalId} (${scopeId}): ${String(error)}`);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
// ── Charge ──────────────────────────────────────────────────────────────────────────────
|
|
1502
|
+
/** Sends the charge to the chosen terminal. Returns once queued, not once paid. */
|
|
1503
|
+
async charge(scopeId, id, amountCents, reference) {
|
|
1504
|
+
const { adapter, config } = await this.adapterOf(scopeId, id);
|
|
1505
|
+
if (!config.terminalId)
|
|
1506
|
+
throw new ConflictAppException("Elige una terminal en Configuraci\xF3n \u2192 Terminal.", {}, "TERMINAL_SIN_ELEGIR");
|
|
1507
|
+
const minimum = this.o.minimumCents?.[config.provider] ?? DEFAULT_MINIMUM[config.provider];
|
|
1508
|
+
if (amountCents < minimum) {
|
|
1509
|
+
const params = { provider: this.name(config.provider), minimum: (minimum / 100).toFixed(2) };
|
|
1510
|
+
throw new ValidationAppException(
|
|
1511
|
+
this.o.messages?.minimumAmount?.(params) ?? `El monto m\xEDnimo con ${params.provider} es $${params.minimum}.`,
|
|
1512
|
+
{ provider: config.provider, minimumCents: minimum },
|
|
1513
|
+
"MONTO_MINIMO_TERMINAL"
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
let payment;
|
|
1517
|
+
try {
|
|
1518
|
+
payment = await adapter.charge({
|
|
1519
|
+
amountCents,
|
|
1520
|
+
terminalId: config.terminalId,
|
|
1521
|
+
reference: reference.replace(/-/g, "").slice(0, 64),
|
|
1522
|
+
// Clip takes no description (the reader shows only the amount); Mercado Pago does.
|
|
1523
|
+
...config.provider === "mercadopago" ? { description: this.o.chargeDescription ?? "Cobro" } : {},
|
|
1524
|
+
idempotencyKey: `${scopeId}:${reference}`
|
|
1525
|
+
});
|
|
1526
|
+
} catch (e) {
|
|
1527
|
+
const rejection = summarizeProviderRejection(e);
|
|
1528
|
+
if (rejection) this.log.warn(`Cobro rechazado (terminal ${id}, ${amountCents} centavos): ${rejection}`);
|
|
1529
|
+
throw e;
|
|
1530
|
+
}
|
|
1531
|
+
this.log.log(`Cobro ${payment.id} (${payment.provider}) por ${amountCents} \u2192 ${payment.status}`);
|
|
1532
|
+
return this.normalize(payment);
|
|
1533
|
+
}
|
|
1534
|
+
async get(scopeId, id, paymentId) {
|
|
1535
|
+
const { adapter } = await this.adapterOf(scopeId, id);
|
|
1536
|
+
return this.normalize(await adapter.get(paymentId));
|
|
1537
|
+
}
|
|
1538
|
+
async cancel(scopeId, id, paymentId) {
|
|
1539
|
+
const { adapter } = await this.adapterOf(scopeId, id);
|
|
1540
|
+
const r = await adapter.cancel(paymentId);
|
|
1541
|
+
return this.normalize(r.status === "cancelled" ? r : await adapter.get(paymentId));
|
|
1542
|
+
}
|
|
1543
|
+
/** The status a point of sale should act on, with the adapter's `unknown` resolved (and logged). */
|
|
1544
|
+
normalize(p) {
|
|
1545
|
+
let status = p.status;
|
|
1546
|
+
if (status === "unknown") {
|
|
1547
|
+
status = resolveTerminalStatus(p);
|
|
1548
|
+
this.log.warn(
|
|
1549
|
+
`${p.provider} ${p.id}: estado no reconocido por el adaptador (${JSON.stringify(p.raw?.status)}) \u2192 ${status}`
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1552
|
+
return { id: p.id, provider: p.provider, status, amountCents: p.amountCents, paidCents: p.paidCents ?? null };
|
|
1553
|
+
}
|
|
1554
|
+
// ── Provider notices ────────────────────────────────────────────────────────────────────
|
|
1555
|
+
// A webhook is only a trigger: its body is never trusted. The provider is asked with the tenant's credentials and
|
|
1556
|
+
// `onPaymentChanged` fires if the status moved since the last one seen.
|
|
1557
|
+
/** Clip: `token` identifies the terminal (and the tenant). Never throws: a webhook always answers 200. */
|
|
1558
|
+
async handleClipNotice(token, paymentId) {
|
|
1559
|
+
try {
|
|
1560
|
+
if (typeof paymentId !== "string" || !paymentId || paymentId.length > 128) return;
|
|
1561
|
+
if (!token || token.length > 200) return;
|
|
1562
|
+
const row = await this.o.store.findByWebhookToken(token);
|
|
1563
|
+
if (!row?.webhookToken || row.provider !== "clip" || !row.active) return;
|
|
1564
|
+
const a = Buffer.from(row.webhookToken);
|
|
1565
|
+
const b = Buffer.from(token);
|
|
1566
|
+
if (a.length !== b.length || !timingSafeEqual4(a, b)) return;
|
|
1567
|
+
await this.lookupAndNotify(row.scopeId, row.id, paymentId);
|
|
1568
|
+
} catch (e) {
|
|
1569
|
+
this.log.warn(`Aviso de Clip no procesado: ${e.message}`);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/** Mercado Pago: verifies `x-signature` and finds the tenant(s) by `user_id`. Never throws. */
|
|
1573
|
+
async handleMercadoPagoNotice(a) {
|
|
1574
|
+
try {
|
|
1575
|
+
const w = this.o.mercadoPagoWebhookSecret;
|
|
1576
|
+
const secret = typeof w === "function" ? w() : w;
|
|
1577
|
+
if (!secret) return;
|
|
1578
|
+
if (!verifyMercadoPagoSignature(secret, a.dataIdQuery, a.xSignature, a.xRequestId)) {
|
|
1579
|
+
this.log.warn("Aviso de Mercado Pago con firma inv\xE1lida: ignorado.");
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
const c = a.body ?? {};
|
|
1583
|
+
const orderId = a.dataIdQuery ?? (typeof c.data?.id === "string" ? c.data.id : null);
|
|
1584
|
+
const userId = c.user_id == null ? "" : String(c.user_id);
|
|
1585
|
+
if (!orderId || !userId || orderId.length > 128) return;
|
|
1586
|
+
for (const rowId of await this.mercadoPagoRows(userId)) {
|
|
1587
|
+
try {
|
|
1588
|
+
const row = await this.o.store.find(rowId);
|
|
1589
|
+
if (!row) continue;
|
|
1590
|
+
this.o.onMercadoPagoOrder?.(row.scopeId, orderId);
|
|
1591
|
+
await this.lookupAndNotify(row.scopeId, row.id, orderId);
|
|
1592
|
+
} catch (e) {
|
|
1593
|
+
this.log.debug(`Orden ${orderId} no consultable para la terminal ${rowId}: ${e.message}`);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
} catch (e) {
|
|
1597
|
+
this.log.warn(`Aviso de Mercado Pago no procesado: ${e.message}`);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
/** One active row per tenant whose Mercado Pago account is `mpUserId`. Short cache. */
|
|
1601
|
+
async mercadoPagoRows(mpUserId) {
|
|
1602
|
+
const fresh = (ms) => this.mpCache && Date.now() - this.mpCache.at < ms;
|
|
1603
|
+
if (!fresh(6e4) || !this.mpCache.byUser.has(mpUserId)) {
|
|
1604
|
+
if (!(fresh(1e4) && !this.mpCache.byUser.has(mpUserId))) {
|
|
1605
|
+
const cipher = this.requireCipher();
|
|
1606
|
+
const rows = await this.o.store.listActiveByProvider("mercadopago");
|
|
1607
|
+
const byUser = /* @__PURE__ */ new Map();
|
|
1608
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1609
|
+
for (const r of rows) {
|
|
1610
|
+
try {
|
|
1611
|
+
const c = cipher.decryptJson(r.encryptedCredentials);
|
|
1612
|
+
if (!c.mpUserId) continue;
|
|
1613
|
+
const u = String(c.mpUserId);
|
|
1614
|
+
const scopes = seen.get(u) ?? /* @__PURE__ */ new Set();
|
|
1615
|
+
if (scopes.has(r.scopeId)) continue;
|
|
1616
|
+
scopes.add(r.scopeId);
|
|
1617
|
+
seen.set(u, scopes);
|
|
1618
|
+
byUser.set(u, (byUser.get(u) ?? /* @__PURE__ */ new Set()).add(r.id));
|
|
1619
|
+
} catch {
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
this.mpCache = { at: Date.now(), byUser };
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
return [...this.mpCache?.byUser.get(mpUserId) ?? []];
|
|
1626
|
+
}
|
|
1627
|
+
async lookupAndNotify(scopeId, rowId, paymentId) {
|
|
1628
|
+
const { adapter } = await this.adapterOf(scopeId, rowId);
|
|
1629
|
+
const charge = this.normalize(await adapter.get(paymentId));
|
|
1630
|
+
const key = `${scopeId}:${paymentId}`;
|
|
1631
|
+
if (this.lastStatus.get(key) === charge.status) return;
|
|
1632
|
+
this.lastStatus.delete(key);
|
|
1633
|
+
this.lastStatus.set(key, charge.status);
|
|
1634
|
+
while (this.lastStatus.size > 2e3) this.lastStatus.delete(this.lastStatus.keys().next().value);
|
|
1635
|
+
this.o.onPaymentChanged?.(scopeId, paymentId, charge);
|
|
1636
|
+
}
|
|
1637
|
+
// ── Online checkout ─────────────────────────────────────────────────────────────────────
|
|
1638
|
+
/**
|
|
1639
|
+
* Credentials of the tenant's own account for online checkout (the money goes to them). With no `provider` it takes
|
|
1640
|
+
* the primary terminal's. Mercado Pago refreshes its access token here.
|
|
1641
|
+
*/
|
|
1642
|
+
async checkoutCredentials(scopeId, provider) {
|
|
1643
|
+
this.requireCipher();
|
|
1644
|
+
const rows = this.sorted((await this.o.store.list(scopeId)).filter((r) => r.active));
|
|
1645
|
+
const row = rows.find((r) => !provider || r.provider === provider);
|
|
1646
|
+
if (!row)
|
|
1647
|
+
throw new ConflictAppException(
|
|
1648
|
+
"La tienda no tiene una cuenta de Mercado Pago o Clip conectada.",
|
|
1649
|
+
{},
|
|
1650
|
+
"PAGO_SIN_PROVEEDOR"
|
|
1651
|
+
);
|
|
1652
|
+
const { credentials } = await this.adapterOf(scopeId, row.id);
|
|
1653
|
+
if (row.provider === "mercadopago" && "accessToken" in credentials)
|
|
1654
|
+
return { provider: "mercadopago", accessToken: credentials.accessToken };
|
|
1655
|
+
if (row.provider === "clip" && "apiKey" in credentials && credentials.secretKey)
|
|
1656
|
+
return { provider: "clip", apiKey: credentials.apiKey, secretKey: credentials.secretKey };
|
|
1657
|
+
throw new ValidationAppException(
|
|
1658
|
+
this.o.messages?.missingCredentials?.() ?? "Faltan credenciales.",
|
|
1659
|
+
{},
|
|
1660
|
+
"TERMINAL_CREDENCIALES"
|
|
1661
|
+
);
|
|
1662
|
+
}
|
|
1663
|
+
// ── Refunds (Mercado Pago only) ─────────────────────────────────────────────────────────
|
|
1664
|
+
/** There is something to ask with: encryption key and an active Mercado Pago account. */
|
|
1665
|
+
async canRefundMercadoPago(scopeId) {
|
|
1666
|
+
if (!this.available) return false;
|
|
1667
|
+
return (await this.o.store.list(scopeId)).some((r) => r.provider === "mercadopago" && r.active);
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* The account (among those connected to the tenant) where the order exists. `no_answer` if one did not answer and
|
|
1671
|
+
* none had it: it cannot be concluded the order does not exist.
|
|
1672
|
+
*/
|
|
1673
|
+
async accountOfOrder(scopeId, orderId) {
|
|
1674
|
+
const rows = this.sorted(
|
|
1675
|
+
(await this.o.store.list(scopeId)).filter((r) => r.provider === "mercadopago" && r.active)
|
|
1676
|
+
);
|
|
1677
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1678
|
+
let noAnswer = false;
|
|
1679
|
+
for (const r of rows) {
|
|
1680
|
+
try {
|
|
1681
|
+
const { credentials } = await this.adapterOf(scopeId, r.id);
|
|
1682
|
+
if (!("accessToken" in credentials)) continue;
|
|
1683
|
+
const account = String(credentials.mpUserId ?? credentials.accessToken);
|
|
1684
|
+
if (seen.has(account)) continue;
|
|
1685
|
+
seen.add(account);
|
|
1686
|
+
const client = new MercadoPagoRefunds({
|
|
1687
|
+
accessToken: credentials.accessToken,
|
|
1688
|
+
baseUrl: this.o.mercadoPagoBaseUrl ?? process.env.MERCADOPAGO_BASE_URL,
|
|
1689
|
+
fetchImpl: this.fetchFor("mercadopago", scopeId)
|
|
1690
|
+
});
|
|
1691
|
+
const { status, order } = await client.order(orderId);
|
|
1692
|
+
if (order) return { client, order };
|
|
1693
|
+
if (isTransientStatus(status)) noAnswer = true;
|
|
1694
|
+
} catch (e) {
|
|
1695
|
+
noAnswer = true;
|
|
1696
|
+
this.log.warn(`Orden ${orderId} no consultable (${scopeId}): ${e.message}`);
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
return noAnswer ? "no_answer" : "not_found";
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Asks (or asks again with the SAME key) for the refund of `amountCents` of the order, or just looks it up.
|
|
1703
|
+
* - `key`: stable per refund; Mercado Pago remembers it 24 h, so retrying never creates a second refund.
|
|
1704
|
+
* - `providerRefundId` known or `onlyLookup` (past the key's window): the order is only read, nothing is sent.
|
|
1705
|
+
* - `firstAttempt`: if the order is not in the connected account it is rejected; on a retry it stays pending (the
|
|
1706
|
+
* first attempt may have gone through).
|
|
1707
|
+
* - `claimed`: ids of refunds of that order that already belong to OTHER records (not to be mistaken for this one).
|
|
1708
|
+
* Never throws because of the provider: no answer = `pending`.
|
|
1709
|
+
*/
|
|
1710
|
+
async refundMercadoPago(scopeId, a) {
|
|
1711
|
+
const messages = { ...DEFAULT_REFUND_MESSAGES, ...this.o.refundMessages };
|
|
1712
|
+
const pending = (detail) => ({ status: "pending", providerRefundId: a.providerRefundId, detail });
|
|
1713
|
+
if (!this.available) return pending("Los cobros con terminal no est\xE1n habilitados en este servidor.");
|
|
1714
|
+
const account = await this.accountOfOrder(scopeId, a.orderId);
|
|
1715
|
+
if (account === "no_answer") return pending(NO_ANSWER);
|
|
1716
|
+
if (account === "not_found")
|
|
1717
|
+
return a.firstAttempt ? { status: "rejected", providerRefundId: null, detail: "Mercado Pago no encuentra este cobro en la cuenta conectada." } : pending("Mercado Pago no encuentra este cobro en la cuenta conectada; rev\xEDsalo en tu cuenta.");
|
|
1718
|
+
const wanted = { providerRefundId: a.providerRefundId, amountCents: a.amountCents, claimed: a.claimed };
|
|
1719
|
+
if (a.providerRefundId || a.onlyLookup) return interpretOrder(account.order, wanted, messages);
|
|
1720
|
+
const { paymentId, collectedCents } = paymentOfOrder(account.order);
|
|
1721
|
+
const total = a.amountCents === collectedCents;
|
|
1722
|
+
if (!total && !paymentId)
|
|
1723
|
+
return a.firstAttempt ? { status: "rejected", providerRefundId: null, detail: "Mercado Pago no permite reembolsar parte de este cobro desde Caj\xF3n." } : pending(NO_ANSWER);
|
|
1724
|
+
let r;
|
|
1725
|
+
try {
|
|
1726
|
+
r = await account.client.refund({ orderId: a.orderId, key: a.key, total, paymentId, amountCents: a.amountCents });
|
|
1727
|
+
} catch (e) {
|
|
1728
|
+
this.log.warn(`Reembolso de la orden ${a.orderId} sin respuesta: ${e.message}`);
|
|
1729
|
+
return pending(NO_ANSWER);
|
|
1730
|
+
}
|
|
1731
|
+
if (r.status >= 200 && r.status < 300) {
|
|
1732
|
+
const order = r.body ?? {};
|
|
1733
|
+
const read = interpretOrder(order, wanted, messages);
|
|
1734
|
+
if (read.status === "pending" && !read.providerRefundId && total && order.status === "refunded")
|
|
1735
|
+
return { status: "confirmed", providerRefundId: null, detail: null };
|
|
1736
|
+
return read;
|
|
1737
|
+
}
|
|
1738
|
+
const kind = classifyRefundError(r.status, r.body, messages);
|
|
1739
|
+
if (kind.transient) return pending(NO_ANSWER);
|
|
1740
|
+
this.log.warn(
|
|
1741
|
+
`Mercado Pago rechaz\xF3 el reembolso de la orden ${a.orderId}: HTTP ${r.status} ${refundErrorCode(r.body) ?? ""}`
|
|
1742
|
+
);
|
|
1743
|
+
return { status: "rejected", providerRefundId: null, detail: kind.detail };
|
|
1744
|
+
}
|
|
1745
|
+
// ── Internals ───────────────────────────────────────────────────────────────────────────
|
|
1746
|
+
/** The row, its decrypted (and, for Mercado Pago, refreshed) credentials and a ready adapter. */
|
|
1747
|
+
async adapterOf(scopeId, id) {
|
|
1748
|
+
const cipher = this.requireCipher();
|
|
1749
|
+
const config = await this.o.store.find(id);
|
|
1750
|
+
if (!config || config.scopeId !== scopeId || !config.active)
|
|
1751
|
+
throw new NotFoundAppException("Esta terminal no existe o no est\xE1 conectada.", {}, "TERMINAL_NO_CONECTADA");
|
|
1752
|
+
let credentials = cipher.decryptJson(config.encryptedCredentials);
|
|
1753
|
+
if (config.provider === "mercadopago" && "refreshToken" in credentials)
|
|
1754
|
+
credentials = await this.refreshed(config, credentials);
|
|
1755
|
+
return { config, credentials, adapter: this.adapter(config.provider, credentials, scopeId) };
|
|
1756
|
+
}
|
|
1757
|
+
/** Renews the Mercado Pago access token 5 minutes before it expires; Mercado Pago rotates the refresh token too. */
|
|
1758
|
+
async refreshed(config, c) {
|
|
1759
|
+
if (new Date(c.expira).getTime() - Date.now() > REFRESH_MARGIN_MS) return c;
|
|
1760
|
+
const connect = this.o.mercadoPagoConnect?.(config.scopeId);
|
|
1761
|
+
if (!connect) return c;
|
|
1762
|
+
const tokens = await connect.refresh(c.refreshToken);
|
|
1763
|
+
const next = {
|
|
1764
|
+
...c,
|
|
1765
|
+
accessToken: tokens.accessToken,
|
|
1766
|
+
refreshToken: tokens.refreshToken,
|
|
1767
|
+
expira: tokens.expiresAt.toISOString()
|
|
1768
|
+
};
|
|
1769
|
+
await this.o.store.update(config.id, { encryptedCredentials: this.requireCipher().encryptJson(next) });
|
|
1770
|
+
return next;
|
|
1771
|
+
}
|
|
1772
|
+
mercadoPagoTerminals(c, scopeId) {
|
|
1773
|
+
return new MercadoPagoTerminalPayments({
|
|
1774
|
+
accessToken: c.accessToken,
|
|
1775
|
+
baseUrl: this.o.mercadoPagoBaseUrl ?? process.env.MERCADOPAGO_BASE_URL,
|
|
1776
|
+
fetchImpl: this.fetchFor("mercadopago", scopeId)
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
adapter(provider, c, scopeId) {
|
|
1780
|
+
if (provider === "mercadopago") {
|
|
1781
|
+
if (!("accessToken" in c))
|
|
1782
|
+
throw new ValidationAppException(
|
|
1783
|
+
this.o.messages?.missingAccessToken?.() ?? "Falta el access token.",
|
|
1784
|
+
{},
|
|
1785
|
+
"TERMINAL_CREDENCIALES"
|
|
1786
|
+
);
|
|
1787
|
+
return createTerminalPaymentsAdapter({
|
|
1788
|
+
provider: "mercadopago",
|
|
1789
|
+
mercadopago: {
|
|
1790
|
+
accessToken: c.accessToken,
|
|
1791
|
+
baseUrl: this.o.mercadoPagoBaseUrl ?? process.env.MERCADOPAGO_BASE_URL,
|
|
1792
|
+
fetchImpl: this.fetchFor("mercadopago", scopeId)
|
|
1793
|
+
}
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
if (!("apiKey" in c) || !c.secretKey)
|
|
1797
|
+
throw new ValidationAppException("Faltan API key y secret key.", {}, "TERMINAL_CREDENCIALES");
|
|
1798
|
+
return createTerminalPaymentsAdapter({
|
|
1799
|
+
provider: "clip",
|
|
1800
|
+
clip: {
|
|
1801
|
+
apiKey: c.apiKey,
|
|
1802
|
+
secretKey: c.secretKey,
|
|
1803
|
+
baseUrl: this.o.clipBaseUrl ?? process.env.CLIP_BASE_URL,
|
|
1804
|
+
fetchImpl: this.fetchFor("clip", scopeId)
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
932
1809
|
export {
|
|
1810
|
+
ALWAYS_OPEN,
|
|
933
1811
|
ClipTerminalPayments,
|
|
1812
|
+
CredentialsCipher,
|
|
1813
|
+
DEFAULT_REFUND_MESSAGES,
|
|
1814
|
+
DEFINITIVE_REFUND_REJECTIONS,
|
|
1815
|
+
IDEMPOTENCY_WINDOW_MS,
|
|
934
1816
|
MercadoPagoConnect,
|
|
1817
|
+
MercadoPagoRefunds,
|
|
935
1818
|
MercadoPagoTerminalPayments,
|
|
1819
|
+
OnlineCheckoutClient,
|
|
936
1820
|
PAYMENTS_OPTIONS,
|
|
937
1821
|
PaymentsModule,
|
|
938
1822
|
TERMINAL_PAYMENTS,
|
|
1823
|
+
TerminalConnections,
|
|
939
1824
|
TerminalPaymentProviderException,
|
|
940
1825
|
UnsupportedByProviderException,
|
|
941
1826
|
assertCents,
|
|
1827
|
+
centsOf,
|
|
942
1828
|
centsToDecimalString,
|
|
1829
|
+
classifyRefundError,
|
|
1830
|
+
clipStatus,
|
|
943
1831
|
createTerminalPaymentsAdapter,
|
|
944
1832
|
createTerminalPaymentsWebhookController,
|
|
945
1833
|
decimalToCents,
|
|
1834
|
+
defaultStoreLocation,
|
|
1835
|
+
interpretOrder,
|
|
946
1836
|
isIntegrableTerminalModel,
|
|
947
|
-
|
|
1837
|
+
isTransientStatus,
|
|
1838
|
+
mercadoPagoStatus,
|
|
1839
|
+
paymentOfOrder,
|
|
1840
|
+
refundErrorCode,
|
|
1841
|
+
refundErrorMessage,
|
|
1842
|
+
resolvePaymentsOptions,
|
|
1843
|
+
resolveTerminalStatus,
|
|
1844
|
+
summarizeProviderRejection,
|
|
1845
|
+
verifyMercadoPagoSignature
|
|
948
1846
|
};
|