Skip to content

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

Fix voucher usage increasing race condition (#15862)

Iga Karbowiak01f6a116f8de
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 4aaad9f206..92b92ead51 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -116,14 +116,53 @@ def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
return {}
customer_email = cast(str, checkout_info.get_customer_email())
- increase_voucher_usage(voucher, voucher_code, customer_email)
+ _increase_checkout_voucher_usage(checkout, voucher_code, voucher, customer_email)
return {
"voucher": voucher,
"voucher_code": voucher_code.code,
}
+@traced_atomic_transaction()
+def _increase_checkout_voucher_usage(
+ checkout: "Checkout",
+ voucher_code: "VoucherCode",
+ voucher: "Voucher",
+ customer_email: str,
+):
+ # Prevent race condition when two different threads are processing the same checkout
+ # with limited usage voucher assigned, both threads increasing the
+ # voucher usage which causing `NotApplicable` error for voucher.
+ if checkout.is_voucher_usage_increased:
+ return
+
+ increase_voucher_usage(voucher, voucher_code, customer_email)
+ checkout.is_voucher_usage_increased = True
+ checkout.save(update_fields=["is_voucher_usage_increased"])
+
+
+@traced_atomic_transaction()
+def _release_checkout_voucher_usage(
+ checkout: "Checkout",
+ voucher_code: Optional["VoucherCode"],
+ voucher: Optional["Voucher"],
+ user_email: Optional[str],
+):
+ if not checkout.is_voucher_usage_increased:
+ return
+
+ checkout.is_voucher_usage_increased = False
+ checkout.save(update_fields=["is_voucher_usage_increased"])
+
+ if voucher_code:
+ release_voucher_code_usage(
+ voucher_code,
+ voucher,
+ user_email,
+ )
+
+
def _process_shipping_data_for_order(
checkout_info: "CheckoutInfo",
base_shipping_price: Money,
@@ -525,7 +564,8 @@ def _prepare_order_data(
try:
manager.preprocess_order_creation(checkout_info, lines)
except TaxError:
- release_voucher_code_usage(
+ _release_checkout_voucher_usage(
+ checkout,
checkout_info.voucher_code,
checkout_info.voucher,
order_data.get("user_email"),
@@ -816,6 +856,7 @@ def _get_order_data(
def _process_payment(
+ checkout: Checkout,
payment: Payment,
customer_id: Optional[str],
store_source: bool,
@@ -850,10 +891,8 @@ def _process_payment(
if not txn.is_success:
raise PaymentError(txn.error)
except PaymentError as e:
- release_voucher_code_usage(
- voucher_code,
- voucher,
- order_data.get("user_email"),
+ _release_checkout_voucher_usage(
+ checkout, voucher_code, voucher, order_data.get("user_email")
)
raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value)
return txn
@@ -929,7 +968,8 @@ def complete_checkout_post_payment_part(
action_required = txn.action_required
if action_required:
action_data = txn.action_required_data
- release_voucher_code_usage(
+ _release_checkout_voucher_usage(
+ checkout_info.checkout,
checkout_info.voucher_code,
checkout_info.voucher,
order_data.get("user_email"),
@@ -952,7 +992,8 @@ def complete_checkout_post_payment_part(
# remove checkout after order is successfully created
checkout_info.checkout.delete()
except InsufficientStock as e:
- release_voucher_code_usage(
+ _release_checkout_voucher_usage(
+ checkout_info.checkout,
checkout_info.voucher_code,
checkout_info.voucher,
order_data.get("user_email"),
@@ -963,7 +1004,8 @@ def complete_checkout_post_payment_part(
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error
except GiftCardNotApplicable as e:
- release_voucher_code_usage(
+ _release_checkout_voucher_usage(
+ checkout_info.checkout,
checkout_info.voucher_code,
checkout_info.voucher,
order_data.get("user_email"),
@@ -1002,8 +1044,9 @@ def _increase_voucher_code_usage_value(checkout_info: "CheckoutInfo"):
return None
customer_email = cast(str, checkout_info.get_customer_email())
- increase_voucher_usage(voucher, code, customer_email)
+ checkout = checkout_info.checkout
+ _increase_checkout_voucher_usage(checkout, code, voucher, customer_email)
return code
@@ -1368,17 +1411,13 @@ def create_order_from_checkout(
checkout_info.checkout.delete()
return order
except InsufficientStock:
- release_voucher_code_usage(
- code,
- voucher,
- checkout_info.checkout.get_customer_email(),
+ _release_checkout_voucher_usage(
+ checkout, code, voucher, checkout_info.checkout.get_customer_email()
)
raise
except GiftCardNotApplicable:
- release_voucher_code_usage(
- code,
- voucher,
- checkout_info.checkout.get_customer_email(),
+ _release_checkout_voucher_usage(
+ checkout, code, voucher, checkout_info.checkout.get_customer_email()
)
raise
@@ -1557,9 +1596,17 @@ def complete_checkout_with_payment(
voucher_code = checkout_info.voucher_code
if payment:
with transaction_with_commit_on_errors():
- Checkout.objects.select_for_update().filter(pk=checkout_pk).first()
+ checkout = (
+ Checkout.objects.select_for_update().filter(pk=checkout_pk).first()
+ )
+
+ if not checkout:
+ order = Order.objects.get_by_checkout_token(checkout_pk)
+ return order, False, {}
+
payment = Payment.objects.select_for_update().get(id=payment.id)
txn = _process_payment(
+ checkout=checkout,
payment=payment,
customer_id=customer_id,
store_source=store_source,
diff --git a/saleor/checkout/migrations/0064_checkout_is_voucher_usage_increased.py b/saleor/checkout/migrations/0064_checkout_is_voucher_usage_increased.py
new file mode 100644
index 0000000000..765b6ab234
--- /dev/null
+++ b/saleor/checkout/migrations/0064_checkout_is_voucher_usage_increased.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.25 on 2024-04-23 06:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0063_auto_20240402_1114"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="is_voucher_usage_increased",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN is_voucher_usage_increased
+ SET DEFAULT false;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0068_merge_20240424_1209.py b/saleor/checkout/migrations/0068_merge_20240424_1209.py
new file mode 100644
index 0000000000..ff4dce4f73
--- /dev/null
+++ b/saleor/checkout/migrations/0068_merge_20240424_1209.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2024-04-24 12:09
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0064_checkout_is_voucher_usage_increased"),
+ ("checkout", "0067_auto_20240405_0756"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 8f4ae38288..291965a248 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -181,8 +181,13 @@ class Checkout(models.Model):
discount_name = models.CharField(max_length=255, blank=True, null=True)
translated_discount_name = models.CharField(max_length=255, blank=True, null=True)
- voucher_code = models.CharField(max_length=255, blank=True, null=True)
gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts")
+ voucher_code = models.CharField(max_length=255, blank=True, null=True)
+
+ # The field prevents race condition when two different threads are processing
+ # the same checkout with limited usage voucher assigned. Both threads increasing the
+ # voucher usage would cause `NotApplicable` error for voucher.
+ is_voucher_usage_increased = models.BooleanField(default=False)
redirect_url = models.URLField(blank=True, null=True)
tracking_code = models.CharField(max_length=255, blank=True, null=True)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 7abf6d1de3..d2b0b5d508 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -54,6 +54,7 @@ from ..utils import (
get_checkout_metadata,
get_external_shipping_id,
get_voucher_discount_for_checkout,
+ get_voucher_for_checkout,
get_voucher_for_checkout_info,
is_fully_paid,
recalculate_checkout_discount,
@@ -1195,6 +1196,58 @@ def test_get_voucher_for_checkout_info_no_voucher_code(checkout):
assert checkout_voucher is None
+def test_get_voucher_for_checkout(checkout_with_voucher, voucher):
+ # given
+ checkout = checkout_with_voucher
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+
+ # when
+ checkout_voucher, _ = get_voucher_for_checkout(checkout, checkout.channel.slug)
+
+ # then
+ assert checkout_voucher == voucher
+
+
+def test_get_voucher_for_checkout_voucher_used(checkout_with_voucher, voucher):
+ # given
+ checkout = checkout_with_voucher
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+
+ code = voucher.codes.first()
+ code.used = 1
+ code.save(update_fields=["used"])
+
+ # when
+ checkout_voucher, _ = get_voucher_for_checkout(checkout, checkout.channel.slug)
+
+ # then
+ assert checkout_voucher is None
+
+
+def test_get_voucher_for_checkout_voucher_used_voucher_usage_already_increased(
+ checkout_with_voucher, voucher
+):
+ # given
+ checkout = checkout_with_voucher
+ checkout.is_voucher_usage_increased = True
+ checkout.save(update_fields=["is_voucher_usage_increased"])
+
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+
+ code = voucher.codes.first()
+ code.used = 1
+ code.save(update_fields=["used"])
+
+ # when
+ checkout_voucher, _ = get_voucher_for_checkout(checkout, checkout.channel.slug)
+
+ # then
+ assert checkout_voucher == voucher
+
+
def test_remove_voucher_from_checkout(checkout_with_voucher, voucher_translation_fr):
checkout = checkout_with_voucher
remove_voucher_from_checkout(checkout)
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 2a5f46cdbe..635976016c 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -31,8 +31,10 @@ from ...tests.utils import flush_post_commit_hooks
from .. import calculations
from ..complete_checkout import (
_create_order,
+ _increase_checkout_voucher_usage,
_prepare_order_data,
_process_shipping_data_for_order,
+ _release_checkout_voucher_usage,
complete_checkout,
)
from ..fetch import fetch_checkout_info, fetch_checkout_lines
@@ -1391,6 +1393,8 @@ def test_complete_checkout_action_required_voucher_once_per_customer(
assert action_required is True
assert not voucher_customer.exists()
mocked_create_order.assert_not_called()
+ checkout.refresh_from_db()
+ assert checkout.is_voucher_usage_increased is False
@mock.patch("saleor.checkout.complete_checkout._create_order")
@@ -1456,6 +1460,9 @@ def test_complete_checkout_action_required_voucher_single_use(
code.refresh_from_db()
assert code.is_active is True
+ checkout.refresh_from_db()
+ assert checkout.is_voucher_usage_increased is False
+
@mock.patch("saleor.checkout.complete_checkout._create_order")
def test_complete_checkout_order_not_created_when_the_refund_is_ongoing(
@@ -1619,6 +1626,146 @@ def test_complete_checkout_checkout_was_deleted_before_completing(
mocked_create_order.assert_not_called()
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._process_payment")
+def test_complete_checkout_checkout_limited_use_voucher_multiple_thread(
+ mocked_process_payment,
+ mocked_payment_refund_or_void,
+ customer_user,
+ checkout_with_voucher_free_shipping,
+ voucher_free_shipping,
+ app,
+ success_gateway_response,
+):
+ # given
+ checkout = checkout_with_voucher_free_shipping
+ address = customer_user.default_billing_address
+ checkout.user = customer_user
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ voucher_free_shipping.usage_limit = 1
+ voucher_free_shipping.save(update_fields=["usage_limit"])
+
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ Payment.objects.create(
+ gateway="mirumee.payments.dummy",
+ is_active=True,
+ checkout=checkout,
+ total=total.gross.amount,
+ )
+ mocked_process_payment.return_value = success_gateway_response
+
+ # when
+ def call_checkout_complete(*args, **kwargs):
+ lines_2, _ = fetch_checkout_lines(checkout)
+ checkout_info_2 = fetch_checkout_info(checkout, lines, manager)
+ complete_checkout(
+ checkout_info=checkout_info_2,
+ lines=lines_2,
+ manager=manager,
+ payment_data={},
+ store_source=False,
+ user=customer_user,
+ app=app,
+ )
+
+ with before_after.after(
+ "saleor.checkout.complete_checkout._process_payment", call_checkout_complete
+ ):
+ order_from_checkout, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ lines=lines,
+ manager=manager,
+ payment_data={},
+ store_source=False,
+ user=customer_user,
+ app=app,
+ )
+ # then
+ assert order_from_checkout
+ mocked_payment_refund_or_void.assert_not_called()
+ code = voucher_free_shipping.codes.first()
+ assert code.used == 1
+
+
[email protected]("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
[email protected]("saleor.checkout.complete_checkout._process_payment")
+def test_complete_checkout_checkout_completed_in_the_meantime(
+ mocked_process_payment,
+ mocked_payment_refund_or_void,
+ customer_user,
+ checkout,
+ app,
+ success_gateway_response,
+):
+ # given
+ address = customer_user.default_billing_address
+ checkout.user = customer_user
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ Payment.objects.create(
+ gateway="mirumee.payments.dummy",
+ is_active=True,
+ checkout=checkout,
+ total=total.gross.amount,
+ )
+ mocked_process_payment.return_value = success_gateway_response
+
+ # when
+ def call_checkout_complete(*args, **kwargs):
+ lines_2, _ = fetch_checkout_lines(checkout)
+ checkout_info_2 = fetch_checkout_info(checkout, lines, manager)
+ complete_checkout(
+ checkout_info=checkout_info_2,
+ lines=lines_2,
+ manager=manager,
+ payment_data={},
+ store_source=False,
+ user=customer_user,
+ app=app,
+ )
+
+ with before_after.after(
+ "saleor.checkout.complete_checkout._reserve_stocks_without_availability_check",
+ call_checkout_complete,
+ ):
+ order_from_checkout, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ lines=lines,
+ manager=manager,
+ payment_data={},
+ store_source=False,
+ user=customer_user,
+ app=app,
+ )
+ # then
+ assert order_from_checkout
+ mocked_payment_refund_or_void.assert_not_called()
+
+
def test_process_shipping_data_for_order_store_customer_shipping_address(
checkout_with_item, customer_user, address_usa, shipping_method
):
@@ -1890,6 +2037,8 @@ def test_complete_checkout_invalid_shipping_method(
mocked_payment_refund_or_void.called_once_with(
payment, manager, channel_slug=checkout.channel.slug
)
+ checkout.refresh_from_db()
+ assert checkout.is_voucher_usage_increased is False
@mock.patch("saleor.checkout.complete_checkout.complete_checkout_with_transaction")
@@ -2119,3 +2268,90 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
mocked_get_tax_calculation_strategy_for_checkout.call_count
== calculation_call_count
)
+
+
[email protected]("saleor.checkout.complete_checkout.increase_voucher_usage")
+def test_increase_checkout_voucher_usage(
+ increase_voucher_usage_mock, checkout_with_voucher, voucher
+):
+ # given
+ code = voucher.codes.first()
+
+ # when
+ _increase_checkout_voucher_usage(checkout_with_voucher, code, voucher, None)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert checkout_with_voucher.is_voucher_usage_increased is True
+ increase_voucher_usage_mock.assert_called_once()
+
+
[email protected]("saleor.checkout.complete_checkout.increase_voucher_usage")
+def test_increase_checkout_voucher_usage_checkout_usage_already_increased(
+ increase_voucher_usage_mock, checkout_with_voucher, voucher
+):
+ # given
+ code = voucher.codes.first()
+ checkout_with_voucher.is_voucher_usage_increased = True
+ checkout_with_voucher.save(update_fields=["is_voucher_usage_increased"])
+
+ # when
+ _increase_checkout_voucher_usage(checkout_with_voucher, code, voucher, None)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert checkout_with_voucher.is_voucher_usage_increased is True
+ increase_voucher_usage_mock.assert_not_called()
+
+
[email protected]("saleor.checkout.complete_checkout.release_voucher_code_usage")
+def test_release_checkout_voucher_usage(
+ release_voucher_usage_mock, checkout_with_voucher, voucher
+):
+ # given
+ code = voucher.codes.first()
+ checkout_with_voucher.is_voucher_usage_increased = True
+ checkout_with_voucher.save(update_fields=["is_voucher_usage_increased"])
+
+ # when
+ _release_checkout_voucher_usage(checkout_with_voucher, code, voucher, None)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert checkout_with_voucher.is_voucher_usage_increased is False
+ release_voucher_usage_mock.assert_called_once()
+
+
[email protected]("saleor.checkout.complete_checkout.release_voucher_code_usage")
+def test_release_checkout_voucher_usage_checkout_usage_not_increased(
+ release_voucher_usage_mock, checkout_with_voucher, voucher
+):
+ # given
+ code = voucher.codes.first()
+ checkout_with_voucher.is_voucher_usage_increased = False
+ checkout_with_voucher.save(update_fields=["is_voucher_usage_increased"])
+
+ # when
+ _release_checkout_voucher_usage(checkout_with_voucher, code, voucher, None)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert checkout_with_voucher.is_voucher_usage_increased is False
+ release_voucher_usage_mock.assert_not_called()
+
+
[email protected]("saleor.checkout.complete_checkout.release_voucher_code_usage")
+def test_release_checkout_voucher_usage_no_voucher_code(
+ release_voucher_usage_mock, checkout_with_voucher, voucher
+):
+ # given
+ checkout_with_voucher.is_voucher_usage_increased = True
+ checkout_with_voucher.save(update_fields=["is_voucher_usage_increased"])
+
+ # when
+ _release_checkout_voucher_usage(checkout_with_voucher, None, voucher, None)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert checkout_with_voucher.is_voucher_usage_increased is False
+ release_voucher_usage_mock.assert_not_called()
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 94084f66b2..ed90f3574d 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -574,12 +574,21 @@ def get_voucher_for_checkout(
except VoucherCode.DoesNotExist:
return None, None
- voucher = (
- Voucher.objects.using(database_connection_name)
- .active_in_channel(date=timezone.now(), channel_slug=channel_slug)
- .filter(id=code.voucher_id)
- .first()
- )
+ # The voucher validation should be performed only when the voucher
+ # usage for this checkout hasn't been increased.
+ if checkout.is_voucher_usage_increased:
+ voucher = (
+ Voucher.objects.using(database_connection_name)
+ .filter(id=code.voucher_id)
+ .first()
+ )
+ else:
+ voucher = (
+ Voucher.objects.using(database_connection_name)
+ .active_in_channel(date=timezone.now(), channel_slug=channel_slug)
+ .filter(id=code.voucher_id)
+ .first()
+ )
if not voucher:
return None, None
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index 01cbb35d43..207600ca14 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -8,9 +8,11 @@ from django.core.exceptions import ValidationError
from django.utils import timezone
from stripe.stripe_object import StripeObject
+from .....checkout.calculations import calculate_checkout_total_with_gift_cards
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 .....payment.models import Transaction
from .....plugins.manager import get_plugins_manager
from .....tests.utils import flush_post_commit_hooks
from .... import ChargeStatus, TransactionKind
@@ -382,6 +384,94 @@ def test_handle_successful_payment_intent_different_order_channel_slug(
assert wrapped_order_charged.called == called
+@patch("saleor.checkout.complete_checkout.gateway.payment_refund_or_void")
+@patch("saleor.checkout.complete_checkout.gateway.process_payment")
+@patch("saleor.payment.gateways.stripe.webhooks.order_charged", wraps=order_charged)
+@patch("saleor.payment.gateways.stripe.webhooks.update_payment_method")
+def test_handle_successful_payment_intent_checkout_with_voucher_ongoing_completing(
+ _wrapped_update_payment_method,
+ wrapped_order_charged,
+ wrapped_process_payment,
+ wrapped_payment_refund_or_void,
+ payment_stripe_for_checkout,
+ voucher_free_shipping,
+ stripe_plugin,
+ channel_USD,
+ customer_user,
+ success_gateway_response,
+):
+ # given
+ channel = channel_USD
+ payment = payment_stripe_for_checkout
+ checkout = payment.checkout
+
+ wrapped_process_payment.return_value = success_gateway_response
+
+ checkout.voucher_code = voucher_free_shipping.codes.first().code
+ checkout.save(update_fields=["voucher_code"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ address = customer_user.default_billing_address
+ total = calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ # set voucher usage limit to 1
+ voucher_free_shipping.usage_limit = 1
+ voucher_free_shipping.save(update_fields=["usage_limit"])
+
+ plugin = stripe_plugin()
+ payment_intent = StripeObject(id="token", last_response={})
+ payment_intent["amount_received"] = payment.total
+ payment_intent["currency"] = payment.currency
+ payment_intent["capture_method"] = "automatic"
+ payment_intent["setup_future_usage"] = None
+ payment_intent["payment_method"] = StripeObject()
+
+ Transaction.objects.create(
+ payment=payment_stripe_for_checkout,
+ action_required=False,
+ kind=TransactionKind.AUTH,
+ token=payment_intent.id,
+ is_success=True,
+ amount=total.gross.amount,
+ currency=total.gross.currency,
+ error="",
+ gateway_response={},
+ action_required_data={},
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ def call_webhook_success_event(*args, **kwargs):
+ handle_successful_payment_intent(payment_intent, plugin.config, channel.slug)
+
+ with before_after.after(
+ "saleor.checkout.complete_checkout._process_payment", call_webhook_success_event
+ ):
+ order_from_checkout, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ lines=lines,
+ manager=manager,
+ payment_data={},
+ store_source=False,
+ user=customer_user,
+ app=None,
+ )
+
+ # then
+ assert wrapped_order_charged.called is False
+ assert order_from_checkout
+ wrapped_payment_refund_or_void.assert_not_called()
+ code = voucher_free_shipping.codes.first()
+ assert code.used == 1
+
+
@patch(
"saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout
)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index f4f558fc7d..0ee1eb7b4d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -8609,6 +8609,20 @@ def action_required_gateway_response():
)
+def success_gateway_response():
+ return GatewayResponse(
+ is_success=True,
+ action_required=False,
+ action_required_data={},
+ kind=TransactionKind.CAPTURE,
+ amount=Decimal("10.0"),
+ currency="usd",
+ transaction_id="1234",
+ error=None,
+ )
+
+
@pytest.fixture
def product_media_image(product, image, media_root):
return ProductMedia.objects.create(