fix: the card form opens with the order's document, so the card token and the Mercado Pago payer agree
Some checks failed
Build and deploy / Validate source (push) Successful in 15s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
Some checks failed
Build and deploy / Validate source (push) Successful in 15s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
65f8dd2 made the order's document the payer of every card payment, which
could differ from the document inside the card token and raise refusals.
The card form now opens with the order's CPF or CNPJ (Card Payment Brick
initialization.payer.identification), so both carry it. A valid document
the customer types there instead (someone else's card) is the payer, as
the token says; a placeholder such as 999.999.999-99, or none, gives way
to the order's. The order's document always rides in the payment's
metadata for finance, and the order's name goes as first and last name.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -413,9 +413,8 @@ class PaymentMethod(StrictModel):
|
|||||||
# Up to 3, as Dropstar sells; the card form offers no more.
|
# Up to 3, as Dropstar sells; the card form offers no more.
|
||||||
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
installments: int = Field(default=1, ge=1, le=3, strict=True)
|
||||||
issuer_id: str | None = Field(default=None, max_length=40)
|
issuer_id: str | None = Field(default=None, max_length=40)
|
||||||
# The card form's document. No longer sent nor used: the payer is the
|
# The document in the card form, which opens with the order's: the payer
|
||||||
# order's customer (app/mercadopago.py payer, Marcus 2026-11-18); kept so a
|
# when it is a valid CPF or CNPJ (app/mercadopago.py payer).
|
||||||
# page loaded before the change still pays.
|
|
||||||
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
|
||||||
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from typing import Mapping
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from .adapters import PaymentEvent
|
from .adapters import PaymentEvent
|
||||||
|
from .core.models import cnpj_ok, cpf_ok
|
||||||
|
|
||||||
API = 'https://api.mercadopago.com'
|
API = 'https://api.mercadopago.com'
|
||||||
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
|
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
|
||||||
@@ -41,15 +42,22 @@ PIX_MINUTES = 30
|
|||||||
BRASILIA = timezone(timedelta(hours=-3))
|
BRASILIA = timezone(timedelta(hours=-3))
|
||||||
|
|
||||||
|
|
||||||
def payer(customer):
|
def payer(customer, method=None):
|
||||||
"""Who pays, as Dropstar's finance reconciles it and the invoice is issued
|
"""Who pays, as Dropstar's finance reconciles it and the invoice is issued
|
||||||
(Marcus, 2026-11-18): the customer's own CPF or CNPJ from the order, with
|
(Marcus, 2026-11-18): a real CPF or CNPJ, never a placeholder such as
|
||||||
their name and e-mail, for PIX and card alike, never a placeholder such
|
999.999.999-99, with the order's name and e-mail.
|
||||||
as 999.999.999-99. The card form's document is not the payer: the
|
|
||||||
cardholder's data travel inside the card token."""
|
The card form opens with the order's document already in it (web/
|
||||||
|
checkout.js), so the card token and the payer agree. A valid document
|
||||||
|
the customer typed there instead (someone else's card) is the payer, as
|
||||||
|
the token says; anything else, and PIX, is the order's own."""
|
||||||
document = customer['cnpj']
|
document = customer['cnpj']
|
||||||
who = {'email': customer['mail'],
|
identification = {'type': 'CPF' if len(document) == 11 else 'CNPJ', 'number': document}
|
||||||
'identification': {'type': 'CPF' if len(document) == 11 else 'CNPJ', 'number': document}}
|
typed = ''.join(ch for ch in str((method or {}).get('payer_document') or '') if ch.isdigit())
|
||||||
|
kind = (method or {}).get('payer_document_type')
|
||||||
|
if (kind == 'CPF' and cpf_ok(typed)) or (kind == 'CNPJ' and cnpj_ok(typed)):
|
||||||
|
identification = {'type': kind, 'number': typed}
|
||||||
|
who = {'email': customer['mail'], 'identification': identification}
|
||||||
names = (customer.get('name') or '').split()
|
names = (customer.get('name') or '').split()
|
||||||
if names:
|
if names:
|
||||||
who['first_name'] = names[0]
|
who['first_name'] = names[0]
|
||||||
@@ -92,7 +100,10 @@ class MercadoPagoPayment:
|
|||||||
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
body = {'transaction_amount': float(Decimal(total_cents) / 100),
|
||||||
'description': f'DTF - cotação {quote_id[:8]}',
|
'description': f'DTF - cotação {quote_id[:8]}',
|
||||||
'external_reference': quote_id,
|
'external_reference': quote_id,
|
||||||
'payer': payer(customer)}
|
'payer': payer(customer, method if method['type'] == 'card' else None),
|
||||||
|
# The order's own document, kept on the payment for finance
|
||||||
|
# even when the card's holder is someone else.
|
||||||
|
'metadata': {'documento_pedido': customer['cnpj']}}
|
||||||
if self.notification_url:
|
if self.notification_url:
|
||||||
body['notification_url'] = self.notification_url
|
body['notification_url'] = self.notification_url
|
||||||
expires_at = None
|
expires_at = None
|
||||||
|
|||||||
@@ -166,9 +166,10 @@ class MercadoPagoTests(unittest.TestCase):
|
|||||||
{'type': 'card', 'token': 'tok_def', 'payment_method_id': 'visa'})
|
{'type': 'card', 'token': 'tok_def', 'payment_method_id': 'visa'})
|
||||||
self.assertNotEqual(self.requests[-1].headers['x-idempotency-key'], first_key)
|
self.assertNotEqual(self.requests[-1].headers['x-idempotency-key'], first_key)
|
||||||
self.assertTrue(first_key.startswith('dtf-quote-q-card-'))
|
self.assertTrue(first_key.startswith('dtf-quote-q-card-'))
|
||||||
# 3-D Secure is asked of debit only. The payer is the order's customer,
|
# 3-D Secure is asked of debit only. The payer is a real document
|
||||||
# never the card form's document (Marcus, 2026-11-18): finance
|
# (Marcus, 2026-11-18): a placeholder from the card form (999...) gives
|
||||||
# reconciles by it and the invoice is issued to it.
|
# way to the order's, with the order's name; the order's document is
|
||||||
|
# always kept in the metadata for finance.
|
||||||
self.assertNotIn('three_d_secure_mode', body)
|
self.assertNotIn('three_d_secure_mode', body)
|
||||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
|
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
|
||||||
{'type': 'card', 'token': 'tok_deb', 'payment_method_id': 'debmaster',
|
{'type': 'card', 'token': 'tok_deb', 'payment_method_id': 'debmaster',
|
||||||
@@ -177,9 +178,18 @@ class MercadoPagoTests(unittest.TestCase):
|
|||||||
self.assertEqual(debit['three_d_secure_mode'], 'optional')
|
self.assertEqual(debit['three_d_secure_mode'], 'optional')
|
||||||
self.assertEqual(debit['payer'], {'email': 'a@example.test', 'first_name': 'Maria', 'last_name': 'da Silva',
|
self.assertEqual(debit['payer'], {'email': 'a@example.test', 'first_name': 'Maria', 'last_name': 'da Silva',
|
||||||
'identification': {'type': 'CNPJ', 'number': '11222333000181'}})
|
'identification': {'type': 'CNPJ', 'number': '11222333000181'}})
|
||||||
|
self.assertEqual(debit['metadata'], {'documento_pedido': '11222333000181'})
|
||||||
self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'})
|
self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'})
|
||||||
# An order from before the Site asked the name sends none.
|
# An order from before the Site asked the name sends none.
|
||||||
self.assertNotIn('first_name', body['payer'])
|
self.assertNotIn('first_name', body['payer'])
|
||||||
|
# A valid document typed in the card form (someone else's card) is the
|
||||||
|
# payer, as the card token says; the order's stays in the metadata.
|
||||||
|
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
|
||||||
|
{'type': 'card', 'token': 'tok_other', 'payment_method_id': 'visa',
|
||||||
|
'payer_document_type': 'CPF', 'payer_document': '52998224725'})
|
||||||
|
other = json.loads(self.requests[-1].content)
|
||||||
|
self.assertEqual(other['payer']['identification'], {'type': 'CPF', 'number': '52998224725'})
|
||||||
|
self.assertEqual(other['metadata'], {'documento_pedido': '11222333000181'})
|
||||||
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
|
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
|
||||||
{'type': 'card', 'token': 'tok_iss', 'payment_method_id': 'master', 'issuer_id': '24'})
|
{'type': 'card', 'token': 'tok_iss', 'payment_method_id': 'master', 'issuer_id': '24'})
|
||||||
self.assertNotIn('issuer_id', json.loads(self.requests[-1].content))
|
self.assertNotIn('issuer_id', json.loads(self.requests[-1].content))
|
||||||
|
|||||||
@@ -784,6 +784,14 @@
|
|||||||
});
|
});
|
||||||
return sdkLoading;
|
return sdkLoading;
|
||||||
}
|
}
|
||||||
|
// The document in the card form, which opens with the order's; the server
|
||||||
|
// keeps the order's when this one is not a valid CPF or CNPJ.
|
||||||
|
function cardholder(id) {
|
||||||
|
const number=String(id?.number||'').replace(/\D/g,'');
|
||||||
|
const type=String(id?.type||'').toUpperCase();
|
||||||
|
return ['CPF','CNPJ'].includes(type) && /^[0-9]{11,14}$/.test(number)
|
||||||
|
? {payer_document_type:type, payer_document:number} : {};
|
||||||
|
}
|
||||||
// Each mount of the card form has its own number and its own holder. One
|
// 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,
|
// 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
|
// is stale: Mercado Pago no longer finds its fields, so its callbacks are
|
||||||
@@ -809,7 +817,10 @@
|
|||||||
let brick;
|
let brick;
|
||||||
try {
|
try {
|
||||||
brick=await mp.bricks().create('cardPayment',holder.id,{
|
brick=await mp.bricks().create('cardPayment',holder.id,{
|
||||||
initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail}},
|
// The order's document already in the card form (Marcus, 2026-11-18):
|
||||||
|
// the card token and the payer agree, and finance reconciles by it.
|
||||||
|
initialization:{amount:approved.total_cents/100, payer:{email:approved.customer.mail,
|
||||||
|
identification:{type:approved.customer.cnpj.length===11?'CPF':'CNPJ', number:approved.customer.cnpj}}},
|
||||||
// Credit cards only, in up to 3 installments, as Dropstar decided.
|
// Credit cards only, in up to 3 installments, as Dropstar decided.
|
||||||
customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}},
|
customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}},
|
||||||
// The option above already names the card; the form's own title
|
// The option above already names the card; the form's own title
|
||||||
@@ -827,7 +838,8 @@
|
|||||||
result=await api('/payments/intent',{quote_id:draftId,method:{
|
result=await api('/payments/intent',{quote_id:draftId,method:{
|
||||||
type:'card', token:data.token, payment_method_id:data.payment_method_id,
|
type:'card', token:data.token, payment_method_id:data.payment_method_id,
|
||||||
installments:Number(data.installments)||1,
|
installments:Number(data.installments)||1,
|
||||||
issuer_id:data.issuer_id==null?null:String(data.issuer_id)}});
|
issuer_id:data.issuer_id==null?null:String(data.issuer_id),
|
||||||
|
...cardholder(data.payer?.identification)}});
|
||||||
} catch(error) {
|
} catch(error) {
|
||||||
// Rejecting stops the form's spinner; the reason is shown above it.
|
// 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');
|
message(error.message || 'Não foi possível concluir o pagamento. Tente de novo.','error');
|
||||||
|
|||||||
Reference in New Issue
Block a user