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>
This commit is contained in:
committed by
GitHub
parent
51abc66eb3
commit
838e5dd25d
+26
-1
@@ -1832,12 +1832,37 @@ def confirmar_setup_intent(request: HttpRequest):
|
|||||||
customer_id = _get_or_create_stripe_customer(request.user)
|
customer_id = _get_or_create_stripe_customer(request.user)
|
||||||
|
|
||||||
# Attach the PaymentMethod to the customer
|
# 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)
|
pm = stripe.PaymentMethod.retrieve(payment_method_id)
|
||||||
card = pm.card
|
card = pm.card
|
||||||
label = f"{card.brand.capitalize()} •••• {card.last4} (exp. {card.exp_month:02d}/{card.exp_year})"
|
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()
|
has_existing = SavedPaymentMethod.objects.filter(user=request.user).exists()
|
||||||
saved = SavedPaymentMethod.objects.create(
|
saved = SavedPaymentMethod.objects.create(
|
||||||
user=request.user,
|
user=request.user,
|
||||||
|
|||||||
Reference in New Issue
Block a user