Merge fix/epayco-pse-reemplaza-payu into main
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 30s
Build and Push Frontend / Escaneo de Secretos (Gitleaks) (push) Successful in 23s
Build and Push Medusa / Construir y publicar Medusa (push) Failing after 4m19s
Build and Push Frontend / Construir y Subir Imagen (push) Successful in 18m42s
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 30s
Build and Push Frontend / Escaneo de Secretos (Gitleaks) (push) Successful in 23s
Build and Push Medusa / Construir y publicar Medusa (push) Failing after 4m19s
Build and Push Frontend / Construir y Subir Imagen (push) Successful in 18m42s
This commit is contained in:
commit
d4716382d3
17 files changed
+471
-509
No files matched your search
@@ -27,13 +27,13 @@ ENV CI=true \
|
|||||||
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
||||||
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
||||||
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback \
|
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback \
|
||||||
PAYU_API_LOGIN=build-only-payu-login \
|
EPAYCO_PUBLIC_KEY=build-only-epayco-public \
|
||||||
PAYU_API_KEY=build-only-payu-key \
|
EPAYCO_PRIVATE_KEY=build-only-epayco-private \
|
||||||
PAYU_MERCHANT_ID=999999 \
|
EPAYCO_P_CUST_ID_CLIENTE=build-only-epayco-pcust \
|
||||||
PAYU_ACCOUNT_ID=999999 \
|
EPAYCO_P_KEY=build-only-epayco-pkey \
|
||||||
PAYU_ENV=sandbox \
|
EPAYCO_ENV=sandbox \
|
||||||
PAYU_RESPONSE_URL=http://localhost:8000/checkout/pse/return \
|
EPAYCO_RESPONSE_URL=http://localhost:8000/checkout/pse/return \
|
||||||
PAYU_NOTIFY_URL=http://localhost:9000/hooks/payment/payu_pse
|
EPAYCO_NOTIFY_URL=http://localhost:9000/hooks/payment/epayco_pse
|
||||||
|
|
||||||
COPY package.json package-lock.json .npmrc ./
|
COPY package.json package-lock.json .npmrc ./
|
||||||
|
|
||||||
|
|||||||
@@ -181,28 +181,34 @@ module.exports = defineConfig({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// ADR 0009: PayU LatAm elegido como proveedor de pago -- no existe
|
// ADR 0009: proveedor de pago -- tercera vuelta. PayU LatAm fue la
|
||||||
// ningun plugin real de Medusa para su API (los paquetes que
|
// decision original, pero Rapyd compro ese negocio en 2023 y el
|
||||||
// aparecen buscando "PayU" son para PayU Polonia/CEE, API distinta
|
// registro real del usuario quedo con credenciales de Rapyd
|
||||||
// por completo), asi que es un modulo custom propio. Alcance inicial:
|
// (incompatibles, API completamente distinta). Se evaluo Rapyd en
|
||||||
// solo PSE (transferencia bancaria), no Nequi/Daviplata/tarjetas.
|
// vivo y se termino descartando: comision mas alta que otras
|
||||||
// provider_id resultante: "pp_payu_pse" (identifier "payu" + id
|
// opciones para el volumen real del usuario. ePayco elegido en su
|
||||||
|
// lugar -- 100% de Davivienda desde 2024, comision PSE mas baja,
|
||||||
|
// tarifa preferencial con cuenta Davivienda (que el usuario ya
|
||||||
|
// tiene), sin exigir Bancolombia/Nequi como si exige Wompi. Tampoco
|
||||||
|
// existe plugin real de Medusa para ePayco, modulo custom propio.
|
||||||
|
// Alcance inicial: solo PSE, no tarjetas/otros metodos.
|
||||||
|
// provider_id resultante: "pp_epayco_pse" (identifier "epayco" + id
|
||||||
// "pse", convencion de Medusa).
|
// "pse", convencion de Medusa).
|
||||||
{
|
{
|
||||||
resolve: "@medusajs/medusa/payment",
|
resolve: "@medusajs/medusa/payment",
|
||||||
options: {
|
options: {
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
resolve: "./src/modules/payu-pse",
|
resolve: "./src/modules/epayco-pse",
|
||||||
id: "pse",
|
id: "pse",
|
||||||
options: {
|
options: {
|
||||||
apiLogin: required("PAYU_API_LOGIN"),
|
publicKey: required("EPAYCO_PUBLIC_KEY"),
|
||||||
apiKey: required("PAYU_API_KEY"),
|
privateKey: required("EPAYCO_PRIVATE_KEY"),
|
||||||
merchantId: required("PAYU_MERCHANT_ID"),
|
pCustIdCliente: required("EPAYCO_P_CUST_ID_CLIENTE"),
|
||||||
accountId: required("PAYU_ACCOUNT_ID"),
|
pKey: required("EPAYCO_P_KEY"),
|
||||||
env: process.env.PAYU_ENV || "sandbox",
|
env: process.env.EPAYCO_ENV || "sandbox",
|
||||||
responseUrl: required("PAYU_RESPONSE_URL"),
|
responseUrl: required("EPAYCO_RESPONSE_URL"),
|
||||||
notifyUrl: required("PAYU_NOTIFY_URL"),
|
notifyUrl: required("EPAYCO_NOTIFY_URL"),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -15,7 +15,8 @@
|
|||||||
"@medusajs/cli": "2.18.0",
|
"@medusajs/cli": "2.18.0",
|
||||||
"@medusajs/framework": "2.18.0",
|
"@medusajs/framework": "2.18.0",
|
||||||
"@medusajs/medusa": "2.18.0",
|
"@medusajs/medusa": "2.18.0",
|
||||||
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1"
|
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1",
|
||||||
|
"epayco-sdk-node": "^1.4.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||||
import { fetchPseBanks, type PayuBank, type PayuEnv } from "../../../../lib/payu";
|
import { createEpaycoClient, type EpaycoEnv } from "../../../../lib/epayco";
|
||||||
|
|
||||||
// Lista de bancos PSE -- no hay forma de pedirle esto al modulo de pago
|
// Lista de bancos PSE -- no hay forma de pedirle esto al modulo de pago
|
||||||
// custom directamente (AbstractPaymentProvider no expone sus metodos
|
// custom directamente (AbstractPaymentProvider no expone sus metodos
|
||||||
// internos fuera del contrato de pago), asi que esta ruta llama a PayU
|
// internos fuera del contrato de pago), asi que esta ruta llama a
|
||||||
// con las mismas credenciales de medusa-config.ts. Cache en memoria (sin
|
// ePayco con las mismas credenciales de medusa-config.ts. Cache en
|
||||||
// Redis/cron) porque PayU solo pide refrescar "una vez al dia" -- mismo
|
// memoria (sin Redis/cron), mismo criterio de simplicidad que ya usa la
|
||||||
// criterio de simplicidad que ya usa la seccion de Meilisearch en
|
// seccion de Meilisearch en medusa-config.ts.
|
||||||
// medusa-config.ts.
|
//
|
||||||
|
// El shape exacto de la respuesta de bank.getBanks() no quedo verificado
|
||||||
|
// contra el sandbox real en esta sesion -- se prueban los nombres de
|
||||||
|
// campo mas probables (bankCode/bankName y variantes) y se degrada a
|
||||||
|
// lista vacia si no matchea nada, en vez de romper el checkout entero.
|
||||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||||
let cache: { banks: PayuBank[]; fetchedAt: number } | null = null;
|
let cache: { banks: Array<{ pseCode: string; description: string }>; fetchedAt: number } | null = null;
|
||||||
|
|
||||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) {
|
if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) {
|
||||||
@@ -18,20 +22,31 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const banks = await fetchPseBanks({
|
const client = createEpaycoClient({
|
||||||
apiLogin: process.env.PAYU_API_LOGIN ?? "",
|
publicKey: process.env.EPAYCO_PUBLIC_KEY ?? "",
|
||||||
apiKey: process.env.PAYU_API_KEY ?? "",
|
privateKey: process.env.EPAYCO_PRIVATE_KEY ?? "",
|
||||||
merchantId: process.env.PAYU_MERCHANT_ID ?? "",
|
pCustIdCliente: process.env.EPAYCO_P_CUST_ID_CLIENTE ?? "",
|
||||||
accountId: process.env.PAYU_ACCOUNT_ID ?? "",
|
pKey: process.env.EPAYCO_P_KEY ?? "",
|
||||||
env: (process.env.PAYU_ENV as PayuEnv) || "sandbox",
|
env: (process.env.EPAYCO_ENV as EpaycoEnv) || "sandbox",
|
||||||
});
|
});
|
||||||
|
const response = await client.bank.getBanks();
|
||||||
|
const rawBanks = (response.data ?? response.banks ?? response) as unknown;
|
||||||
|
const list = Array.isArray(rawBanks) ? rawBanks : [];
|
||||||
|
|
||||||
|
const banks = list
|
||||||
|
.map((bank) => {
|
||||||
|
const record = bank as Record<string, unknown>;
|
||||||
|
const pseCode = record.bankCode ?? record.bank_code ?? record.codigo ?? record.id;
|
||||||
|
const description = record.bankName ?? record.bank_name ?? record.nombre ?? record.name ?? record.description;
|
||||||
|
return typeof pseCode === "string" || typeof pseCode === "number"
|
||||||
|
? { pseCode: String(pseCode), description: String(description ?? pseCode) }
|
||||||
|
: null;
|
||||||
|
})
|
||||||
|
.filter((bank): bank is { pseCode: string; description: string } => bank !== null);
|
||||||
|
|
||||||
cache = { banks, fetchedAt: Date.now() };
|
cache = { banks, fetchedAt: Date.now() };
|
||||||
res.json({ banks });
|
res.json({ banks });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Degrada a lista vacia en vez de tirar 500 -- el checkout debe poder
|
|
||||||
// mostrar un mensaje de "no disponible" en vez de romper la pagina
|
|
||||||
// entera, mismo criterio que /store/search cuando Meilisearch no
|
|
||||||
// responde.
|
|
||||||
res.json({ banks: cache?.banks ?? [], error: (error as Error).message });
|
res.json({ banks: cache?.banks ?? [], error: (error as Error).message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
// ePayco (100% de Davivienda desde 2024, ver ADR 0009 -- tercer proveedor
|
||||||
|
// evaluado tras PayU LatAm/Rapyd, elegido por comision PSE mas baja para
|
||||||
|
// bajo volumen y tarifa preferencial con cuenta Davivienda, que el
|
||||||
|
// usuario ya tiene). A diferencia de PayU/Rapyd, no llamamos la API REST
|
||||||
|
// cruda nosotros: usamos el SDK oficial `epayco-sdk-node` (mantenido por
|
||||||
|
// github.com/epayco, ultimo publish reciente) porque su protocolo real
|
||||||
|
// -- leido del codigo fuente, no de la doc -- es bastante mas raro de lo
|
||||||
|
// que parece en los ejemplos: cada campo del payload se cifra con
|
||||||
|
// AES-CBC usando la private key como llave (IV fijo en cero) ANTES de
|
||||||
|
// mandarse a secure.payco.co, ademas de un login previo a
|
||||||
|
// api.secure.payco.co/v1/auth/login que da un bearer token que tambien
|
||||||
|
// va en la request. Reimplementar esto a mano tiene mucho mas riesgo de
|
||||||
|
// error que delegarlo al SDK del propio proveedor.
|
||||||
|
export type EpaycoEnv = "sandbox" | "production";
|
||||||
|
|
||||||
|
export interface EpaycoCredentials {
|
||||||
|
publicKey: string;
|
||||||
|
privateKey: string;
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
env: EpaycoEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sin tipos de TypeScript en el paquete (confirmado: package.json no
|
||||||
|
// declara "types") -- se tipa manualmente el subset que usamos.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const EpaycoSdk = require("epayco-sdk-node");
|
||||||
|
|
||||||
|
export interface EpaycoClient {
|
||||||
|
bank: {
|
||||||
|
create(options: Record<string, unknown>): Promise<Record<string, unknown>>;
|
||||||
|
get(transactionId: string): Promise<Record<string, unknown>>;
|
||||||
|
getBanks(): Promise<Record<string, unknown>>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createEpaycoClient(credentials: EpaycoCredentials): EpaycoClient {
|
||||||
|
return EpaycoSdk({
|
||||||
|
apiKey: credentials.publicKey,
|
||||||
|
privateKey: credentials.privateKey,
|
||||||
|
lang: "ES",
|
||||||
|
test: credentials.env === "sandbox",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firma del webhook de confirmacion (url_confirmation) -- formula
|
||||||
|
// verificada contra la documentacion real de ePayco:
|
||||||
|
// sha256(p_cust_id_cliente^p_key^x_ref_payco^x_transaction_id^x_amount^x_currency_code).
|
||||||
|
// p_cust_id_cliente/p_key son valores propios del dashboard de ePayco
|
||||||
|
// (Configuracion > Llaves secretas), distintos de publicKey/privateKey
|
||||||
|
// -- confirmar contra el dashboard real antes de la primera prueba.
|
||||||
|
// Falla cerrado: cualquier mismatch devuelve false, nunca se traga la
|
||||||
|
// excepcion.
|
||||||
|
export function verifyWebhookSignature(params: {
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
refPayco: string;
|
||||||
|
transactionId: string;
|
||||||
|
amount: string;
|
||||||
|
currencyCode: string;
|
||||||
|
signature: string;
|
||||||
|
}): boolean {
|
||||||
|
const raw = `${params.pCustIdCliente}^${params.pKey}^${params.refPayco}^${params.transactionId}^${params.amount}^${params.currencyCode}`;
|
||||||
|
const expected = createHash("sha256").update(raw).digest("hex");
|
||||||
|
return expected.toLowerCase() === params.signature.toLowerCase();
|
||||||
|
}
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { createHash } from "node:crypto";
|
|
||||||
|
|
||||||
// Contrato real de la API de PayU LatAm (developers.payulatam.com,
|
|
||||||
// verificado en vivo 2026-09-06/07 -- NO es la misma API que los plugins
|
|
||||||
// de Medusa que aparecen buscando "PayU": esos son para PayU Polonia/CEE
|
|
||||||
// (clientId/posId/secondKey), API distinta por completo. Esta es la de
|
|
||||||
// apiLogin/apiKey/merchantId/accountId, la que cubre Colombia.
|
|
||||||
|
|
||||||
export type PayuEnv = "sandbox" | "production";
|
|
||||||
|
|
||||||
export interface PayuCredentials {
|
|
||||||
apiLogin: string;
|
|
||||||
apiKey: string;
|
|
||||||
merchantId: string;
|
|
||||||
accountId: string;
|
|
||||||
env: PayuEnv;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BASE_URL: Record<PayuEnv, string> = {
|
|
||||||
sandbox: "https://sandbox.api.payulatam.com/payments-api/4.0/service.cgi",
|
|
||||||
production: "https://api.payulatam.com/payments-api/4.0/service.cgi",
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function payuRequest(
|
|
||||||
credentials: PayuCredentials,
|
|
||||||
body: Record<string, unknown>,
|
|
||||||
): Promise<Record<string, unknown>> {
|
|
||||||
const response = await fetch(BASE_URL[credentials.env], {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
test: credentials.env === "sandbox",
|
|
||||||
language: "es",
|
|
||||||
...body,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const text = await response.text();
|
|
||||||
let json: Record<string, unknown>;
|
|
||||||
try {
|
|
||||||
json = JSON.parse(text);
|
|
||||||
} catch {
|
|
||||||
throw new Error(`Respuesta no-JSON de PayU (HTTP ${response.status}): ${text.slice(0, 300)}`);
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`PayU respondió HTTP ${response.status}: ${JSON.stringify(json).slice(0, 300)}`);
|
|
||||||
}
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PayuBank {
|
|
||||||
id: string;
|
|
||||||
description: string;
|
|
||||||
pseCode: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchPseBanks(credentials: PayuCredentials): Promise<PayuBank[]> {
|
|
||||||
const json = await payuRequest(credentials, {
|
|
||||||
command: "GET_BANKS_LIST",
|
|
||||||
bankListInformation: { paymentMethod: "PSE", paymentCountry: "CO" },
|
|
||||||
});
|
|
||||||
const banks = (json.banks ?? []) as Array<{
|
|
||||||
id?: unknown;
|
|
||||||
description?: unknown;
|
|
||||||
pseCode?: unknown;
|
|
||||||
}>;
|
|
||||||
return banks
|
|
||||||
.filter((bank) => typeof bank.pseCode === "string" && typeof bank.description === "string")
|
|
||||||
.map((bank) => ({
|
|
||||||
id: String(bank.id ?? bank.pseCode),
|
|
||||||
description: String(bank.description),
|
|
||||||
pseCode: String(bank.pseCode),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Regla documentada de PayU para el campo de monto de la firma: si el
|
|
||||||
// segundo decimal es cero, un solo decimal (150.00 -> "150.0",
|
|
||||||
// 150.20 -> "150.2"); si no, dos decimales (150.25 -> "150.25").
|
|
||||||
export function formatPayuAmount(amount: number): string {
|
|
||||||
const twoDecimals = amount.toFixed(2);
|
|
||||||
return twoDecimals.endsWith("0") ? amount.toFixed(1) : twoDecimals;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Firma de la orden (SUBMIT_TRANSACTION) -- distinta de la firma del
|
|
||||||
// webhook de abajo, confirmado contra el SDK PHP oficial de PayU.
|
|
||||||
export function buildOrderSignature(params: {
|
|
||||||
apiKey: string;
|
|
||||||
merchantId: string;
|
|
||||||
referenceCode: string;
|
|
||||||
amount: string;
|
|
||||||
currency: string;
|
|
||||||
}): string {
|
|
||||||
const raw = `${params.apiKey}~${params.merchantId}~${params.referenceCode}~${params.amount}~${params.currency}`;
|
|
||||||
return createHash("md5").update(raw).digest("hex");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Firma del webhook de confirmación (notifyUrl) -- lo único que impide
|
|
||||||
// que cualquiera falsifique una confirmación de pago. Falla cerrado:
|
|
||||||
// cualquier mismatch devuelve false, nunca se traga la excepción.
|
|
||||||
export function verifyWebhookSignature(params: {
|
|
||||||
apiKey: string;
|
|
||||||
merchantId: string;
|
|
||||||
referenceSale: string;
|
|
||||||
value: string;
|
|
||||||
currency: string;
|
|
||||||
statePol: string;
|
|
||||||
sign: string;
|
|
||||||
}): boolean {
|
|
||||||
const raw = `${params.apiKey}~${params.merchantId}~${params.referenceSale}~${params.value}~${params.currency}~${params.statePol}`;
|
|
||||||
const expected = createHash("md5").update(raw).digest("hex");
|
|
||||||
return expected.toLowerCase() === params.sign.toLowerCase();
|
|
||||||
}
|
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||||
import PayuPseProviderService from "./service";
|
import EpaycoPseProviderService from "./service";
|
||||||
|
|
||||||
export default ModuleProvider(Modules.PAYMENT, {
|
export default ModuleProvider(Modules.PAYMENT, {
|
||||||
services: [PayuPseProviderService],
|
services: [EpaycoPseProviderService],
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { AbstractPaymentProvider, BigNumber } from "@medusajs/framework/utils";
|
||||||
|
import type {
|
||||||
|
AuthorizePaymentInput,
|
||||||
|
AuthorizePaymentOutput,
|
||||||
|
CancelPaymentInput,
|
||||||
|
CancelPaymentOutput,
|
||||||
|
CapturePaymentInput,
|
||||||
|
CapturePaymentOutput,
|
||||||
|
DeletePaymentInput,
|
||||||
|
DeletePaymentOutput,
|
||||||
|
GetPaymentStatusInput,
|
||||||
|
GetPaymentStatusOutput,
|
||||||
|
InitiatePaymentInput,
|
||||||
|
InitiatePaymentOutput,
|
||||||
|
Logger,
|
||||||
|
ProviderWebhookPayload,
|
||||||
|
RefundPaymentInput,
|
||||||
|
RefundPaymentOutput,
|
||||||
|
RetrievePaymentInput,
|
||||||
|
RetrievePaymentOutput,
|
||||||
|
UpdatePaymentInput,
|
||||||
|
UpdatePaymentOutput,
|
||||||
|
WebhookActionResult,
|
||||||
|
} from "@medusajs/framework/types";
|
||||||
|
import { createEpaycoClient, verifyWebhookSignature } from "../../lib/epayco";
|
||||||
|
import type { EpaycoPseInputData, EpaycoPseOptions, EpaycoPseSessionData } from "./types";
|
||||||
|
|
||||||
|
type InjectedDependencies = {
|
||||||
|
logger: Logger;
|
||||||
|
};
|
||||||
|
|
||||||
|
// PSE via ePayco es asincrono igual que PayU/Rapyd: no hay confirmacion
|
||||||
|
// real hasta que llega el webhook (url_confirmation), nunca en la
|
||||||
|
// respuesta sincrona de bank.create(). authorizePayment/capturePayment
|
||||||
|
// por eso son casi no-ops -- el estado real lo trae siempre el webhook.
|
||||||
|
export default class EpaycoPseProviderService extends AbstractPaymentProvider<EpaycoPseOptions> {
|
||||||
|
static identifier = "epayco";
|
||||||
|
|
||||||
|
protected logger_: Logger;
|
||||||
|
protected options_: EpaycoPseOptions;
|
||||||
|
|
||||||
|
constructor(container: InjectedDependencies, options: EpaycoPseOptions) {
|
||||||
|
super(container, options);
|
||||||
|
this.logger_ = container.logger;
|
||||||
|
this.options_ = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateOptions(options: Record<string, unknown>): void {
|
||||||
|
for (const key of ["publicKey", "privateKey", "pCustIdCliente", "pKey", "env", "responseUrl", "notifyUrl"]) {
|
||||||
|
if (!options[key]) {
|
||||||
|
throw new Error(`epayco-pse: falta la opción "${key}" en medusa-config.ts`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseInputData & { session_id: string };
|
||||||
|
const sessionId = data.session_id;
|
||||||
|
const amount = new BigNumber(input.amount).numeric;
|
||||||
|
const currency = input.currency_code.toUpperCase();
|
||||||
|
|
||||||
|
const client = createEpaycoClient(this.options_);
|
||||||
|
|
||||||
|
// Campos confirmados leyendo node_modules/epayco-sdk-node/lib/keylang.json
|
||||||
|
// y tests/bank.js directamente (no la documentacion publica -- esa
|
||||||
|
// mostraba "metodoconfirmacion", el codigo real que de verdad manda
|
||||||
|
// el SDK usa "method_confirmation"). El SDK cifra estos valores y
|
||||||
|
// agrega ip/test/auth por su cuenta, no hace falta hacerlo nosotros.
|
||||||
|
const response = await client.bank.create({
|
||||||
|
bank: data.bank_code,
|
||||||
|
invoice: sessionId,
|
||||||
|
description: `Orden ARI Shopping ${sessionId}`,
|
||||||
|
value: String(amount),
|
||||||
|
tax: "0",
|
||||||
|
tax_base: "0",
|
||||||
|
currency,
|
||||||
|
type_person: data.user_type,
|
||||||
|
doc_type: data.doc_type,
|
||||||
|
doc_number: data.doc_number,
|
||||||
|
name: data.first_name,
|
||||||
|
last_name: data.last_name,
|
||||||
|
email: data.email,
|
||||||
|
country: "CO",
|
||||||
|
city: data.city,
|
||||||
|
cell_phone: data.phone,
|
||||||
|
url_response: this.options_.responseUrl,
|
||||||
|
url_confirmation: this.options_.notifyUrl,
|
||||||
|
method_confirmation: "POST",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
throw new Error(`ePayco rechazó la transacción para la sesión ${sessionId}: ${JSON.stringify(response).slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// El nombre real del campo con la URL de redirección al banco NO
|
||||||
|
// quedó verificado contra una respuesta real de sandbox en esta
|
||||||
|
// sesión (ni la doc ni los tests del SDK lo muestran) -- se prueban
|
||||||
|
// los candidatos más probables y, si ninguno aparece, se tira un
|
||||||
|
// error con el payload completo para poder leerlo en los logs y
|
||||||
|
// corregir esto en el primer intento real contra el sandbox.
|
||||||
|
const flat = (response.data ?? response) as Record<string, unknown>;
|
||||||
|
const bankUrlCandidates = ["urlbanco", "url_banco", "urlBanco", "url", "redirect_url"];
|
||||||
|
const bankUrl = bankUrlCandidates.map((key) => flat[key]).find((value) => typeof value === "string" && value);
|
||||||
|
|
||||||
|
if (typeof bankUrl !== "string" || !bankUrl) {
|
||||||
|
throw new Error(
|
||||||
|
`ePayco no devolvió una URL de banco reconocible para la sesión ${sessionId}. Respuesta completa (revisar para corregir el nombre del campo): ${JSON.stringify(response).slice(0, 500)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionData: EpaycoPseSessionData = {
|
||||||
|
...data,
|
||||||
|
session_id: sessionId,
|
||||||
|
ref_payco: String(flat.ref_payco ?? flat.refPayco ?? ""),
|
||||||
|
transaction_id: String(flat.transactionID ?? flat.transaction_id ?? ""),
|
||||||
|
bank_url: bankUrl,
|
||||||
|
state: "PENDING",
|
||||||
|
amount,
|
||||||
|
currency,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { id: sessionId, data: sessionData as unknown as Record<string, unknown>, status: "pending" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSE es diferido: en el momento de completar el carrito, ePayco
|
||||||
|
// todavia no confirmo nada -- "pending_authorization" es el mecanismo
|
||||||
|
// documentado de Medusa para esto (la orden queda "awaiting" y el
|
||||||
|
// navegador ya puede redirigirse al banco).
|
||||||
|
async authorizePayment(input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
|
||||||
|
return { data: input.data, status: "pending_authorization" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casi no-op: cuando el webhook reporta "captured", ePayco ya liquido
|
||||||
|
// el dinero de su lado -- solo persiste el data actualizado.
|
||||||
|
async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
|
||||||
|
this.logger_.warn("epayco-pse: cancelPayment llamado, pero PSE no soporta cancelar una transacción ya enviada");
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Endpoint de reembolso de ePayco no quedó verificado en vivo en esta
|
||||||
|
// sesión -- con dinero real de por medio, mejor tirar un error
|
||||||
|
// explícito que fingir un reembolso que nunca se procesó.
|
||||||
|
async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
|
||||||
|
throw new Error(
|
||||||
|
"epayco-pse: refundPayment no está implementado todavía -- procesar el reembolso manualmente desde el panel de ePayco por ahora.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /validation/v1/reference/{ref_payco} -- endpoint de verificación
|
||||||
|
// server-to-server documentado por ePayco para consultar el estado
|
||||||
|
// real de una transacción.
|
||||||
|
async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseSessionData | undefined;
|
||||||
|
const refPayco = data?.ref_payco;
|
||||||
|
if (!refPayco) {
|
||||||
|
throw new Error("epayco-pse: retrievePayment necesita ref_payco, no está guardado en esta sesión.");
|
||||||
|
}
|
||||||
|
const response = await fetch(`https://secure.epayco.co/validation/v1/reference/${refPayco}`);
|
||||||
|
const json = await response.json();
|
||||||
|
return { data: json as Record<string, unknown> };
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
|
||||||
|
// ePayco no tiene concepto de "modificar" una transaccion ya
|
||||||
|
// enviada. El checkout solo llega al step de pago despues de fijar
|
||||||
|
// direccion y envio, asi que el total no deberia cambiar una vez que
|
||||||
|
// existe una sesion PSE.
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseSessionData | undefined;
|
||||||
|
const state = data?.state;
|
||||||
|
if (state === "1") return { status: "captured" };
|
||||||
|
if (state === "3") return { status: "pending" };
|
||||||
|
if (state === "PENDING") return { status: "pending" };
|
||||||
|
return { status: "canceled" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unico punto real de confirmacion asincrona. Falla cerrado: si la
|
||||||
|
// firma no matchea, no se hace nada -- nunca se confia en un webhook
|
||||||
|
// sin firma valida.
|
||||||
|
async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
|
||||||
|
const body = payload.data as Record<string, unknown>;
|
||||||
|
const refPayco = String(body.x_ref_payco ?? "");
|
||||||
|
const transactionId = String(body.x_transaction_id ?? "");
|
||||||
|
const amount = String(body.x_amount ?? "");
|
||||||
|
const currencyCode = String(body.x_currency_code ?? "");
|
||||||
|
const codState = String(body.x_cod_transaction_state ?? "");
|
||||||
|
const signature = String(body.x_signature ?? "");
|
||||||
|
// session_id sale del invoice que nosotros mandamos -- ePayco lo
|
||||||
|
// devuelve como x_id_invoice (o x_extra1 si no viniera) segun el
|
||||||
|
// webhook real; se intentan ambos.
|
||||||
|
const sessionId = String(body.x_id_invoice ?? body.x_extra1 ?? refPayco);
|
||||||
|
|
||||||
|
const validSignature = verifyWebhookSignature({
|
||||||
|
pCustIdCliente: this.options_.pCustIdCliente,
|
||||||
|
pKey: this.options_.pKey,
|
||||||
|
refPayco,
|
||||||
|
transactionId,
|
||||||
|
amount,
|
||||||
|
currencyCode,
|
||||||
|
signature,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!validSignature) {
|
||||||
|
this.logger_.warn(`epayco-pse: webhook con firma inválida para x_ref_payco=${refPayco}, ignorado`);
|
||||||
|
return { action: "not_supported" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo "1" (Aceptada) es exito -- cualquier otro codigo (2 Rechazada,
|
||||||
|
// 4 Fallida, 6 Reversada, 9 caducada, 10 abandonada, 11 Cancelada,
|
||||||
|
// 3 Pendiente) se trata como fallido en vez de asumir un exito
|
||||||
|
// distinto. Un "failed" de mas es reintentable; un "captured" de mas
|
||||||
|
// (dinero que nunca se aprobo) no lo es.
|
||||||
|
const action = codState === "1" ? "captured" : "failed";
|
||||||
|
|
||||||
|
return {
|
||||||
|
action,
|
||||||
|
data: {
|
||||||
|
session_id: sessionId,
|
||||||
|
amount: new BigNumber(amount || 0),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { EpaycoEnv } from "../../lib/epayco";
|
||||||
|
|
||||||
|
export interface EpaycoPseOptions {
|
||||||
|
publicKey: string;
|
||||||
|
privateKey: string;
|
||||||
|
// p_cust_id_cliente / p_key -- valores propios del dashboard de ePayco
|
||||||
|
// para verificar la firma del webhook, distintos de publicKey/privateKey.
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
env: EpaycoEnv;
|
||||||
|
// A donde ePayco redirige al comprador de vuelta tras pagar en el
|
||||||
|
// banco (pagina propia del storefront, no confirma nada por si sola).
|
||||||
|
responseUrl: string;
|
||||||
|
// URL publica de confirmacion -- por-transaccion (a diferencia de
|
||||||
|
// Rapyd, que solo permite configurarlo una vez a nivel de cuenta),
|
||||||
|
// apunta a la ruta nativa de Medusa /hooks/payment/:provider.
|
||||||
|
notifyUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EpaycoDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
// "0" persona natural, "1" persona juridica -- valores reales que espera
|
||||||
|
// el campo type_person de ePayco.
|
||||||
|
export type EpaycoUserType = "0" | "1";
|
||||||
|
|
||||||
|
// Lo que el storefront manda como `data` al crear la sesion de pago PSE
|
||||||
|
// (recolectado en el step "address" del checkout, mas el banco/tipo de
|
||||||
|
// persona/documento del nuevo step "payment"). No viene de
|
||||||
|
// `context.customer` porque el checkout es de invitado -- ver ADR 0009.
|
||||||
|
export interface EpaycoPseInputData {
|
||||||
|
bank_code: string;
|
||||||
|
user_type: EpaycoUserType;
|
||||||
|
doc_type: EpaycoDocType;
|
||||||
|
doc_number: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
city: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lo que initiatePayment devuelve y queda guardado en `data` de la
|
||||||
|
// PaymentSession -- publico para el storefront, nunca poner credenciales
|
||||||
|
// acá. `bank_url`: nombre de campo AUN NO VERIFICADO contra una
|
||||||
|
// respuesta real de sandbox (ver comentario en service.ts) -- primer
|
||||||
|
// punto a confirmar en la primera prueba end-to-end.
|
||||||
|
export interface EpaycoPseSessionData extends EpaycoPseInputData {
|
||||||
|
session_id: string;
|
||||||
|
ref_payco: string;
|
||||||
|
transaction_id: string;
|
||||||
|
bank_url: string;
|
||||||
|
state: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
import { AbstractPaymentProvider, BigNumber } from "@medusajs/framework/utils";
|
|
||||||
import type {
|
|
||||||
AuthorizePaymentInput,
|
|
||||||
AuthorizePaymentOutput,
|
|
||||||
CancelPaymentInput,
|
|
||||||
CancelPaymentOutput,
|
|
||||||
CapturePaymentInput,
|
|
||||||
CapturePaymentOutput,
|
|
||||||
DeletePaymentInput,
|
|
||||||
DeletePaymentOutput,
|
|
||||||
GetPaymentStatusInput,
|
|
||||||
GetPaymentStatusOutput,
|
|
||||||
InitiatePaymentInput,
|
|
||||||
InitiatePaymentOutput,
|
|
||||||
Logger,
|
|
||||||
ProviderWebhookPayload,
|
|
||||||
RefundPaymentInput,
|
|
||||||
RefundPaymentOutput,
|
|
||||||
RetrievePaymentInput,
|
|
||||||
RetrievePaymentOutput,
|
|
||||||
UpdatePaymentInput,
|
|
||||||
UpdatePaymentOutput,
|
|
||||||
WebhookActionResult,
|
|
||||||
} from "@medusajs/framework/types";
|
|
||||||
import { buildOrderSignature, formatPayuAmount, payuRequest, verifyWebhookSignature } from "../../lib/payu";
|
|
||||||
import type { PayuPseInputData, PayuPseOptions, PayuPseSessionData } from "./types";
|
|
||||||
|
|
||||||
type InjectedDependencies = {
|
|
||||||
logger: Logger;
|
|
||||||
};
|
|
||||||
|
|
||||||
// PSE es AUTHORIZATION_AND_CAPTURE en un solo paso del lado de PayU, y
|
|
||||||
// asincrono: no hay confirmacion real hasta que llega el webhook (ver
|
|
||||||
// getWebhookActionAndData). authorizePayment/capturePayment por eso son
|
|
||||||
// casi no-ops -- el estado real lo trae siempre el webhook, nunca una
|
|
||||||
// llamada sincrona nuestra a PayU.
|
|
||||||
export default class PayuPseProviderService extends AbstractPaymentProvider<PayuPseOptions> {
|
|
||||||
static identifier = "payu";
|
|
||||||
|
|
||||||
protected logger_: Logger;
|
|
||||||
protected options_: PayuPseOptions;
|
|
||||||
|
|
||||||
constructor(container: InjectedDependencies, options: PayuPseOptions) {
|
|
||||||
super(container, options);
|
|
||||||
this.logger_ = container.logger;
|
|
||||||
this.options_ = options;
|
|
||||||
}
|
|
||||||
|
|
||||||
static validateOptions(options: Record<string, unknown>): void {
|
|
||||||
for (const key of ["apiLogin", "apiKey", "merchantId", "accountId", "env", "responseUrl", "notifyUrl"]) {
|
|
||||||
if (!options[key]) {
|
|
||||||
throw new Error(`payu-pse: falta la opción "${key}" en medusa-config.ts`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
|
|
||||||
const data = input.data as unknown as PayuPseInputData & { session_id: string };
|
|
||||||
const sessionId = data.session_id;
|
|
||||||
const amount = new BigNumber(input.amount).numeric;
|
|
||||||
const currency = input.currency_code.toUpperCase();
|
|
||||||
const formattedAmount = formatPayuAmount(amount);
|
|
||||||
|
|
||||||
const signature = buildOrderSignature({
|
|
||||||
apiKey: this.options_.apiKey,
|
|
||||||
merchantId: this.options_.merchantId,
|
|
||||||
referenceCode: sessionId,
|
|
||||||
amount: formattedAmount,
|
|
||||||
currency,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Shape del request confirmado contra la documentacion real de PayU
|
|
||||||
// LatAm para command/paymentMethod/extraParameters -- la anidacion
|
|
||||||
// exacta de buyer/payer (nombres de campo dentro de esos objetos) no
|
|
||||||
// quedo verificada campo por campo contra una respuesta real de
|
|
||||||
// sandbox en esta sesion. Primera prueba end-to-end contra el
|
|
||||||
// sandbox real de PayU debe confirmar esto (ver plan de
|
|
||||||
// implementacion, seccion Verificacion).
|
|
||||||
const json = await payuRequest(
|
|
||||||
{ apiLogin: this.options_.apiLogin, apiKey: this.options_.apiKey, merchantId: this.options_.merchantId, accountId: this.options_.accountId, env: this.options_.env },
|
|
||||||
{
|
|
||||||
command: "SUBMIT_TRANSACTION",
|
|
||||||
merchant: {
|
|
||||||
apiLogin: this.options_.apiLogin,
|
|
||||||
apiKey: this.options_.apiKey,
|
|
||||||
},
|
|
||||||
transaction: {
|
|
||||||
order: {
|
|
||||||
accountId: this.options_.accountId,
|
|
||||||
referenceCode: sessionId,
|
|
||||||
description: `Orden ARI Shopping ${sessionId}`,
|
|
||||||
language: "es",
|
|
||||||
signature,
|
|
||||||
notifyUrl: this.options_.notifyUrl,
|
|
||||||
additionalValues: {
|
|
||||||
TX_VALUE: { value: amount, currency },
|
|
||||||
},
|
|
||||||
buyer: {
|
|
||||||
fullName: data.full_name,
|
|
||||||
emailAddress: data.email,
|
|
||||||
contactPhone: data.phone,
|
|
||||||
dniNumber: data.doc_number,
|
|
||||||
shippingAddress: {
|
|
||||||
street1: data.address,
|
|
||||||
city: data.city,
|
|
||||||
state: data.state,
|
|
||||||
country: "CO",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payer: {
|
|
||||||
fullName: data.full_name,
|
|
||||||
emailAddress: data.email,
|
|
||||||
contactPhone: data.phone,
|
|
||||||
dniNumber: data.doc_number,
|
|
||||||
billingAddress: {
|
|
||||||
street1: data.address,
|
|
||||||
city: data.city,
|
|
||||||
state: data.state,
|
|
||||||
country: "CO",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
type: "AUTHORIZATION_AND_CAPTURE",
|
|
||||||
paymentMethod: "PSE",
|
|
||||||
paymentCountry: "CO",
|
|
||||||
extraParameters: {
|
|
||||||
RESPONSE_URL: this.options_.responseUrl,
|
|
||||||
FINANCIAL_INSTITUTION_CODE: data.bank_code,
|
|
||||||
USER_TYPE: data.user_type,
|
|
||||||
PSE_REFERENCE2: data.doc_type,
|
|
||||||
PSE_REFERENCE3: data.doc_number,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const transactionResponse = (json.transactionResponse ?? {}) as Record<string, unknown>;
|
|
||||||
const extraParameters = (transactionResponse.extraParameters ?? {}) as Record<string, unknown>;
|
|
||||||
const bankUrl = extraParameters.BANK_URL;
|
|
||||||
if (typeof bankUrl !== "string" || !bankUrl) {
|
|
||||||
throw new Error(
|
|
||||||
`PayU no devolvió BANK_URL para la sesión ${sessionId}: ${JSON.stringify(transactionResponse).slice(0, 300)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionData: PayuPseSessionData = {
|
|
||||||
...data,
|
|
||||||
session_id: sessionId,
|
|
||||||
payu_order_id: String(transactionResponse.orderId ?? ""),
|
|
||||||
payu_transaction_id: String(transactionResponse.transactionId ?? ""),
|
|
||||||
reference_code: sessionId,
|
|
||||||
bank_url: bankUrl,
|
|
||||||
state: String(transactionResponse.state ?? "PENDING"),
|
|
||||||
amount,
|
|
||||||
currency,
|
|
||||||
};
|
|
||||||
|
|
||||||
return { id: sessionId, data: sessionData as unknown as Record<string, unknown>, status: "pending" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// PSE es diferido: en el momento de completar el carrito, PayU todavia
|
|
||||||
// no confirmo nada -- "pending_authorization" es el mecanismo
|
|
||||||
// documentado de Medusa para esto (la orden queda "awaiting" y el
|
|
||||||
// navegador ya puede redirigirse al banco).
|
|
||||||
async authorizePayment(input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
|
|
||||||
return { data: input.data, status: "pending_authorization" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Casi no-op: cuando el webhook reporta "captured", PayU ya liquido el
|
|
||||||
// dinero de su lado (un solo paso AUTHORIZATION_AND_CAPTURE) -- solo
|
|
||||||
// persiste el data actualizado.
|
|
||||||
async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
|
|
||||||
return { data: input.data };
|
|
||||||
}
|
|
||||||
|
|
||||||
// PSE no tiene concepto de cancelar una transaccion ya enviada al banco.
|
|
||||||
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
|
|
||||||
this.logger_.warn("payu-pse: cancelPayment llamado, pero PSE no soporta cancelar una transacción ya enviada");
|
|
||||||
return { data: input.data };
|
|
||||||
}
|
|
||||||
|
|
||||||
async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
|
|
||||||
return { data: input.data };
|
|
||||||
}
|
|
||||||
|
|
||||||
// No verificado contra el endpoint real de PayU en esta sesión -- con
|
|
||||||
// dinero real de por medio, mejor tirar un error explícito que fingir
|
|
||||||
// un reembolso que nunca llamó a PayU.
|
|
||||||
async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
|
|
||||||
throw new Error(
|
|
||||||
"payu-pse: refundPayment no está implementado todavía -- el endpoint de reembolso de PayU LatAm no quedó verificado en vivo. Procesar el reembolso manualmente desde el panel de PayU por ahora.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Idem refundPayment: no verificado en vivo, mejor fallar explícito.
|
|
||||||
async retrievePayment(_input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
|
|
||||||
throw new Error("payu-pse: retrievePayment no está implementado todavía -- usar el panel de PayU para consultar una transacción.");
|
|
||||||
}
|
|
||||||
|
|
||||||
async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
|
|
||||||
// PayU no tiene concepto de "modificar" una transaccion ya enviada.
|
|
||||||
// El checkout solo llega al step de pago despues de fijar direccion
|
|
||||||
// y envio, asi que el total no deberia cambiar una vez que existe
|
|
||||||
// una sesion PSE -- si esto se dispara, es una señal de que algo
|
|
||||||
// cambió el carrito después de crear la sesión.
|
|
||||||
return { data: input.data };
|
|
||||||
}
|
|
||||||
|
|
||||||
async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
|
|
||||||
const data = input.data as unknown as PayuPseSessionData | undefined;
|
|
||||||
const state = data?.state;
|
|
||||||
if (state === "APPROVED") return { status: "captured" };
|
|
||||||
if (state === "DECLINED" || state === "EXPIRED" || state === "ERROR") return { status: "canceled" };
|
|
||||||
return { status: "pending" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unico punto real de confirmacion asincrona. Falla cerrado: si la
|
|
||||||
// firma no matchea, no se hace nada -- nunca se confia en un webhook
|
|
||||||
// sin firma valida, es lo unico que impide que cualquiera falsifique
|
|
||||||
// un pago aprobado.
|
|
||||||
async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
|
|
||||||
const body = payload.data as Record<string, unknown>;
|
|
||||||
const merchantId = String(body.merchant_id ?? "");
|
|
||||||
const referenceSale = String(body.reference_sale ?? "");
|
|
||||||
const value = String(body.value ?? "");
|
|
||||||
const currency = String(body.currency ?? "");
|
|
||||||
const statePol = String(body.state_pol ?? "");
|
|
||||||
const sign = String(body.sign ?? "");
|
|
||||||
|
|
||||||
const validSignature = verifyWebhookSignature({
|
|
||||||
apiKey: this.options_.apiKey,
|
|
||||||
merchantId,
|
|
||||||
referenceSale,
|
|
||||||
value,
|
|
||||||
currency,
|
|
||||||
statePol,
|
|
||||||
sign,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!validSignature) {
|
|
||||||
this.logger_.warn(`payu-pse: webhook con firma inválida para reference_sale=${referenceSale}, ignorado`);
|
|
||||||
return { action: "not_supported" };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Solo state_pol "4" (aprobado) es exito -- la tabla completa de
|
|
||||||
// codigos no quedo 100% verificada, asi que cualquier otro valor se
|
|
||||||
// trata como fallido en vez de asumir que es un exito distinto. Un
|
|
||||||
// "failed" de mas es reintentable; un "captured" de mas (dinero que
|
|
||||||
// nunca se aprobo) no lo es.
|
|
||||||
const action = statePol === "4" ? "captured" : "failed";
|
|
||||||
|
|
||||||
return {
|
|
||||||
action,
|
|
||||||
data: {
|
|
||||||
session_id: referenceSale,
|
|
||||||
amount: new BigNumber(value || 0),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import type { PayuEnv } from "../../lib/payu";
|
|
||||||
|
|
||||||
export interface PayuPseOptions {
|
|
||||||
apiLogin: string;
|
|
||||||
apiKey: string;
|
|
||||||
merchantId: string;
|
|
||||||
accountId: string;
|
|
||||||
env: PayuEnv;
|
|
||||||
// A donde PayU redirige al comprador de vuelta tras pagar en el banco
|
|
||||||
// (pagina propia del storefront, no confirma nada por si sola -- ver
|
|
||||||
// src/modules/payu-pse/service.ts).
|
|
||||||
responseUrl: string;
|
|
||||||
// URL publica de notifyUrl -- la rellena Medusa (ruta nativa
|
|
||||||
// /hooks/payment/:provider, no la escribimos nosotros), ver
|
|
||||||
// medusa-config.ts.
|
|
||||||
notifyUrl: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PayuDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
|
||||||
export type PayuUserType = "N" | "J";
|
|
||||||
|
|
||||||
// Lo que el storefront manda como `data` al crear la sesion de pago PSE
|
|
||||||
// (recolectado en el step "address" del checkout, mas el banco elegido en
|
|
||||||
// el nuevo step "payment"). No viene de `context.customer` porque el
|
|
||||||
// checkout es de invitado -- ver ADR 0009.
|
|
||||||
export interface PayuPseInputData {
|
|
||||||
bank_code: string;
|
|
||||||
user_type: PayuUserType;
|
|
||||||
doc_type: PayuDocType;
|
|
||||||
doc_number: string;
|
|
||||||
full_name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
address: string;
|
|
||||||
city: string;
|
|
||||||
// Nombre del departamento (PayU pide "state" como texto libre, no un
|
|
||||||
// codigo DIVIPOLA como el resto del checkout).
|
|
||||||
state: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lo que initiatePayment devuelve y queda guardado en `data` de la
|
|
||||||
// PaymentSession -- publico para el storefront (ver nota en
|
|
||||||
// AbstractPaymentProvider.initiatePayment), nunca poner credenciales acá.
|
|
||||||
export interface PayuPseSessionData extends PayuPseInputData {
|
|
||||||
session_id: string;
|
|
||||||
payu_order_id: string;
|
|
||||||
payu_transaction_id: string;
|
|
||||||
reference_code: string;
|
|
||||||
bank_url: string;
|
|
||||||
state: string;
|
|
||||||
amount: number;
|
|
||||||
currency: string;
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ import { createPaymentCollection, createPsePaymentSession } from "@/lib/headless
|
|||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const { cartId, ...pse } = await request.json();
|
const { cartId, ...pse } = await request.json();
|
||||||
if (!cartId || !pse.bankCode || !pse.docNumber || !pse.fullName || !pse.email || !pse.phone) {
|
if (!cartId || !pse.bankCode || !pse.docNumber || !pse.firstName || !pse.lastName || !pse.email || !pse.phone) {
|
||||||
return Response.json({ error: "Faltan campos obligatorios para el pago con PSE" }, { status: 400 });
|
return Response.json({ error: "Faltan campos obligatorios para el pago con PSE" }, { status: 400 });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -25,10 +25,11 @@ data:
|
|||||||
# MEILI_MASTER_KEY en secrets.template.yaml).
|
# MEILI_MASTER_KEY en secrets.template.yaml).
|
||||||
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
||||||
|
|
||||||
# PayU LatAm (ADR 0009) -- solo URLs/config no sensible, credenciales
|
# ePayco (ADR 0009 -- tercer proveedor evaluado, ver medusa-config.ts
|
||||||
# reales (apiLogin/apiKey/merchantId/accountId) van en
|
# para el historial completo) -- solo URLs/config no sensible,
|
||||||
# secrets.template.yaml. PAYU_ENV=sandbox hasta que haya credenciales
|
# credenciales reales (publicKey/privateKey/pCustIdCliente/pKey) van en
|
||||||
|
# secrets.template.yaml. EPAYCO_ENV=sandbox hasta que haya credenciales
|
||||||
# de produccion reales.
|
# de produccion reales.
|
||||||
PAYU_ENV: sandbox
|
EPAYCO_ENV: sandbox
|
||||||
PAYU_RESPONSE_URL: https://shop.cruzcloud.net/checkout/pse/return
|
EPAYCO_RESPONSE_URL: https://shop.cruzcloud.net/checkout/pse/return
|
||||||
PAYU_NOTIFY_URL: https://commerce.cruzcloud.net/hooks/payment/payu_pse
|
EPAYCO_NOTIFY_URL: https://commerce.cruzcloud.net/hooks/payment/epayco_pse
|
||||||
@@ -36,14 +36,17 @@ stringData:
|
|||||||
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
||||||
REVALIDATE_SECRET: CAMBIAR
|
REVALIDATE_SECRET: CAMBIAR
|
||||||
|
|
||||||
# PayU LatAm (ADR 0009) -- credenciales del comercio. Mientras no exista
|
# ePayco (ADR 0009 -- tercer proveedor evaluado: PayU LatAm quedó
|
||||||
# cuenta real, usar las de sandbox genéricas y públicas de PayU
|
# inviable porque Rapyd compró ese negocio en 2023, Rapyd descartado
|
||||||
# (developers.payulatam.com/latam/en/docs/getting-started/test-your-solution.html),
|
# por costo; ePayco es de Davivienda desde 2024, mejor tarifa PSE para
|
||||||
# nunca hardcodeadas acá.
|
# el volumen real del usuario). Credenciales del comercio real, nunca
|
||||||
PAYU_API_LOGIN: CAMBIAR
|
# hardcodeadas acá. p_cust_id_cliente/p_key son valores propios del
|
||||||
PAYU_API_KEY: CAMBIAR
|
# dashboard de ePayco (Configuración > Llaves secretas), distintos de
|
||||||
PAYU_MERCHANT_ID: CAMBIAR
|
# publicKey/privateKey.
|
||||||
PAYU_ACCOUNT_ID: CAMBIAR
|
EPAYCO_PUBLIC_KEY: CAMBIAR
|
||||||
|
EPAYCO_PRIVATE_KEY: CAMBIAR
|
||||||
|
EPAYCO_P_CUST_ID_CLIENTE: CAMBIAR
|
||||||
|
EPAYCO_P_KEY: CAMBIAR
|
||||||
---
|
---
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Secret
|
kind: Secret
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ const SELECT_CLASS =
|
|||||||
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
||||||
|
|
||||||
// ADR 0009: direccion + envio + pago real, todo contra el Store API real.
|
// ADR 0009: direccion + envio + pago real, todo contra el Store API real.
|
||||||
// El pago es PayU LatAm/PSE (modulo custom del backend, ver
|
// El pago es ePayco/PSE (modulo custom del backend, ver
|
||||||
// workloads/commerce-backend/src/modules/payu-pse) -- redirige al banco
|
// workloads/commerce-backend/src/modules/epayco-pse) -- redirige al banco
|
||||||
// del comprador, la confirmacion real llega despues via webhook async
|
// del comprador, la confirmacion real llega despues via webhook async
|
||||||
// (nunca por esta pantalla). WhatsApp queda como respaldo manual si la
|
// (nunca por esta pantalla). WhatsApp queda como respaldo manual si la
|
||||||
// iniciacion del pago falla, ya no como camino principal.
|
// iniciacion del pago falla, ya no como camino principal.
|
||||||
@@ -68,7 +68,7 @@ export function CheckoutClient() {
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [banks, setBanks] = useState<PseBank[]>([]);
|
const [banks, setBanks] = useState<PseBank[]>([]);
|
||||||
const [bankCode, setBankCode] = useState("");
|
const [bankCode, setBankCode] = useState("");
|
||||||
const [userType, setUserType] = useState<"N" | "J">("N");
|
const [userType, setUserType] = useState<"0" | "1">("0");
|
||||||
const [docType, setDocType] = useState<"CC" | "CE" | "NIT" | "TI" | "PP">("CC");
|
const [docType, setDocType] = useState<"CC" | "CE" | "NIT" | "TI" | "PP">("CC");
|
||||||
const [docNumber, setDocNumber] = useState("");
|
const [docNumber, setDocNumber] = useState("");
|
||||||
|
|
||||||
@@ -139,17 +139,16 @@ export function CheckoutClient() {
|
|||||||
userType,
|
userType,
|
||||||
docType,
|
docType,
|
||||||
docNumber,
|
docNumber,
|
||||||
fullName: `${form.firstName} ${form.lastName}`.trim(),
|
firstName: form.firstName,
|
||||||
|
lastName: form.lastName,
|
||||||
email: form.email,
|
email: form.email,
|
||||||
phone: form.phone,
|
phone: form.phone,
|
||||||
address: form.address1,
|
|
||||||
city: selectedCiudad.name,
|
city: selectedCiudad.name,
|
||||||
state: selectedDepartamento.name,
|
|
||||||
});
|
});
|
||||||
if (session.error) throw new Error(session.error);
|
if (session.error) throw new Error(session.error);
|
||||||
const completion = await postJson("/api/cart/complete", { cartId });
|
const completion = await postJson("/api/cart/complete", { cartId });
|
||||||
if (completion.error) throw new Error(completion.error);
|
if (completion.error) throw new Error(completion.error);
|
||||||
// Navegacion completa, no iframe -- asi lo exige PayU para el
|
// Navegacion completa, no iframe -- asi lo exige ePayco para el
|
||||||
// flujo de PSE. La confirmacion real llega despues via webhook,
|
// flujo de PSE. La confirmacion real llega despues via webhook,
|
||||||
// esta pagina nunca vuelve a cargar sola.
|
// esta pagina nunca vuelve a cargar sola.
|
||||||
window.location.href = session.bankUrl;
|
window.location.href = session.bankUrl;
|
||||||
@@ -260,8 +259,8 @@ export function CheckoutClient() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex gap-4 text-sm font-bold">
|
<div className="flex gap-4 text-sm font-bold">
|
||||||
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "N"} onChange={() => setUserType("N")} />Persona natural</label>
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "0"} onChange={() => setUserType("0")} />Persona natural</label>
|
||||||
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "J"} onChange={() => setUserType("J")} />Persona jurídica</label>
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "1"} onChange={() => setUserType("1")} />Persona jurídica</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ import { Clock } from "lucide-react";
|
|||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
// PayU redirige aca despues de que el comprador paga en su banco -- esto
|
// ePayco redirige aca despues de que el comprador paga en su banco --
|
||||||
// NO confirma el pago. Los parametros de esta URL son solo informativos;
|
// esto NO confirma el pago. Los parametros de esta URL son solo
|
||||||
// el estado real y definitivo llega por el webhook async de PayU al
|
// informativos; el estado real y definitivo llega por el webhook async
|
||||||
// backend (getWebhookActionAndData en el modulo payu-pse), nunca por
|
// de ePayco al backend (getWebhookActionAndData en el modulo
|
||||||
// esta pantalla. Por eso el mensaje nunca afirma exito, solo que
|
// epayco-pse), nunca por esta pantalla. Por eso el mensaje nunca afirma
|
||||||
// estamos esperando la confirmacion.
|
// exito, solo que estamos esperando la confirmacion.
|
||||||
export function PseReturnClient() {
|
export function PseReturnClient() {
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const referenceCode = searchParams.get("referenceCode") ?? searchParams.get("reference_sale");
|
const referenceCode = searchParams.get("referenceCode") ?? searchParams.get("reference_sale");
|
||||||
@@ -20,7 +20,7 @@ export function PseReturnClient() {
|
|||||||
<Clock className="mx-auto size-12 text-ari-marino" />
|
<Clock className="mx-auto size-12 text-ari-marino" />
|
||||||
<h1 className="mt-6 text-2xl font-black">Estamos confirmando tu pago</h1>
|
<h1 className="mt-6 text-2xl font-black">Estamos confirmando tu pago</h1>
|
||||||
<p className="mt-3 text-slate-500">
|
<p className="mt-3 text-slate-500">
|
||||||
Tu banco ya procesó la transferencia. PayU nos avisa en unos minutos si quedó aprobada — te llegará la confirmación por correo.
|
Tu banco ya procesó la transferencia. ePayco nos avisa en unos minutos si quedó aprobada — te llegará la confirmación por correo.
|
||||||
{referenceCode && (
|
{referenceCode && (
|
||||||
<>
|
<>
|
||||||
{" "}Tu número de referencia es <strong>{referenceCode}</strong>.
|
{" "}Tu número de referencia es <strong>{referenceCode}</strong>.
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
// ADR 0009: pago real via PayU LatAm (PSE), modulo custom del backend
|
// ADR 0009: pago real via ePayco (PSE) -- tercer proveedor evaluado
|
||||||
// (workloads/commerce-backend/src/modules/payu-pse). Archivo separado de
|
// (PayU LatAm descartado porque Rapyd compró ese negocio en 2023 y el
|
||||||
// medusa-cart.ts por el mismo motivo que ese archivo esta separado de
|
// registro real quedó con credenciales incompatibles; Rapyd descartado
|
||||||
|
// por costo). ePayco: 100% de Davivienda desde 2024, comisión PSE más
|
||||||
|
// baja para el volumen real del usuario, tarifa preferencial con cuenta
|
||||||
|
// Davivienda. Módulo custom del backend
|
||||||
|
// (workloads/commerce-backend/src/modules/epayco-pse). Archivo separado
|
||||||
|
// de medusa-cart.ts por el mismo motivo que ese archivo esta separado de
|
||||||
// medusa.ts -- reutiliza su mismo fetch helper (medusaCartFetch), no
|
// medusa.ts -- reutiliza su mismo fetch helper (medusaCartFetch), no
|
||||||
// duplica la logica de headers/no-store.
|
// duplica la logica de headers/no-store.
|
||||||
import { medusaCartFetch } from "./medusa-cart";
|
import { medusaCartFetch } from "./medusa-cart";
|
||||||
@@ -10,7 +15,9 @@ export interface PseBank {
|
|||||||
description: string;
|
description: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PseUserType = "N" | "J";
|
// "0" persona natural, "1" persona juridica -- valores reales que espera
|
||||||
|
// ePayco (campo type_person), no un codigo propio nuestro.
|
||||||
|
export type PseUserType = "0" | "1";
|
||||||
export type PseDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
export type PseDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
|
||||||
export interface PsePaymentInput {
|
export interface PsePaymentInput {
|
||||||
@@ -18,18 +25,17 @@ export interface PsePaymentInput {
|
|||||||
userType: PseUserType;
|
userType: PseUserType;
|
||||||
docType: PseDocType;
|
docType: PseDocType;
|
||||||
docNumber: string;
|
docNumber: string;
|
||||||
fullName: string;
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
address: string;
|
|
||||||
city: string;
|
city: string;
|
||||||
state: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// "pp_{identifier}_{id}" -- convencion de Medusa, confirmada contra el
|
// "pp_{identifier}_{id}" -- convencion de Medusa, confirmada contra el
|
||||||
// codigo fuente de @medusajs/payment (identifier "payu" + id "pse" en
|
// codigo fuente de @medusajs/payment (identifier "epayco" + id "pse" en
|
||||||
// medusa-config.ts).
|
// medusa-config.ts).
|
||||||
const PSE_PROVIDER_ID = "pp_payu_pse";
|
const PSE_PROVIDER_ID = "pp_epayco_pse";
|
||||||
|
|
||||||
export async function getPseBanks(): Promise<PseBank[]> {
|
export async function getPseBanks(): Promise<PseBank[]> {
|
||||||
const data = await medusaCartFetch("/store/payments/pse-banks");
|
const data = await medusaCartFetch("/store/payments/pse-banks");
|
||||||
@@ -58,12 +64,11 @@ export async function createPsePaymentSession(paymentCollectionId: string, input
|
|||||||
user_type: input.userType,
|
user_type: input.userType,
|
||||||
doc_type: input.docType,
|
doc_type: input.docType,
|
||||||
doc_number: input.docNumber,
|
doc_number: input.docNumber,
|
||||||
full_name: input.fullName,
|
first_name: input.firstName,
|
||||||
|
last_name: input.lastName,
|
||||||
email: input.email,
|
email: input.email,
|
||||||
phone: input.phone,
|
phone: input.phone,
|
||||||
address: input.address,
|
|
||||||
city: input.city,
|
city: input.city,
|
||||||
state: input.state,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -73,7 +78,7 @@ export async function createPsePaymentSession(paymentCollectionId: string, input
|
|||||||
const session = collection.payment_sessions?.find((paymentSession) => paymentSession.provider_id === PSE_PROVIDER_ID);
|
const session = collection.payment_sessions?.find((paymentSession) => paymentSession.provider_id === PSE_PROVIDER_ID);
|
||||||
const bankUrl = session?.data?.bank_url;
|
const bankUrl = session?.data?.bank_url;
|
||||||
if (!bankUrl) {
|
if (!bankUrl) {
|
||||||
throw new Error("PayU no devolvió la URL del banco para completar el pago.");
|
throw new Error("ePayco no devolvió la URL del banco para completar el pago.");
|
||||||
}
|
}
|
||||||
return bankUrl;
|
return bankUrl;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user