From 838e5dd25d2bc6b6114e26be77d52e8eb0948447 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 10 Apr 2026 07:49:01 +0000 Subject: [PATCH] fix: handle already-attached Stripe payment method gracefully Agent-Logs-Url: https://github.com/dsaub/proyecto-final/sessions/9a4f463c-0ad0-4552-8b3f-85b3373203b5 Co-authored-by: dsaub <54474838+dsaub@users.noreply.github.com> --- tienda/views.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/tienda/views.py b/tienda/views.py index c6a0a22..cfeeea4 100644 --- a/tienda/views.py +++ b/tienda/views.py @@ -1832,12 +1832,37 @@ def confirmar_setup_intent(request: HttpRequest): customer_id = _get_or_create_stripe_customer(request.user) # Attach the PaymentMethod to the customer - stripe.PaymentMethod.attach(payment_method_id, customer=customer_id) + try: + stripe.PaymentMethod.attach(payment_method_id, customer=customer_id) + except stripe.error.InvalidRequestError as attach_err: + # The payment method may already be attached to a customer + pm_check = stripe.PaymentMethod.retrieve(payment_method_id) + if pm_check.get("customer") == customer_id: + # Already attached to this same customer – continue normally + pass + else: + logger.warning( + "CONFIRMAR_SETUP_INTENT_ALREADY_ATTACHED user_id=%s pm=%s error=%s", + request.user.id, payment_method_id, str(attach_err), + ) + return JsonResponse( + {"error": "Este método de pago ya está asociado a otra cuenta. " + "Por favor, usa una tarjeta diferente."}, + status=400, + ) pm = stripe.PaymentMethod.retrieve(payment_method_id) card = pm.card label = f"{card.brand.capitalize()} •••• {card.last4} (exp. {card.exp_month:02d}/{card.exp_year})" + # Avoid saving duplicates in our database + existing = SavedPaymentMethod.objects.filter( + user=request.user, + stripe_payment_method_id=payment_method_id, + ).first() + if existing: + return JsonResponse({"success": True, "label": existing.label, "id": existing.id}) + has_existing = SavedPaymentMethod.objects.filter(user=request.user).exists() saved = SavedPaymentMethod.objects.create( user=request.user,