function addScript(url, callback) { var script = document.createElement('script'); script.type = 'application/javascript'; script.src = url; // adiciona um listener de evento para executar o callback após o script ser carregado if (typeof callback === 'function') { script.addEventListener('load', callback, false); } document.body.appendChild(script); } function addStyle(url, callback) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = url; if (typeof callback === 'function') { link.addEventListener('load', callback, false); } document.head.appendChild(link); } function addStyleInLine(styleText) { var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = styleText; if (typeof callback === 'function') { style.addEventListener('load', callback, false); } document.head.appendChild(style); } //SWEETALERT2 addStyle("https://cdn.jsdelivr.net/npm/@sweetalert2/theme-default@5/default.css"); addStyleInLine(` .swal2-popup { border-radius: 31px !important; font-family: "Urbanist",Sans-serif !important; color: #000 !important; } .swal2-popup button[type="button"] { border-radius: 21px !important; background-color: #00425A !important; } `); addStyleInLine(` .swal2-input { border-radius: 30px !important; } .swal2-input.token { width: 45px; text-align: center; margin-right: 5px; margin-left: 13px; border: solid 1px #b4acac; } .center { display: flex; justify-content: center; align-items: center; } .swal2-input.reset-password { width: 80%; border: solid 1px #b4acac; } .swal2-input::placeholder { color: #484848; } .hints{ margin-top: 10px; display: none; text-align: left; color: #b92727; } .hints_ul{ }`) const urlBase = 'https://apiabrinqfoundation.fadc.org.br/api'; const cielo = { consultaCartao(id) { return new Promise((resolve, reject) => { fetch(urlBase + '/Cielo/ConsultaBIN?nrCartao=' + id) .then(response => response.json()) .then(data => resolve(data)) .catch(error => reject(error)); }); }, // MESMA VALIDAÇÃO UTILIZADA NA FICHA DE DOAÇÃO (REGRA DO MOD10 - Algoritmo de Luhn) ValidarNumeroCartao(numCartao) { // Validação de número de cartão com base no Algoritmo de Luhn var a = numCartao.replaceAll(' ', ''); // a = armazenamento de número removendo os espaços var b = a.length; // b = tamanho de texto var c = 0; // c = soma var dobrarNumero = false; for (var d = b - 1; d >= 0; d--) { var e = parseInt(a.charAt(d)); if (dobrarNumero) { if ((e *= 2) > 9) { e -= 9; } } c += e; dobrarNumero = !dobrarNumero; } return (c % 10) == 0; } };//IMPORTS addScript("https://cdnjs.cloudflare.com/ajax/libs/vanilla-masker/1.2.0/vanilla-masker.min.js", function () { aplicarMascarasFormulario(); }); addScript("https://cdn.jsdelivr.net/npm/sweetalert2@11.1.2/dist/sweetalert2.min.js", function () { init(); }); addStyleInLine(` .input_invalido { border : 1px solid red !important } `); //MAPEAMENTO DE CAMPOS var mapeamento = { nome: document.getElementById("name"), sobreNome: document.getElementById("last-name"), numeroCartao: document.getElementById("card-number"), dataValidade: document.getElementById("expiration"), cvv: document.getElementById("cvv"), email: document.getElementById("email"), btnEnviar: document.getElementById("btnSend"), inputOutroValor: document.getElementById("inputOtherValue"), }; function init() { alteraComportamentoBtnSubmit(); } function aplicarMascarasFormulario() { VMasker(mapeamento.numeroCartao).maskPattern("9999999999999999"); //VMasker(mapeamento.numeroCartao).maskPattern("9999 9999 9999 9999"); VMasker(mapeamento.dataValidade).maskPattern("99/99"); VMasker(mapeamento.cvv).maskPattern("9999"); } function alteraComportamentoBtnSubmit() { _x("//div[contains(@class, 'destacar')]").forEach(element => element.onclick = function () { mapeamento.inputOutroValor.value = ""; }); mapeamento.btnEnviar.onclick = function login(event) { //Cancela comportamento padrão do botão event.preventDefault(); submit(); } mapeamento.numeroCartao.oninput = function () { if (mapeamento.numeroCartao.value.length < 9) { mapeamento.bandeira = null; //DESELECIONA BANDEIRA ATUAL _x("//img[contains(@alt, 'Bandeira')]").forEach(function (element) { element.setAttribute("class", "") }); //APLICA MASCARA DEFAULT VMasker(mapeamento.numeroCartao).maskPattern("9999999999999999"); return; }; //Caso já tem uma bandeira selecionada, não faz nada if (mapeamento.bandeira != null) return; consultaBin(mapeamento.numeroCartao.value).then(function (resultado) { //LIMPA BANDEIRA SELECIONADA mapeamento.bandeira = null; switch (resultado) { case 'AMEX': mapeamento.bandeira = "Amex"; _x("//img[contains(@alt, 'Bandeira') and contains(@data-bandeira, 'amex')]")[0].setAttribute("class", "active"); break; case 'VISA': mapeamento.bandeira = "Visa"; jQuery(_x("//img[contains(@alt, 'Bandeira') and contains(@data-bandeira, 'visa')]"))[0].setAttribute("class", "active"); break; case 'DISCOVER': mapeamento.bandeira = "Discover"; jQuery(_x("//img[contains(@alt, 'Bandeira') and contains(@data-bandeira, 'discover')]"))[0].setAttribute("class", "active"); break; case 'MASTERCARD': mapeamento.bandeira = "Master"; jQuery(_x("//img[contains(@alt, 'Bandeira') and contains(@data-bandeira, 'mastercard')]"))[0].setAttribute("class", "active"); break; default: break; } switch (resultado) { case 'AMEX': VMasker(mapeamento.numeroCartao).maskPattern("9999 999999 99999"); break; case 'VISA': case 'DISCOVER': case 'MASTERCARD': VMasker(mapeamento.numeroCartao).maskPattern("9999 9999 9999 9999"); break; } }); } mapeamento.inputOutroValor.onchange = function () { document.getElementById('containerOther').className += ' destacada'; } } function submit() { //REMOVE BORTAS INPUTS INVALIDOS jQuery(".input_invalido").each(function () { // Inside this function, "this" refers to the current DOM element in the iteration jQuery(this).removeClass("input_invalido"); }); var totalErro = 0; var mensagemErro = ""; if (!isValidDate(mapeamento.dataValidade.value)) { mapeamento.dataValidade.setAttribute("class", "input_invalido"); mensagemErro = "Enter a valid expiration date"; totalErro += 1; } if (mapeamento.nome.value.length < 2) { mapeamento.nome.setAttribute("class", "input_invalido"); mensagemErro += "
Enter a valid name"; totalErro += 1; } if (mapeamento.sobreNome.value.length < 2) { mapeamento.sobreNome.setAttribute("class", "input_invalido"); mensagemErro += "
Enter a valid lastname"; totalErro += 1; } if (mapeamento.numeroCartao.value.length < 6) { mapeamento.numeroCartao.setAttribute("class", "input_invalido"); mensagemErro += "
Enter a valid card number"; totalErro += 1; } if (mapeamento.cvv.value.length < 4) { mapeamento.cvv.setAttribute("class", "input_invalido"); mensagemErro += "
Enter a valid cvv"; totalErro += 1; } if (!isValidEmail(mapeamento.email.value)) { mapeamento.email.setAttribute("class", "input_invalido"); mensagemErro += "
Enter a valid e-mail"; totalErro += 1; } var xpathValorPredefinido = "//div[contains(@class, 'destacada')]//h3[contains(@class, 'elementor-icon-box-title')]//span"; var xpathInputValorPersonalizado = "//div[contains(@class, 'destacada')]//input"; //VALOR SELECIONADO var hasInputSelecionado = jQuery(_x(xpathInputValorPersonalizado)).length == 1; var hasValorSelecionado = jQuery(_x(xpathValorPredefinido)).length == 1; var valorSelecionado = null; if (!hasInputSelecionado && !hasValorSelecionado) { //mapeamento.email.setAttribute("class", "input_invalido"); mensagemErro += "
Select a donation amount"; totalErro += 1; } //Obter valor do input if (hasInputSelecionado) { valorSelecionado = mapeamento.inputOutroValor.value.trim(); if (valorSelecionado == '' || valorSelecionado == undefined) { mensagemErro += "
Select a donation amount"; totalErro += 1; } } else if (_x(xpathValorPredefinido)[0] != undefined) { valorSelecionado = jQuery(_x(xpathValorPredefinido))[0].innerText.replace('$', ''); } if (parseInt(valorSelecionado) < 6) { mensagemErro += "
A minimum of $6 is required."; totalErro += 1; } if (mapeamento.bandeira === null || mapeamento.length <= 0) { mensagemErro += "
The selected card brand is not valid"; totalErro += 1; } if (totalErro >= 1) { //Swal.fire(mensagemErro, "", "warning"); Swal.fire({ title: 'Please follow the instructions to continue:', icon: 'warning', html: '
' + mensagemErro + '
', confirmButtonText: 'Confirm', }) return; } //MONTA OBJETO DO POST var dados = { Valor: valorSelecionado, Nome: mapeamento.nome.value, SobreNome: mapeamento.sobreNome.value, NumeroCartao: mapeamento.numeroCartao.value, DataValidade: mapeamento.dataValidade.value, Cvv: mapeamento.cvv.value, Email: mapeamento.email.value, Bandeira: mapeamento.bandeira, } showLoading(); //ENVIA DADOS return fetch(urlBase + '/DoacaoUnica/Doacao', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(dados) }) .then(response => response.json()) .then(data => { hideLoading(); if (data != null && data.mensagem) { Swal.fire(data.mensagem) .then((result) => { if (result.isConfirmed) { if (data.success === true) { //LIMPA CAMPOS mapeamento.inputOutroValor.value = ''; mapeamento.nome.value = ''; mapeamento.sobreNome.value = ''; mapeamento.numeroCartao.value = ''; mapeamento.dataValidade.value = ''; mapeamento.cvv.value = ''; mapeamento.email.value = ''; mapeamento.bandeira = null; _x("//img[contains(@alt, 'Bandeira')]").forEach(function (element) { element.setAttribute("class", "") }); } }; }); return; } else { //Ocorreu um problema ao concluir a doação, por favor tente novamente Swal.fire("There was a problem completing the donation, please try again"); return; } }) .catch(error => { console.error('Erro:', error); hideLoading(); ////Ocorreu um problema ao concluir a doação, por favor tente novamente Swal.fire("There was a problem completing the donation, please try again"); return; }); } function consultaBin(cardNumber) { return new Promise(function (resolve, reject) { if (cardNumber.length < 9) { resolve(''); return; } var nrCartaoIsValid = cielo.ValidarNumeroCartao(cardNumber); if (!nrCartaoIsValid) { if (cardNumber.length >= 19) Swal.fire("Invalid card number"); resolve(''); return; } cielo.consultaCartao(cardNumber) .then(data => { hideLoading(); // Validar resposta if (data.success) { //angular.element(document.querySelector('body')).scope().mapeamento.cc_bandeira = data.model.provider; resolve(data.model.provider); return; } else if (data.message) { //angular.element(document.querySelector('body')).scope().mapeamento.cc_bandeira = ''; Swal.fire(data.message); resolve(''); return; } }) .catch(error => { console.log(error); reject(''); return; }); }); } function mudarEstiloDaBorda(inputElement) { if (inputElement) { inputElement.style.border = "1px solid red"; } } //FUNÇÃO PARA VALIDAR SE A DATA DE EXPIRAÇÃO DO CARTÃO É UMA DATA VÁLIDA function isValidDate(text) { var listDate = text.split("/"); var mes = listDate[0]; var ano = listDate[1]; var validDate = new Date("20" + ano + "/" + mes + "/01"); if (validDate == "Invalid Date") { return false; } else { return true; } //// Check if the text has the correct length and format "DD/MM" //if (text.length !== 5 || text.charAt(2) !== '/') { // return false; //} //// Extract day and month parts from the text //const day = parseInt(text.substring(0, 2), 10); //const month = parseInt(text.substring(3, 5), 10); //// Check if day and month are valid numbers //if (isNaN(day) || isNaN(month)) { // return false; //} //// Check if day and month are within the valid ranges //const isValidDay = day >= 1 && day <= 31; //const isValidMonth = month >= 1 && month <= 12; //return isValidDay && isValidMonth; } function isValidEmail(email) { // Expressão regular para validar o formato do e-mail const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Testa o e-mail com a expressão regular e retorna true se for válido return emailRegex.test(email); } //FUNÇÃO PARA EXECUTAR O XPATH function _x(STR_XPATH) { var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null); var xnodes = []; var xres; while (xres = xresult.iterateNext()) { xnodes.push(xres); } return xnodes; } function showLoading() { Swal.fire({ title: 'Please wait!', html: 'Loading...', allowOutsideClick: false, showConfirmButton: false, onBeforeOpen: () => { Swal.showLoading() }, }); } function hideLoading() { swal.close(); }