Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add payment amount check in CheckoutComplete
IKarbowiak20e604f0e661
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 37e1587218..66eec0e5a4 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Iterable, Optionalfrom ..core.prices import quantize_price+from ..core.taxes import zero_taxed_moneyfrom ..discount import DiscountInfofrom ..plugins.manager import get_plugins_manager@@ -41,6 +42,17 @@ def checkout_subtotal(return quantize_price(calculated_checkout_subtotal, checkout.currency)+def calculate_checkout_total(+ checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None+) -> "TaxedMoney":+ total = (+ checkout_total(checkout=checkout, lines=list(checkout), discounts=discounts,)+ - checkout.get_total_gift_cards_balance()+ )++ return max(total, zero_taxed_money(total.currency))++def checkout_total(*,checkout: "Checkout",diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 2db2af2ba4..9c5a587ee9 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -8,6 +8,7 @@ from django.db.models import Prefetchfrom ...account.error_codes import AccountErrorCodefrom ...checkout import models+from ...checkout.calculations import calculate_checkout_totalfrom ...checkout.error_codes import CheckoutErrorCodefrom ...checkout.utils import (abort_order_data,@@ -773,6 +774,15 @@ class CheckoutComplete(BaseMutation):error_type_class = CheckoutErrorerror_type_field = "checkout_errors"+ @classmethod+ def validate_payment_amount(cls, discounts, payment, checkout):+ if payment.total != calculate_checkout_total(checkout, discounts).gross.amount:+ gateway.payment_refund_or_void(payment)+ raise ValidationError(+ "Payment does not cover all checkout value.",+ code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.value,+ )+@classmethoddef perform_mutation(cls, _root, info, checkout_id, store_source, **data):checkout = cls.get_node_or_error(@@ -801,6 +811,8 @@ class CheckoutComplete(BaseMutation):payment = checkout.get_last_active_payment()+ cls.validate_payment_amount(discounts, payment, checkout)+redirect_url = data.get("redirect_url", "")if redirect_url:try:@@ -819,10 +831,7 @@ class CheckoutComplete(BaseMutation):discounts=discounts,)except InsufficientStock as e:- if payment.can_refund():- gateway.refund(payment)- elif payment.can_void():- gateway.void(payment)+ gateway.payment_refund_or_void(payment)raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex c9e2a8986a..b8e4733fdb 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1674,7 +1674,8 @@ MUTATION_CHECKOUT_COMPLETE = """},checkoutErrors {field,- message+ message,+ code}confirmationNeededconfirmationData@@ -1707,8 +1708,7 @@ def test_checkout_complete(checkout_line_quantity = checkout_line.quantitycheckout_line_variant = checkout_line.variant- gift_current_balance = checkout.get_total_gift_cards_balance()- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ total = calculations.calculate_checkout_total(checkout=checkout)payment = payment_dummypayment.is_active = Truepayment.order = None@@ -1731,7 +1731,7 @@ def test_checkout_complete(assert Order.objects.count() == orders_count + 1order = Order.objects.first()assert order.token == order_token- assert order.total.gross == total.gross - gift_current_balance+ assert order.total.gross == total.grossassert order.metadata == checkout.metadataassert order.private_metadata == checkout.private_metadata@@ -1911,7 +1911,7 @@ def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(checkout.store_value_in_private_metadata(items={"accepted": "false"})checkout.save()- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ total = calculations.calculate_checkout_total(checkout=checkout)payment = payment_dummy_credit_cardpayment.is_active = Truepayment.order = None@@ -2331,8 +2331,7 @@ def test_checkout_complete_without_redirect_url(checkout_line_quantity = checkout_line.quantitycheckout_line_variant = checkout_line.variant- gift_current_balance = checkout.get_total_gift_cards_balance()- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ total = calculations.calculate_checkout_total(checkout=checkout)payment = payment_dummypayment.is_active = Truepayment.order = None@@ -2355,7 +2354,7 @@ def test_checkout_complete_without_redirect_url(assert Order.objects.count() == orders_count + 1order = Order.objects.first()assert order.token == order_token- assert order.total.gross == total.gross - gift_current_balance+ assert order.total.gross == total.grossorder_line = order.lines.first()assert checkout_line_quantity == order_line.quantity@@ -2376,6 +2375,55 @@ def test_checkout_complete_without_redirect_url().exists(), "Checkout should have been deleted"+@patch("saleor.graphql.checkout.mutations.gateway.payment_refund_or_void")+def test_checkout_complete_payment_payment_total_different_than_checkout(+ gateway_refund_or_void_mock,+ checkout_with_item,+ address,+ shipping_method,+ payment_dummy,+ user_api_client,+):+ # given+ checkout = checkout_with_item+ 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()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount + Decimal(10)+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert (+ data["checkoutErrors"][0]["code"]+ == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name+ )+ assert orders_count == Order.objects.count()++ gateway_refund_or_void_mock.assert_called_with(payment)++def test_fetch_checkout_by_token(user_api_client, checkout_with_item):query = """query getCheckout($token: UUID!) {diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex f5931bc1ea..5bee7e2258 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -2,10 +2,9 @@ import graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationError-from ...checkout import calculations+from ...checkout.calculations import calculate_checkout_totalfrom ...checkout.utils import cancel_active_paymentsfrom ...core.permissions import OrderPermissions-from ...core.taxes import zero_taxed_moneyfrom ...core.utils import get_client_ipfrom ...core.utils.url import validate_storefront_urlfrom ...graphql.checkout.utils import clean_billing_address, clean_checkout_shipping@@ -77,19 +76,6 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):error_type_class = common_types.PaymentErrorerror_type_field = "payment_errors"- @classmethod- def calculate_total(cls, info, checkout):- checkout_total = (- calculations.checkout_total(- checkout=checkout,- lines=list(checkout),- discounts=info.context.discounts,- )- - checkout.get_total_gift_cards_balance()- )-- return max(checkout_total, zero_taxed_money(checkout_total.currency))-@classmethoddef clean_shipping_method(cls, checkout):if not checkout.shipping_method:@@ -169,7 +155,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):cls.validate_token(info.context.plugins, gateway, data)cls.validate_return_url(data)- checkout_total = cls.calculate_total(info, checkout)+ checkout_total = calculate_checkout_total(checkout, info.context.discounts)amount = data.get("amount", checkout_total.gross.amount)clean_checkout_shipping(checkout, list(checkout), info.context.discounts, PaymentErrorCodediff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex 8b67679a39..afec2d5366 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -244,3 +244,10 @@ def _validate_refund_amount(payment: Payment, amount: Decimal):raise PaymentError("Amount should be a positive number.")if amount > payment.captured_amount:raise PaymentError("Cannot refund more than captured.")+++def payment_refund_or_void(payment):+ if payment.can_refund():+ refund(payment)+ elif payment.can_void():+ void(payment)