Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix refund payment when cannot create an order in Stripe - 3.1 (#8546)
Maciej Korycinski1f47b503f69e
diff --git a/saleor/payment/gateways/stripe/tests/conftest.py b/saleor/payment/gateways/stripe/tests/conftest.pyindex fa047a36a2..b49b858e08 100644--- a/saleor/payment/gateways/stripe/tests/conftest.py+++ b/saleor/payment/gateways/stripe/tests/conftest.py@@ -1,4 +1,5 @@import pytest+from stripe.stripe_object import StripeObjectfrom .....checkout import calculationsfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines@@ -6,7 +7,8 @@ from .....plugins.manager import get_plugins_managerfrom .....plugins.models import PluginConfigurationfrom .... import TransactionKindfrom ....models import Transaction-from ....utils import create_payment+from ....utils import create_payment, price_to_minor_unit+from ..consts import SUCCESS_STATUSfrom ..plugin import StripeGatewayPlugin@@ -99,3 +101,18 @@ def stripe_plugin(settings, monkeypatch, channel_USD):return manager.plugins_per_channel[channel_USD.slug][0]return fun+++def stripe_payment_intent(payment_stripe_for_checkout):+ payment = payment_stripe_for_checkout+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount_received"] = price_to_minor_unit(+ payment.total, payment.currency+ )+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["setup_future_usage"] = None+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = SUCCESS_STATUS++ return payment_intentdiff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.pyindex f4901dc45c..83d91121b7 100644--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom unittest.mock import Mock, patchimport pytest+from django.core.exceptions import ValidationErrorfrom stripe.stripe_object import StripeObjectfrom .....checkout.complete_checkout import complete_checkout@@ -21,6 +22,7 @@ from ..consts import (WEBHOOK_SUCCESS_EVENT,)from ..webhooks import (+ _finalize_checkout,_process_payment_with_checkout,_update_payment_with_new_transaction,handle_authorized_payment_intent,@@ -77,6 +79,41 @@ def test_handle_successful_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch("saleor.payment.gateway.refund")+@patch("saleor.checkout.complete_checkout._get_order_data")+def test_handle_successful_payment_intent_when_order_creation_raises_exception(+ order_data_mock,+ refund_mock,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+ stripe_payment_intent,+):+ order_data_mock.side_effect = ValidationError("Test error")+ payment = payment_stripe_for_checkout+ payment.to_confirm = True+ payment.save()+ payment.transactions.create(+ is_success=True,+ action_required=True,+ kind=TransactionKind.CAPTURE,+ amount=payment.total,+ currency=payment.currency,+ token="ABC",+ gateway_response={},+ )+ plugin = stripe_plugin()++ handle_successful_payment_intent(+ stripe_payment_intent, plugin.config, channel_USD.slug+ )++ payment.refresh_from_db()+ assert not payment.order+ assert refund_mock.called++@pytest.mark.parametrize(["metadata", "called"],[({f"key{i}": f"value{i}" for i in range(5)}, True), ({}, False)],@@ -341,6 +378,42 @@ def test_handle_authorized_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch("saleor.checkout.complete_checkout._get_order_data")+@patch("saleor.payment.gateway.void")+def test_handle_authorized_payment_intent_when_order_creation_raises_exception(+ void_mock,+ order_data_mock,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+ stripe_payment_intent,+):+ order_data_mock.side_effect = ValidationError("Test error")+ 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={},+ )+ plugin = stripe_plugin()++ handle_authorized_payment_intent(+ stripe_payment_intent, plugin.config, channel_USD.slug+ )++ payment.refresh_from_db()++ assert not payment.order+ assert void_mock.called++@patch("saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout)@@ -572,6 +645,47 @@ def test_handle_processing_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch("saleor.checkout.complete_checkout._get_order_data")+@patch("saleor.payment.gateway.void")+@patch("saleor.payment.gateway.refund")+def test_handle_processing_payment_intent_when_order_creation_raises_exception(+ refund_mock,+ void_mock,+ order_data_mock,+ payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+ stripe_payment_intent,+):+ order_data_mock.side_effect = ValidationError("Test error")+ 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={},+ )+ plugin = stripe_plugin()++ stripe_payment_intent["status"] = PROCESSING_STATUS++ handle_processing_payment_intent(+ stripe_payment_intent, plugin.config, channel_USD.slug+ )++ payment.refresh_from_db()++ assert not payment.order+ assert not void_mock.called+ assert not refund_mock.called++@pytest.mark.parametrize("called", [True, False])@patch("saleor.payment.gateways.stripe.webhooks._process_payment_with_checkout",@@ -1049,3 +1163,61 @@ def test_handle_webhook_events(endpoint_secret,api_key=api_key,)+++@patch("saleor.payment.gateway.refund")+@patch("saleor.checkout.complete_checkout._get_order_data")+def test_finalize_checkout_not_created_order_payment_refund(+ order_data_mock,+ refund_mock,+ stripe_plugin,+ channel_USD,+ payment_stripe_for_checkout,+ stripe_payment_intent,+):+ order_data_mock.side_effect = ValidationError("Test error")+ stripe_plugin()+ checkout = payment_stripe_for_checkout.checkout++ _finalize_checkout(+ checkout,+ payment_stripe_for_checkout,+ stripe_payment_intent,+ TransactionKind.CAPTURE,+ payment_stripe_for_checkout.total,+ payment_stripe_for_checkout.currency,+ )++ payment_stripe_for_checkout.refresh_from_db()++ assert not payment_stripe_for_checkout.order+ assert refund_mock.called+++@patch("saleor.payment.gateway.void")+@patch("saleor.checkout.complete_checkout._get_order_data")+def test_finalize_checkout_not_created_order_payment_void(+ order_data_mock,+ void_mock,+ stripe_plugin,+ channel_USD,+ payment_stripe_for_checkout,+ stripe_payment_intent,+):+ order_data_mock.side_effect = ValidationError("Test error")+ stripe_plugin()+ checkout = payment_stripe_for_checkout.checkout++ _finalize_checkout(+ checkout,+ payment_stripe_for_checkout,+ stripe_payment_intent,+ TransactionKind.AUTH,+ payment_stripe_for_checkout.total,+ payment_stripe_for_checkout.currency,+ )++ payment_stripe_for_checkout.refresh_from_db()++ assert not payment_stripe_for_checkout.order+ assert void_mock.calleddiff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.pyindex 08599d1acf..83b0c7a786 100644--- a/saleor/payment/gateways/stripe/webhooks.py+++ b/saleor/payment/gateways/stripe/webhooks.py@@ -2,6 +2,7 @@ import loggingfrom typing import Optionalfrom django.contrib.auth.models import AnonymousUser+from django.core.exceptions import ValidationErrorfrom django.core.handlers.wsgi import WSGIRequestfrom django.db.models import Prefetchfrom django.http import HttpResponse@@ -19,7 +20,12 @@ from ....plugins.manager import get_plugins_managerfrom ... import ChargeStatus, TransactionKindfrom ...interface import GatewayConfig, GatewayResponsefrom ...models import Payment-from ...utils import create_transaction, gateway_postprocess, price_from_minor_unit+from ...utils import (+ create_transaction,+ gateway_postprocess,+ price_from_minor_unit,+ update_payment_charge_status,+)from .consts import (WEBHOOK_AUTHORIZED_EVENT,WEBHOOK_CANCELED_EVENT,@@ -140,7 +146,7 @@ def _finalize_checkout(psp_reference=payment_intent.id,)- create_transaction(+ transaction = create_transaction(payment,kind=kind,payment_information=None, # type: ignore@@ -148,22 +154,34 @@ def _finalize_checkout(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()discounts = fetch_active_discounts()lines = fetch_checkout_lines(checkout) # type: ignorecheckout_info = fetch_checkout_info(checkout, lines, discounts, manager # type: ignore)- order, _, _ = complete_checkout(- manager=manager,- checkout_info=checkout_info,- lines=lines,- payment_data={},- store_source=False,- discounts=discounts,- user=checkout.user or AnonymousUser(), # type: ignore- app=None,- )++ try:+ order, _, _ = complete_checkout(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ payment_data={},+ store_source=False,+ discounts=discounts,+ user=checkout.user or AnonymousUser(), # type: ignore+ app=None,+ )+ except ValidationError as e:+ logger.info("Failed to complete checkout %s.", checkout.pk, extra={"error": e})+ return Nonedef _update_payment_with_new_transaction(diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 7636b636c6..b6d7ec2c50 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -301,6 +301,12 @@ def gateway_postprocess(transaction, payment):payment.to_confirm = Falsechanged_fields.append("to_confirm")+ update_payment_charge_status(payment, transaction, changed_fields)+++def update_payment_charge_status(payment, transaction, changed_fields=None):+ changed_fields = changed_fields or []+transaction_kind = transaction.kindif transaction_kind in {