Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prevent multiple `checkoutPaymentCreate` calls and creating an order for inactive payment (#11139) (#11178)
Iga Karbowiak7d4bcc752c20
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex a7f43a9452..fce7efc308 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -71,6 +71,7 @@ from .checkout_cleaner import (clean_checkout_shipping,)from .fetch import CheckoutInfo, CheckoutLineInfo+from .models import Checkoutfrom .utils import get_voucher_for_checkout_infoif TYPE_CHECKING:@@ -78,7 +79,6 @@ if TYPE_CHECKING:from ..discount.models import Voucherfrom ..plugins.manager import PluginsManagerfrom ..site.models import SiteSettings- from .models import Checkoutdef _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:@@ -1258,9 +1258,19 @@ def complete_checkout()reservations = _reserve_stocks_without_availability_check(checkout_info, lines)+ # Fetch the checkout with a lock just to ensure that no payment is created+ # for this checkout right now.+ with transaction.atomic():+ (+ Checkout.objects.select_for_update()+ .filter(pk=checkout_info.checkout.pk)+ .first()+ )+# Process payments out of transaction to unlock stock rows for another user,# who potentially can order the same product variants.txn = None+ channel_slug = checkout_info.channel.slugif payment:txn = _process_payment(payment=payment,@@ -1269,9 +1279,20 @@ def complete_checkout(payment_data=payment_data,order_data=order_data,manager=manager,- channel_slug=checkout_info.channel.slug,+ channel_slug=channel_slug,)+ # As payment processing might take a while, we need to check if the payment+ # doesn't become inactive in the meantime. If it's inactive we need to refund+ # the payment.+ payment.refresh_from_db()+ if not payment.is_active:+ gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)+ raise ValidationError(+ f"The payment with pspReference: {payment.psp_reference} is inactive.",+ code=CheckoutErrorCode.INACTIVE_PAYMENT.value,+ )+with transaction_with_commit_on_errors():# Run pre-payment checks to make sure, that nothing has changed to the# checkout, during processing payment.diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex 3c5d866bed..eb729b481b 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -29,6 +29,7 @@ class CheckoutErrorCode(Enum):UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"EMAIL_NOT_SET = "email_not_set"NO_LINES = "no_lines"+ INACTIVE_PAYMENT = "inactive_payment"class OrderCreateFromCheckoutErrorCode(Enum):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex c3809f4e3f..972794cb9f 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -2,6 +2,7 @@ from datetime import datetime, timedeltafrom decimal import Decimalfrom unittest.mock import ANY, patch+import before_afterimport grapheneimport pytestimport pytz@@ -3307,3 +3308,76 @@ def test_checkout_complete_reservations_drop(data = content["data"]["checkoutComplete"]assert not data["errors"]assert not len(Reservation.objects.all())++[email protected]_db(transaction=True)+def test_checkout_complete_payment_create_create_run_in_meantime(+ site_settings,+ user_api_client,+ checkout_without_shipping_required,+ gift_card,+ payment_dummy,+ address,+ shipping_method,+):+ # given+ checkout = checkout_without_shipping_required+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ manager = get_plugins_manager()+ 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+ )+ site_settings.automatically_confirm_all_new_orders = True+ site_settings.save()+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ redirect_url = "https://www.example.com"+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}++ # Call CheckoutPaymentCreate mutation during the CheckoutComplete call processing.+ # It should cause deactivation of current payment and creation of new one.+ def call_payment_create_mutation(*args, **kwargs):+ from ....payment.tests.mutations.test_checkout_payment_create import (+ CREATE_PAYMENT_MUTATION,+ DUMMY_GATEWAY,+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "input": {+ "gateway": DUMMY_GATEWAY,+ "token": "sample-token",+ "amount": total.gross.amount,+ },+ }++ user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)++ # when+ with before_after.before(+ "saleor.checkout.complete_checkout._get_order_data",+ call_payment_create_mutation,+ ):+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INACTIVE_PAYMENT.namediff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 23ef32fcff..ba47de6124 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -4,6 +4,7 @@ from typing import List, Optional, Unionimport graphenefrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.db.models import Ffrom ...channel.models import Channel@@ -299,34 +300,55 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):"customer_user_agent": info.context.META.get("HTTP_USER_AGENT"),}- cancel_active_payments(checkout)-metadata = data.get("metadata")if metadata is not None:cls.validate_metadata_keys(metadata)metadata = {data.key: data.value for data in metadata}- payment = None- if amount != 0:- store_payment_method = (- data.get("store_payment_method") or StorePaymentMethod.NONE- )- payment = create_payment(- gateway=gateway,- payment_token=data.get("token", ""),- total=amount,- currency=checkout.currency,- email=checkout.get_customer_email(),- extra_data=extra_data,- # FIXME this is not a customer IP address. It is a client storefront ip- customer_ip_address=get_client_ip(info.context),- checkout=checkout,- return_url=data.get("return_url"),- store_payment_method=store_payment_method,- metadata=metadata,+ # The payment creation and deactivation of old payments should happened in the+ # transaction to avoid creating multiple active payments.+ with transaction.atomic():+ # The checkout lock is used to prevent processing checkout completion+ # and new payment creation. This kind of case could result in the missing+ # payments, that were created for the checkout that was already converted+ # to an order.+ checkout = (+ checkout_models.Checkout.objects.select_for_update()+ .filter(pk=checkout_info.checkout.pk)+ .first())+ if not checkout:+ raise ValidationError(+ "Checkout doesn't exist anymore.",+ code=PaymentErrorCode.NOT_FOUND.value,+ )++ cancel_active_payments(checkout)++ payment = None+ if amount != 0:+ store_payment_method = (+ data.get("store_payment_method") or StorePaymentMethod.NONE+ )++ payment = create_payment(+ gateway=gateway,+ payment_token=data.get("token", ""),+ total=amount,+ currency=checkout.currency,+ email=checkout.get_customer_email(),+ extra_data=extra_data,+ # FIXME this is not a customer IP address.+ # It is a client storefront ip+ customer_ip_address=get_client_ip(info.context),+ checkout=checkout,+ return_url=data.get("return_url"),+ store_payment_method=store_payment_method,+ metadata=metadata,+ )+return CheckoutPaymentCreate(payment=payment, checkout=checkout)diff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.pyindex 0e9dc62820..4217b45a02 100644--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py@@ -1,6 +1,7 @@from decimal import Decimalfrom unittest.mock import patch+import before_afterimport grapheneimport pytest@@ -661,3 +662,46 @@ def test_checkout_add_payment_checkout_without_lines(assert len(errors) == 1assert errors[0]["field"] == "lines"assert errors[0]["code"] == PaymentErrorCode.NO_CHECKOUT_LINES.name+++def test_checkout_add_payment_run_multiple_times(+ user_api_client, checkout_without_shipping_required, address+):+ # given+ checkout = checkout_without_shipping_required+ checkout.billing_address = address+ checkout.save()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ variables = {+ "id": to_global_id_or_none(checkout),+ "input": {+ "gateway": DUMMY_GATEWAY,+ "token": "sample-token",+ "amount": total.gross.amount,+ },+ }++ # call CheckoutPaymentCreate mutation during the first mutation call processing+ def call_payment_create_mutation(*args, **kwargs):+ user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)++ # when+ with before_after.before(+ "saleor.graphql.payment.mutations.cancel_active_payments",+ call_payment_create_mutation,+ ):+ response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutPaymentCreate"]+ assert not data["errors"]+ payments = Payment.objects.filter(checkout=checkout)+ assert payments.count() == 2+ assert payments.filter(is_active=True).count() == 1diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1ed4cd326a..0f9ef19cd1 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -20112,6 +20112,7 @@ enum CheckoutErrorCode {UNAVAILABLE_VARIANT_IN_CHANNELEMAIL_NOT_SETNO_LINES+ INACTIVE_PAYMENT}"""Update billing address in the existing checkout."""diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 1840c98a7f..b98bd08449 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -2870,7 +2870,7 @@ def product_without_shipping(category, warehouse, channel_USD):visible_in_listings=True,available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),)- variant = ProductVariant.objects.create(product=product, sku="SKU_B")+ variant = ProductVariant.objects.create(product=product, sku="SKU_E")ProductVariantChannelListing.objects.create(variant=variant,channel=channel_USD,