From 5d9a78b63ccb323c878f7f09c985f2f4a1213db3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 17 Nov 2026 10:11:23 -0300 Subject: [PATCH] fix: a card form still mounting when the customer picks PIX is dropped quietly (DTF-WEB-T) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clicking PIX while Mercado Pago's card form was still mounting removed its holder; the mount went on, found no fields and its onError showed "Erro no formulário do cartão". Each mount now has its own number and holder id; a stale mount's callbacks are ignored and the late form is unmounted when it arrives. A mount that fails on the current form says so in red. Co-Authored-By: Claude Opus 5.5 (1M context) --- web/checkout.js | 103 +++++++++++++++++++++++++++--------------------- 1 file changed, 58 insertions(+), 45 deletions(-) diff --git a/web/checkout.js b/web/checkout.js index b06c7b4..b831c6b 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -772,64 +772,77 @@ return ['CPF','CNPJ'].includes(type) && /^[0-9]{11,14}$/.test(number) ? {payer_document_type:type, payer_document:number} : {}; } - let cardBrick=null; + // Each mount of the card form has its own number and its own holder. One + // still mounting when the customer switched to PIX, or the page re-rendered, + // is stale: Mercado Pago no longer finds its fields, so its callbacks are + // ignored and it is taken down once it arrives (Sentry DTF-WEB-T). + let cardBrick=null, cardMount=0; function unmountCard() { + cardMount++; if (cardBrick) { try { cardBrick.unmount(); } catch(_) {} cardBrick=null; } } async function showCard(approved, into, version) { + unmountCard(); + const mount=cardMount; const holder=node('div'); - holder.id='cardPaymentBrick'; + holder.id='cardPaymentBrick-'+mount; + const live=()=>mount===cardMount && holder.isConnected && version===refreshVersion; const espera=node('div',null,'skel skelBloco'); into.append(espera,holder); try { await loadMercadoPago(); } catch(error) { espera.remove(); message(error.message,'error'); return; } const session=await ready; - // The customer may have switched to PIX, or the page re-rendered, meanwhile. - if (!holder.isConnected || version!==refreshVersion) return; - unmountCard(); + if (!live()) return; const mp=new window.MercadoPago(session.payment_public_key,{locale:'pt-BR'}); - cardBrick=await mp.bricks().create('cardPayment','cardPaymentBrick',{ - initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}}, - // Credit cards only, in up to 3 installments, as Dropstar decided. - customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}}, - // The option above already names the card; the form's own title - // ("crédito ou débito") would contradict it. - visual:{hideFormTitle:true, - style:{customVariables:{baseColor:'#FFA81A',buttonTextColor:'#03060B'}}}}, - callbacks:{ - onReady:()=>{ espera.remove(); }, - onError:error=>{ console.error(error); message('Erro no formulário do cartão. Confira os dados e tente de novo.','error'); }, - onSubmit:async data=>{ - if (!cartOk()) { await refresh(); throw new Error('cart changed'); } - message(''); - let result; - try { - result=await api('/payments/intent',{quote_id:draftId,method:{ - type:'card', token:data.token, payment_method_id:data.payment_method_id, - installments:Number(data.installments)||1, - issuer_id:data.issuer_id==null?null:String(data.issuer_id), - ...cardholder(data.payer?.identification)}}); - } catch(error) { - // Rejecting stops the form's spinner; the reason is shown above it. - message(error.message || 'Não foi possível concluir o pagamento. Tente de novo.','error'); - status.scrollIntoView({behavior:'smooth',block:'center'}); - throw error; - } - if (result.challenge) { showChallenge(result.challenge, into); waitForOrder(); return; } - if (result.status==='approved' || result.status==='pending') { - unmountCard(); - into.replaceChildren(node('p',result.status==='approved' - ? 'Pagamento aprovado. Confirmando seu pedido…' - : 'Pagamento em análise pelo Mercado Pago. Esta página atualiza assim que ele for confirmado.','pagNota')); - waitForOrder(); - } else { - message(result.message||'O pagamento foi recusado. Confira os dados ou use outro cartão ou pague com PIX.','error'); - throw new Error('rejected'); + let brick; + try { + brick=await mp.bricks().create('cardPayment',holder.id,{ + initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}}, + // Credit cards only, in up to 3 installments, as Dropstar decided. + customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}}, + // The option above already names the card; the form's own title + // ("crédito ou débito") would contradict it. + visual:{hideFormTitle:true, + style:{customVariables:{baseColor:'#FFA81A',buttonTextColor:'#03060B'}}}}, + callbacks:{ + onReady:()=>{ if (live()) espera.remove(); }, + onError:error=>{ if (!live()) return; console.error(error); message('Erro no formulário do cartão. Confira os dados e tente de novo.','error'); }, + onSubmit:async data=>{ + if (!cartOk()) { await refresh(); throw new Error('cart changed'); } + message(''); + let result; + try { + result=await api('/payments/intent',{quote_id:draftId,method:{ + type:'card', token:data.token, payment_method_id:data.payment_method_id, + installments:Number(data.installments)||1, + issuer_id:data.issuer_id==null?null:String(data.issuer_id), + ...cardholder(data.payer?.identification)}}); + } catch(error) { + // Rejecting stops the form's spinner; the reason is shown above it. + message(error.message || 'Não foi possível concluir o pagamento. Tente de novo.','error'); + status.scrollIntoView({behavior:'smooth',block:'center'}); + throw error; + } + if (result.challenge) { showChallenge(result.challenge, into); waitForOrder(); return; } + if (result.status==='approved' || result.status==='pending') { + unmountCard(); + into.replaceChildren(node('p',result.status==='approved' + ? 'Pagamento aprovado. Confirmando seu pedido…' + : 'Pagamento em análise pelo Mercado Pago. Esta página atualiza assim que ele for confirmado.','pagNota')); + waitForOrder(); + } else { + message(result.message||'O pagamento foi recusado. Confira os dados ou use outro cartão ou pague com PIX.','error'); + throw new Error('rejected'); + } } } - } - }); - if (!holder.isConnected || version!==refreshVersion) unmountCard(); + }); + } catch(error) { + if (!live()) return; + espera.remove(); message('Não foi possível abrir o formulário do cartão. Recarregue a página ou pague com PIX.','error'); return; + } + if (!live()) { try { brick.unmount(); } catch(_) {} return; } + cardBrick=brick; } const quoteFromPortal=new URLSearchParams(location.search).get('quote'); if(quoteFromPortal && /^[0-9a-f-]{36}$/.test(quoteFromPortal)){