var apiKey; var imagen_pasarela; async function cargarEnv() { const response = await fetch('.app_config'); const texto = await response.text(); const env = {}; texto.split('\n').forEach(linea => { // Ignorar comentarios y líneas vacías if (linea.trim() && !linea.startsWith('#')) { const [clave, ...valores] = linea.split('='); env[clave.trim()] = valores.join('=').trim(); } }); return env; } function stripeTokenHandler(token) { let form = document.getElementById("payment-form"); let hiddenInput = document.createElement("input"); hiddenInput.setAttribute("type", "hidden"); hiddenInput.setAttribute("name", "stripeToken"); hiddenInput.setAttribute("value", token.id); form.appendChild(hiddenInput); } // CAMBIO PRINCIPAL: Hacer que todo el DOMContentLoaded sea asíncrono document.addEventListener("DOMContentLoaded", async () => { // Primero cargar el env y ESPERAR a que termine const env = await cargarEnv(); apiKey = env.apiKey_pasarela; imagen_pasarela = env.imagen_pasarela; // Ahora sí continuar con el resto del código fetch("https://gateway.calidadbmasconsulting.com/api/obtLavePublicaStripe", { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json", }, body: JSON.stringify({ apiKey: apiKey }), }) .then((response) => response.json()) .then((data) => { stripeLlave = data[0].clave_publica; if (data[0].clave_publica == undefined || data[0].clave_publica == []) { showToast("ApiKey no encontrado", "error"); } const stripe = Stripe(stripeLlave); let elements = stripe.elements(); let style = { base: { color: "#32325d", lineHeight: "24px", fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: "antialiased", fontSize: "16px", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#fa755a", iconColor: "#fa755a", }, }; let card = elements.create("card", { style: style }); card.mount("#card-element"); card.addEventListener("change", function (event) { let displayError = document.getElementById("card-errors"); displayError.textContent = event.error ? event.error.message : ""; }); let form = document.getElementById("payment-form"); form.addEventListener("submit", function (event) { event.preventDefault(); let cantidad = document.getElementById("amountUser").value; let currency = document.getElementById("currency").value; let emailUser = document.getElementById("emailUser").value; let descripcion = document.getElementById("description").value; let nameUsuario = document.getElementById("nameUser").value; console.log("PASO 1"); stripe.createToken(card).then(function (result) { if (result.error) { document.getElementById("card-errors").textContent = result.error.message; document.getElementById("btnstripe").removeAttribute("disabled"); } else { stripeTokenHandler(result.token); let datos = []; const formElements = form.querySelectorAll("input, select, textarea"); formElements.forEach((el) => { if (el.name && !el.disabled) { datos.push({ name: el.name, value: el.value }); } }); datos.push({ name: "amount", value: cantidad }); datos.push({ name: "name", value: nameUsuario }); datos.push({ name: "currency", value: currency }); datos.push({ name: "email", value: emailUser }); datos.push({ name: "descripcion", value: descripcion }); datos.push({ name: "urlbase", value: window.location.origin }); datos.push({ name: "apiKey", value: apiKey }); console.log("DATOS ENVIADOS:", datos); const formBody = datos .map((pair) => encodeURIComponent(pair.name) + "=" + encodeURIComponent(pair.value) ) .join("&"); document.getElementById("btnstripe").style.display = "none"; document.getElementById("mensajePago").innerHTML = ` Espere un momento. Estamos procesando su pago. `; fetch("https://gateway.calidadbmasconsulting.com/api/createPayment", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: formBody, }) .then((response) => response.json()) .then((response) => { console.log(response.success); if (response.success) { document.getElementById("mensajePago").innerHTML = ` ✅ Pago realizado con éxito. ID Transacción: ${response.idTransaction} `; card.clear(); } else { document.getElementById("mensajePago").innerHTML = ` ❌ Hubo un error: ${response.error} `; card.clear(); document.getElementById("btnstripe").style.display = "inline-block"; } }) .catch((error) => { console.log(error); document.getElementById("mensajePago").innerHTML = ` ❌ Error de conexión o del servidor. Intente nuevamente. `; card.clear(); document.getElementById("btnstripe").style.display = "inline-block"; }); } }); }); }) .catch((error) => { showToast("Error: ApiKey no encontrado", "error"); }); }); window.abrirModal = function() { const modal = document.getElementById("miModal"); const contenido = document.getElementById("modalContenido"); modal.style.display = "flex"; contenido.classList.remove("animar-salida"); setTimeout(() => contenido.classList.add("animar-entrada"), 10); } window.cerrarModal = function() { const modal = document.getElementById("miModal"); const contenido = document.getElementById("modalContenido"); contenido.classList.remove("animar-entrada"); contenido.classList.add("animar-salida"); setTimeout(() => (modal.style.display = "none"), 300); } // TAMBIÉN hacer asíncrono este DOMContentLoaded document.addEventListener("DOMContentLoaded", async function () { // Esperar a que cargue el env si aún no está cargado if (!apiKey || !imagen_pasarela) { const env = await cargarEnv(); apiKey = env.apiKey_pasarela; imagen_pasarela = env.imagen_pasarela; } const modalHTML = ` `; document.body.insertAdjacentHTML("beforeend", modalHTML); // Crear la URL completa const base64Url = `data:image/webp;base64,${imagen_pasarela}`; // Cambiar solo la imagen del CSS const header = document.querySelector(".modal-header-personalizada"); header.style.backgroundImage = `url('${base64Url}')`; const script = document.createElement('script'); script.src = '../../config.js'; script.type = 'text/javascript'; document.body.appendChild(script); });