Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add fixes for StripePlugin (#14690)

Maciej Korycinski8477443f2ac0
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index 2f53505f49..26b0c1cac8 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -2,13 +2,17 @@ import json
from decimal import Decimal
from unittest.mock import Mock, patch
+import before_after
import pytest
from django.core.exceptions import ValidationError
from django.utils import timezone
from stripe.stripe_object import StripeObject
from .....checkout.complete_checkout import complete_checkout
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....order.actions import order_charged, order_refunded, order_voided
+from .....plugins.manager import get_plugins_manager
+from .....tests.utils import flush_post_commit_hooks
from .... import ChargeStatus, TransactionKind
from ....utils import price_to_minor_unit
from ..consts import (
@@ -1378,29 +1382,35 @@ def test_finalize_checkout_not_created_order_payment_refund(
@patch("saleor.payment.gateway.refund")
-def test_finalize_checkout_not_created_checkout_variant_deleted_order_payment_refund(
+def test_finalize_checkout_not_created_checkout_variant_unavailable_order_refund(
refund_mock,
stripe_plugin,
channel_USD,
payment_stripe_for_checkout,
stripe_payment_intent,
):
+ # given
stripe_plugin()
checkout = payment_stripe_for_checkout.checkout
- checkout.lines.first().delete()
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
checkout.price_expiration = timezone.now()
checkout.save(update_fields=["price_expiration"])
- _finalize_checkout(
- checkout,
- payment_stripe_for_checkout,
- stripe_payment_intent,
- TransactionKind.CAPTURE,
- payment_stripe_for_checkout.total,
- payment_stripe_for_checkout.currency,
- )
+ # when
+ with pytest.raises(ValidationError):
+ _finalize_checkout(
+ checkout,
+ payment_stripe_for_checkout,
+ stripe_payment_intent,
+ TransactionKind.CAPTURE,
+ payment_stripe_for_checkout.total,
+ payment_stripe_for_checkout.currency,
+ )
+ # then
payment_stripe_for_checkout.refresh_from_db()
assert not payment_stripe_for_checkout.order
@@ -1437,29 +1447,35 @@ def test_finalize_checkout_not_created_order_payment_void(
@patch("saleor.payment.gateway.void")
-def test_finalize_checkout_not_created_checkout_variant_deleted_order_payment_void(
+def test_finalize_checkout_not_created_checkout_variant_unavailable_order_payment_void(
void_mock,
stripe_plugin,
channel_USD,
payment_stripe_for_checkout,
stripe_payment_intent,
):
+ # given
stripe_plugin()
checkout = payment_stripe_for_checkout.checkout
- checkout.lines.first().delete()
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
checkout.price_expiration = timezone.now()
checkout.save(update_fields=["price_expiration"])
- _finalize_checkout(
- checkout,
- payment_stripe_for_checkout,
- stripe_payment_intent,
- TransactionKind.AUTH,
- payment_stripe_for_checkout.total,
- payment_stripe_for_checkout.currency,
- )
+ # when
+ with pytest.raises(ValidationError):
+ _finalize_checkout(
+ checkout,
+ payment_stripe_for_checkout,
+ stripe_payment_intent,
+ TransactionKind.AUTH,
+ payment_stripe_for_checkout.total,
+ payment_stripe_for_checkout.currency,
+ )
+ # then
payment_stripe_for_checkout.refresh_from_db()
assert not payment_stripe_for_checkout.order
@@ -1495,3 +1511,78 @@ def test_update_payment_method_details_from_intent_payment_info_exists(
assert payment.cc_exp_year == 2030
assert payment.cc_exp_month == 3
assert payment.payment_method_type == "card"
+
+
+@patch("saleor.payment.gateways.stripe.plugin.retrieve_payment_intent")
+@patch(
+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout
+)
+@patch("saleor.payment.gateways.stripe.webhooks.update_payment_method")
+def test_handle_successful_payment_intent_for_checkout_when_already_processing_checkout(
+ _wrapped_update_payment_method,
+ wrapped_checkout_complete,
+ mocked_retrieve_payment_intent,
+ payment_stripe_for_checkout,
+ checkout_with_items,
+ stripe_plugin,
+ channel_USD,
+):
+ # given
+ plugin = stripe_plugin()
+ manager = get_plugins_manager()
+ payment = payment_stripe_for_checkout
+ payment.to_confirm = True
+ payment.save()
+ payment.transactions.create(
+ is_success=True,
+ action_required=True,
+ kind=TransactionKind.ACTION_TO_CONFIRM,
+ amount=payment.total,
+ currency=payment.currency,
+ token="ABC",
+ gateway_response={},
+ )
+ payment_intent = StripeObject(id="ABC", last_response={})
+ payment_intent["amount_received"] = price_to_minor_unit(
+ payment.total, payment.currency
+ )
+ payment_intent["setup_future_usage"] = None
+ payment_intent["currency"] = payment.currency
+ payment_intent["amount"] = payment.total * 100
+ payment_intent["status"] = SUCCESS_STATUS
+ payment_intent["payment_method"] = StripeObject()
+ mocked_retrieve_payment_intent.return_value = (payment_intent, None)
+
+ lines_info, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines_info, manager)
+
+ # when
+ def call_webhook_notification(*args, **kwargs):
+ flush_post_commit_hooks()
+ handle_successful_payment_intent(
+ payment_intent, plugin.config, channel_USD.slug
+ )
+
+ with before_after.after(
+ "saleor.checkout.complete_checkout._process_payment",
+ call_webhook_notification,
+ ):
+ complete_checkout(
+ manager,
+ checkout_info,
+ lines_info,
+ {},
+ False,
+ None,
+ None,
+ )
+
+ # then
+ payment.refresh_from_db()
+ assert payment.captured_amount == payment.total
+
+ assert wrapped_checkout_complete.called
+ assert payment.checkout_id is None
+ assert payment.order
+ transaction = payment.transactions.get(kind=TransactionKind.CAPTURE)
+ assert transaction.token == payment_intent.id
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 691d38ed07..2dcbe3c889 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -1,5 +1,5 @@
import logging
-from typing import Optional
+from typing import Optional, cast
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
@@ -20,7 +20,7 @@ from ....plugins.manager import get_plugins_manager
from ... import ChargeStatus, TransactionKind
from ...gateway import payment_refund_or_void
from ...interface import GatewayConfig, GatewayResponse
-from ...models import Payment
+from ...models import Payment, Transaction
from ...utils import (
create_transaction,
gateway_postprocess,
@@ -119,16 +119,14 @@ def _channel_slug_is_different_from_payment_channel_slug(
) # pragma: no cover
-def _get_payment(payment_intent_id: str) -> Optional[Payment]:
- return (
- Payment.objects.prefetch_related(
- Prefetch("checkout", queryset=Checkout.objects.select_related("channel")),
- Prefetch("order", queryset=Order.objects.select_related("channel")),
- )
- .select_for_update(of=("self",))
- .filter(transactions__token=payment_intent_id)
- .first()
+def _get_payment(payment_intent_id: str, with_lock=True) -> Optional[Payment]:
+ qs = Payment.objects.prefetch_related(
+ Prefetch("checkout", queryset=Checkout.objects.select_related("channel")),
+ Prefetch("order", queryset=Order.objects.select_related("channel")),
)
+ if with_lock:
+ qs = qs.select_for_update(of=("self",))
+ return qs.filter(transactions__token=payment_intent_id).first()
def _get_checkout(payment_id: int) -> Optional[Checkout]:
@@ -160,24 +158,35 @@ def _finalize_checkout(
psp_reference=payment_intent.id,
)
- transaction = create_transaction(
- payment,
- kind=kind,
- payment_information=None,
+ transaction = Transaction.objects.filter(
+ payment_id=payment.id,
+ is_success=True,
action_required=False,
- gateway_response=gateway_response,
- )
+ kind=kind,
+ ).first()
- # To avoid zombie payments we have to update payment `charge_status` without
- # changing `to_confirm` flag. In case when order cannot be created then
- # payment will be refunded.
- update_payment_charge_status(payment, transaction)
- payment.refresh_from_db()
- checkout.refresh_from_db()
+ # Ensure that the transaction does not exist before creating it. The transaction
+ # can be created by the `checkoutComplete` logic, which can be executed
+ # simultaneously with this function.
+ if not transaction:
+ transaction = create_transaction(
+ payment,
+ kind=kind,
+ payment_information=None,
+ action_required=False,
+ gateway_response=gateway_response,
+ )
+ # To avoid zombie payments we have to update payment `charge_status` without
+ # changing `to_confirm` flag. In case when order cannot be created then
+ # payment will be refunded.
+ update_payment_charge_status(payment, transaction)
+ payment.refresh_from_db()
+ checkout.refresh_from_db()
manager = get_plugins_manager()
lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
if unavailable_variant_pks:
+ payment_refund_or_void(payment, manager, checkout.channel.slug)
raise ValidationError("Some of the checkout lines variants are unavailable.")
checkout_info = fetch_checkout_info(checkout, lines, manager)
checkout_total = calculate_checkout_total_with_gift_cards(
@@ -188,12 +197,14 @@ def _finalize_checkout(
)
try:
- # when checkout total value is different than total amount from payments
- # it means that some products has been removed during the payment was completed
- if checkout_total.gross.amount != payment.total:
+ # when checkout total amount is less than total amount from payments
+ # it means that something changed in the checkout and we make a refund
+ # if the checkout is overpaid we allow to create the order and handle it
+ # by staff.
+ if checkout_total.gross.amount > payment.total:
payment_refund_or_void(payment, manager, checkout_info.channel.slug)
raise ValidationError(
- "Cannot complete checkout - some products do not exist anymore."
+ "Cannot complete checkout - payment doesn't cover the checkout total."
)
order, _, _ = complete_checkout(
@@ -255,14 +266,12 @@ def _update_payment_with_new_transaction(
def _process_payment_with_checkout(
payment: Payment,
payment_intent: StripeObject,
+ checkout: Checkout,
kind: str,
amount: str,
currency: str,
):
- checkout = _get_checkout(payment.id)
-
- if checkout:
- _finalize_checkout(checkout, payment, payment_intent, kind, amount, currency)
+ _finalize_checkout(checkout, payment, payment_intent, kind, amount, currency)
def _update_payment_method_metadata(
@@ -290,7 +299,7 @@ def update_payment_method_details_from_intent(
def handle_authorized_payment_intent(
payment_intent: StripeObject, gateway_config: "GatewayConfig", channel_slug: str
):
- payment = _get_payment(payment_intent.id)
+ payment = _get_payment(payment_intent.id, with_lock=False)
if not payment:
logger.warning(
@@ -299,6 +308,13 @@ def handle_authorized_payment_intent(
)
return
+ # We apply the lock in the same order as in the checkoutComplete logic. By
+ # reverting these calls we have a risk of deadlocks.
+ checkout = _get_checkout(payment.id)
+ payment = _get_payment(payment_intent.id, with_lock=True)
+ # payment was already fetch, we are sure that it exists
+ payment = cast(Payment, payment)
+
if _channel_slug_is_different_from_payment_channel_slug(channel_slug, payment):
return
@@ -329,10 +345,11 @@ def handle_authorized_payment_intent(
# Order already created
return
- if payment.checkout_id:
+ if checkout:
_process_payment_with_checkout(
payment,
payment_intent,
+ checkout=checkout,
kind=TransactionKind.AUTH,
amount=payment_intent.amount,
currency=payment_intent.currency,
@@ -369,7 +386,7 @@ def handle_failed_payment_intent(
def handle_processing_payment_intent(
payment_intent: StripeObject, _gateway_config: "GatewayConfig", channel_slug: str
):
- payment = _get_payment(payment_intent.id)
+ payment = _get_payment(payment_intent.id, with_lock=False)
if not payment:
logger.warning(
@@ -389,10 +406,18 @@ def handle_processing_payment_intent(
# Order already created
return
- if payment.checkout_id:
+ # We apply the lock in the same order as in the checkoutComplete logic. By
+ # reverting these calls we have a risk of deadlocks.
+ checkout = _get_checkout(payment.id)
+ payment = _get_payment(payment_intent.id, with_lock=True)
+ # payment was already fetch, we are sure that it exists
+ payment = cast(Payment, payment)
+
+ if checkout:
_process_payment_with_checkout(
payment,
payment_intent,
+ checkout,
TransactionKind.PENDING,
amount=payment_intent.amount,
currency=payment_intent.currency,
@@ -402,7 +427,7 @@ def handle_processing_payment_intent(
def handle_successful_payment_intent(
payment_intent: StripeObject, gateway_config: "GatewayConfig", channel_slug: str
):
- payment = _get_payment(payment_intent.id)
+ payment = _get_payment(payment_intent.id, with_lock=False)
if not payment:
logger.warning(
@@ -411,6 +436,13 @@ def handle_successful_payment_intent(
)
return
+ # We apply the lock in the same order as in the checkoutComplete logic. By
+ # reverting these calls we have a risk of deadlocks.
+ checkout = _get_checkout(payment.id)
+ payment = _get_payment(payment_intent.id, with_lock=True)
+ # payment was already fetch, we are sure that it exists
+ payment = cast(Payment, payment)
+
if _channel_slug_is_different_from_payment_channel_slug(channel_slug, payment):
return
@@ -448,11 +480,12 @@ def handle_successful_payment_intent(
)
return
- if payment.checkout_id:
+ if checkout:
_process_payment_with_checkout(
payment,
payment_intent,
- TransactionKind.CAPTURE,
+ checkout=checkout,
+ kind=TransactionKind.CAPTURE,
amount=payment_intent.amount_received,
currency=payment_intent.currency,
)