diff --git a/app/core/models.py b/app/core/models.py index a3308eb..485371c 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -413,9 +413,8 @@ class PaymentMethod(StrictModel): # Up to 3, as Dropstar sells; the card form offers no more. installments: int = Field(default=1, ge=1, le=3, strict=True) issuer_id: str | None = Field(default=None, max_length=40) - # The card form's document. No longer sent nor used: the payer is the - # order's customer (app/mercadopago.py payer, Marcus 2026-11-18); kept so a - # page loaded before the change still pays. + # The document in the card form, which opens with the order's: the payer + # when it is a valid CPF or CNPJ (app/mercadopago.py payer). payer_document_type: Literal['CPF', 'CNPJ'] | None = None payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$') diff --git a/app/mercadopago.py b/app/mercadopago.py index 500e37f..40829c3 100644 --- a/app/mercadopago.py +++ b/app/mercadopago.py @@ -28,6 +28,7 @@ from typing import Mapping import httpx from .adapters import PaymentEvent +from .core.models import cnpj_ok, cpf_ok API = 'https://api.mercadopago.com' # 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)) -def payer(customer): +def payer(customer, method=None): """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 - their name and e-mail, for PIX and card alike, never a placeholder such - as 999.999.999-99. The card form's document is not the payer: the - cardholder's data travel inside the card token.""" + (Marcus, 2026-11-18): a real CPF or CNPJ, never a placeholder such as + 999.999.999-99, with the order's name and e-mail. + + 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'] - 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() if names: who['first_name'] = names[0] @@ -92,7 +100,10 @@ class MercadoPagoPayment: body = {'transaction_amount': float(Decimal(total_cents) / 100), 'description': f'DTF - cotação {quote_id[:8]}', '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: body['notification_url'] = self.notification_url expires_at = None diff --git a/tests/test_mercadopago.py b/tests/test_mercadopago.py index 7264f05..938535a 100644 --- a/tests/test_mercadopago.py +++ b/tests/test_mercadopago.py @@ -166,9 +166,10 @@ class MercadoPagoTests(unittest.TestCase): {'type': 'card', 'token': 'tok_def', 'payment_method_id': 'visa'}) self.assertNotEqual(self.requests[-1].headers['x-idempotency-key'], first_key) self.assertTrue(first_key.startswith('dtf-quote-q-card-')) - # 3-D Secure is asked of debit only. The payer is the order's customer, - # never the card form's document (Marcus, 2026-11-18): finance - # reconciles by it and the invoice is issued to it. + # 3-D Secure is asked of debit only. The payer is a real document + # (Marcus, 2026-11-18): a placeholder from the card form (999...) gives + # 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.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'}, {'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['payer'], {'email': 'a@example.test', 'first_name': 'Maria', 'last_name': 'da Silva', 'identification': {'type': 'CNPJ', 'number': '11222333000181'}}) + self.assertEqual(debit['metadata'], {'documento_pedido': '11222333000181'}) self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'}) # An order from before the Site asked the name sends none. 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'}, {'type': 'card', 'token': 'tok_iss', 'payment_method_id': 'master', 'issuer_id': '24'}) self.assertNotIn('issuer_id', json.loads(self.requests[-1].content)) diff --git a/web/checkout.js b/web/checkout.js index 83554bc..efea981 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -784,6 +784,14 @@ }); 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 // 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 @@ -809,7 +817,10 @@ let brick; try { 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. customization:{paymentMethods:{maxInstallments:3,types:{excluded:['debit_card']}}, // 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:{ 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)}}); + 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');