feat: a refused payment says what happened and what to do, in plain Portuguese
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m11s

A refused card showed Mercado Pago's code ("Pagamento recusado pelo Mercado
Pago (cc_rejected_insufficient_amount)"), a request it refused showed its
cause list, and some errors were in English ("Quote is already paid",
"Payment provider unavailable; try again"). Each now becomes one sentence:
"O cartão não tem limite suficiente para este valor. Use outro cartão ou
pague com PIX." The codes still go to the log and, on the Kanban's "Cartão
recusado" badge, beside the same sentence. A form check the customer cannot
read is replaced by a general one, and every error a customer or operator
can meet in the quote, upload, account and artwork routes is in Portuguese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-06 15:54:14 -03:00
parent 172544b173
commit 959ed37b15
12 changed files with 190 additions and 47 deletions

View File

@@ -11,7 +11,7 @@ import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments
from .. import payment_messages as messages, payments
from ..core import db
from ..core.auth import audit, client_ip, owner, rate_limit
from ..core.models import PaymentIntent
@@ -101,9 +101,9 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
try:
quote = payments.approved_quote(c, body.quote_id, session_id)
except payments.PaymentRefused as refusal:
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
raise HTTPException(409, 'Quote is already paid')
raise HTTPException(409, 'Este pedido já foi pago.')
# Never charge for files that are gone: an unpaid cart's files are
# removed after a while. A payment under way keeps them a day longer,
# time enough for the provider's notice to become the order.
@@ -124,7 +124,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
AND NOT (jsonb_typeof(response->'challenge')='object'
AND created_at < now() - make_interval(mins => %s))))''',
(body.quote_id, CHALLENGE_MINUTES)).fetchone():
raise HTTPException(409, 'A payment for this quote is already approved or in review')
raise HTTPException(409, 'Já existe um pagamento aprovado ou em análise para este pedido. '
'Aguarde a confirmação nesta página.')
method = body.method.model_dump()
if body.method.type == 'pix':
# One open PIX per quote: the same code until it expires, and a new
@@ -144,8 +145,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
try:
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
quote['approved']['customer'], method)
except ValueError as exc:
raise HTTPException(422, str(exc))
except ValueError:
raise HTTPException(422, 'Esta forma de pagamento não é aceita. Pague com cartão de crédito ou PIX.')
except httpx.HTTPStatusError as exc:
# Mercado Pago's own reason (status, message and cause codes) goes to
# the log; it never contains card data, only what was refused.
@@ -153,11 +154,18 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
audit('payment_intent_refused', quote=str(body.quote_id), method=body.method.type,
status=exc.response.status_code, reason=reason)
if exc.response.status_code < 500:
raise HTTPException(422, f'O Mercado Pago recusou o pagamento: {reason}')
raise HTTPException(502, 'Payment provider unavailable; try again')
try:
data = exc.response.json()
except ValueError:
data = {}
raise HTTPException(422, messages.refusal(data))
raise HTTPException(502, messages.UNAVAILABLE)
except Exception as exc:
audit('payment_intent_failed', quote=str(body.quote_id), error=type(exc).__name__)
raise HTTPException(502, 'Payment provider unavailable; try again')
raise HTTPException(502, messages.UNAVAILABLE)
if created.get('status') == 'rejected':
# What to tell the customer; the code stays in status_detail for the team.
created['message'] = messages.rejection(created.get('status_detail'))
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',