Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refund/void inactive payments in Adyen/Stripe webhooks handling - 3.1 (#9075)
Maciej Korycinskiecadd9c937a8
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex b701477455..a8d77f2c1a 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -184,7 +184,6 @@ def capture(@raise_payment_error-@require_active_payment@with_locked_payment@payment_postprocessdef refund(@@ -227,7 +226,6 @@ def refund(@raise_payment_error-@require_active_payment@with_locked_payment@payment_postprocessdef void(@@ -333,7 +331,7 @@ def _validate_refund_amount(payment: Payment, amount: Decimal):def payment_refund_or_void(- payment: Optional[Payment], manager: "PluginsManager", channel_slug: str+ payment: Optional[Payment], manager: "PluginsManager", channel_slug: Optional[str]):if payment is None:returndiff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.pyindex 173c1a8194..b03c383142 100644--- a/saleor/payment/gateways/adyen/tests/conftest.py+++ b/saleor/payment/gateways/adyen/tests/conftest.py@@ -93,6 +93,13 @@ def payment_adyen_for_checkout(checkout_with_items, address, shipping_method):return payment+def inactive_payment_adyen_for_checkout(payment_adyen_for_checkout):+ payment_adyen_for_checkout.is_active = False+ payment_adyen_for_checkout.save(update_fields=["is_active"])+ return payment_adyen_for_checkout++@pytest.fixturedef payment_adyen_for_order(order_with_lines):payment = create_payment(diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.pyindex e8e66a38f9..8e4cbb5574 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py@@ -333,6 +333,44 @@ def test_handle_authorization_with_adyen_auto_capture(assert external_events.count() == 1+@patch("saleor.payment.gateway.refund")+def test_handle_authorization_with_adyen_auto_capture_and_inactive_payment(+ refund_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout+):+ payment = inactive_payment_adyen_for_checkout+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification = notification(+ merchant_reference=payment_id,+ value=price_to_minor_unit(payment.total, payment.currency),+ )+ plugin = adyen_plugin(adyen_auto_capture=True)++ handle_authorization(notification, plugin.config)+ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ assert refund_mock.called+++@patch("saleor.payment.gateway.void")+def test_handle_authorization_without_adyen_auto_capture_and_inactive_payment(+ void_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout+):+ payment = inactive_payment_adyen_for_checkout+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification = notification(+ merchant_reference=payment_id,+ value=price_to_minor_unit(payment.total, payment.currency),+ )+ plugin = adyen_plugin(adyen_auto_capture=False)++ handle_authorization(notification, plugin.config)+ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ assert void_mock.called++@pytest.mark.vcrdef test_handle_authorization_with_auto_capture(notification, adyen_plugin, payment_adyen_for_checkout@@ -531,6 +569,30 @@ def test_handle_capture_for_checkout(assert external_events.count() == 1+@patch("saleor.payment.gateway.refund")+def test_handle_capture_inactive_payment(+ refund_mock,+ notification,+ adyen_plugin,+ inactive_payment_adyen_for_checkout,+ address,+ shipping_method,+):+ payment = inactive_payment_adyen_for_checkout+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification = notification(+ merchant_reference=payment_id,+ value=price_to_minor_unit(payment.total, payment.currency),+ )+ config = adyen_plugin().config++ handle_capture(notification, config)+ payment.refresh_from_db()++ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ assert refund_mock.called++@patch("saleor.payment.gateway.void")def test_handle_capture_for_checkout_order_not_created_checkout_line_variant_deleted(void_mock,@@ -1739,3 +1801,77 @@ def test_order_closed_with_adyen_partial_payments_unable_to_create_order(graphql_payment_id=mock.ANY,adyen_client=mock.ANY,)+++@patch("saleor.payment.gateway.void")[email protected]("saleor.payment.gateways.adyen.webhooks.call_refund")+def test_order_closed_with_not_active_payment(+ mock_call_refund,+ mock_void,+ notification,+ adyen_plugin,+ payment_adyen_for_checkout,+ address,+ shipping_method,+):+ # given++ checkout = payment_adyen_for_checkout.checkout+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ payment = payment_adyen_for_checkout+ 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+ )+ payment.is_active = False+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.to_confirm = True+ payment.save()++ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification_data = notification(+ merchant_reference=payment_id,+ value=price_to_minor_unit(payment.total, payment.currency),+ success="true",+ )+ notification_data["additionalData"] = {+ "order-2-paymentMethod": "visa",+ "order-2-pspReference": "881643125782168B",+ "order-2-paymentAmount": "GBP 29.10",+ "order-1-pspReference": "861643125754056E",+ "order-1-paymentAmount": "GBP 41.90",+ "order-1-paymentMethod": "givex",+ }+ merchant_account = "SaleorEcom"+ config = adyen_plugin(merchant_account=merchant_account).config++ # when+ handle_order_closed(notification_data, config)++ # then+ assert payment.checkout+ assert payment.order is None+ mock_call_refund.assert_any_call(+ amount=Decimal("41.90"),+ currency="GBP",+ merchant_account=merchant_account,+ token="861643125754056E",+ graphql_payment_id=mock.ANY,+ adyen_client=mock.ANY,+ )+ mock_call_refund.assert_any_call(+ amount=Decimal("29.10"),+ currency="GBP",+ merchant_account=merchant_account,+ token="881643125782168B",+ graphql_payment_id=mock.ANY,+ adyen_client=mock.ANY,+ )diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 9c528643d4..02fee373dd 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -52,6 +52,7 @@ from ...utils import (create_transaction,gateway_postprocess,price_from_minor_unit,+ try_void_or_refund_inactive_payment,)from .utils.common import (FAILED_STATUSES,@@ -260,7 +261,9 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo"""transaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:# We don't know anything about that paymentreturn@@ -291,6 +294,11 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo)return+ if not payment.is_active:+ transaction = create_new_transaction(notification, payment, kind)+ try_void_or_refund_inactive_payment(payment, transaction, manager)+ return+if not payment.order:handle_not_created_order(notification, payment, checkout, kind, manager)else:@@ -387,12 +395,22 @@ def handle_cancel_or_refund(def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#capture-notificationtransaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:returncheckout = get_checkout(payment)manager = get_plugins_manager()++ if not payment.is_active:+ transaction = create_new_transaction(+ notification, payment, TransactionKind.CAPTURE+ )+ try_void_or_refund_inactive_payment(payment, transaction, manager)+ return+if not payment.order:handle_not_created_order(notification, payment, checkout, TransactionKind.CAPTURE, manager@@ -423,7 +441,9 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#failed-capturetransaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:return@@ -450,7 +470,9 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/development-resources/webhooks/understand-notifications## event-codes"transaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:returntransaction = get_transaction(payment, transaction_id, TransactionKind.PENDING)@@ -472,7 +494,9 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#refund-notificationtransaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:returntransaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)@@ -511,7 +535,9 @@ def _get_kind(transaction: Optional[Transaction]) -> str:def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#failed-refundtransaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:return@@ -576,7 +602,9 @@ def handle_reversed_refund():# https://docs.adyen.com/checkout/refund#failed-refundtransaction_id = notification.get("pspReference")- payment = get_payment(notification.get("merchantReference"), transaction_id)+ payment = get_payment(+ notification.get("merchantReference"), transaction_id, check_if_active=False+ )if not payment:returntransaction = get_transaction(@@ -775,7 +803,9 @@ def handle_order_closed(notification: Dict[str, Any], gateway_config: GatewayCon"previously are automatically cancelled or refunded by Adyen.")return- payment = get_payment(notification.get("merchantReference"), psp_reference)+ payment = get_payment(+ notification.get("merchantReference"), psp_reference, check_if_active=False+ )if not payment:# We don't know anything about that payment@@ -785,12 +815,20 @@ def handle_order_closed(notification: Dict[str, Any], gateway_config: GatewayConif payment.order:logger.info(f"Order already created for payment: {payment.pk}")return++ adyen_partial_payments = get_or_create_adyen_partial_payments(notification, payment)+ if not payment.is_active:+ logger.info(+ "Immediately refund an Adyen payments: %s as payment %s is not active."+ )+ refund_partial_payments(adyen_partial_payments, config=gateway_config)+ return+checkout = payment.checkoutadyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]kind = TransactionKind.CAPTURE if adyen_auto_capture else TransactionKind.AUTH- adyen_partial_payments = get_or_create_adyen_partial_payments(notification, payment)try:order = handle_not_created_order(notification, payment, checkout, kind, get_plugins_manager()diff --git a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.pyindex f9476b4aab..39872d4a66 100644--- a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py+++ b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py@@ -133,11 +133,6 @@ def test_void_success(payment_txn_preauth):@pytest.mark.parametrize("is_active, charge_status, error",[- (False, ChargeStatus.NOT_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_REFUNDED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_REFUNDED, NO_LONGER_ACTIVE),(True, ChargeStatus.PARTIALLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),(True, ChargeStatus.FULLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),(True, ChargeStatus.PARTIALLY_REFUNDED, LACK_OF_SUCCESSFUL_TRANSACTION),diff --git a/saleor/payment/gateways/stripe/tests/conftest.py b/saleor/payment/gateways/stripe/tests/conftest.pyindex 7a39257fbf..067d273849 100644--- a/saleor/payment/gateways/stripe/tests/conftest.py+++ b/saleor/payment/gateways/stripe/tests/conftest.py@@ -37,6 +37,13 @@ def payment_stripe_for_checkout(checkout_with_items, address, shipping_method):return payment+def inactive_payment_stripe_for_checkout(payment_stripe_for_checkout):+ payment_stripe_for_checkout.is_active = False+ payment_stripe_for_checkout.save(update_fields=["is_active"])+ return payment_stripe_for_checkout++@pytest.fixturedef payment_stripe_for_order(payment_stripe_for_checkout, order_with_lines):payment_stripe_for_checkout.checkout = Nonediff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.pyindex 4b8fe6ece7..c8fd17d8cf 100644--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py@@ -80,6 +80,46 @@ def test_handle_successful_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+@patch("saleor.payment.gateway.refund")+def test_handle_successful_payment_intent_for_checkout_inactive_payment(+ refund_mock,+ wrapped_checkout_complete,+ inactive_payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+):+ payment = inactive_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()+ 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["status"] = SUCCESS_STATUS++ handle_successful_payment_intent(payment_intent, plugin.config, channel_USD.slug)+ payment.refresh_from_db()++ assert refund_mock.called+ assert not wrapped_checkout_complete.called++@patch("saleor.payment.gateway.refund")@patch("saleor.checkout.complete_checkout._get_order_data")def test_handle_successful_payment_intent_when_order_creation_raises_exception(@@ -429,6 +469,36 @@ def test_handle_authorized_payment_intent_for_checkout_with_payment_details(assert transaction.token == intent.id+@patch("saleor.payment.gateway.void")+def test_handle_authorized_payment_intent_for_checkout_inactive_payment(+ void_mock,+ inactive_payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+):+ payment = inactive_payment_stripe_for_checkout+ 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()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = AUTHORIZED_STATUS++ handle_authorized_payment_intent(payment_intent, plugin.config, channel_USD.slug)+ payment.refresh_from_db()++ assert void_mock.called++@patch("saleor.checkout.complete_checkout._get_order_data")@patch("saleor.payment.gateway.void")def test_handle_authorized_payment_intent_when_order_creation_raises_exception(@@ -696,6 +766,39 @@ def test_handle_processing_payment_intent_for_checkout(assert transaction.token == payment_intent.id+@patch(+ "saleor.payment.gateways.stripe.webhooks.complete_checkout", wraps=complete_checkout+)+def test_handle_processing_payment_intent_for_checkout_inactive_payment(+ wrapped_checkout_complete,+ inactive_payment_stripe_for_checkout,+ checkout_with_items,+ stripe_plugin,+ channel_USD,+):+ payment = inactive_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()+ payment_intent = StripeObject(id="ABC", last_response={})+ payment_intent["amount"] = price_to_minor_unit(payment.total, payment.currency)+ payment_intent["currency"] = payment.currency+ payment_intent["status"] = PROCESSING_STATUS++ handle_processing_payment_intent(payment_intent, plugin.config, channel_USD.slug)++ assert not wrapped_checkout_complete.called++@patch("saleor.checkout.complete_checkout._get_order_data")@patch("saleor.payment.gateway.void")@patch("saleor.payment.gateway.refund")diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.pyindex 3c4c31bde1..9ea7433fe8 100644--- a/saleor/payment/gateways/stripe/webhooks.py+++ b/saleor/payment/gateways/stripe/webhooks.py@@ -27,6 +27,7 @@ from ...utils import (create_transaction,gateway_postprocess,price_from_minor_unit,+ try_void_or_refund_inactive_payment,update_payment_charge_status,update_payment_method_details,)@@ -120,7 +121,7 @@ def _get_payment(payment_intent_id: str) -> Optional[Payment]:Prefetch("order", queryset=Order.objects.select_related("channel")),).select_for_update(of=("self",))- .filter(transactions__token=payment_intent_id, is_active=True)+ .filter(transactions__token=payment_intent_id).first())@@ -288,6 +289,18 @@ def handle_authorized_payment_intent(_update_payment_method_metadata(payment, payment_intent, gateway_config)update_payment_method_details_from_intent(payment, payment_intent)+ if not payment.is_active:+ transaction = _update_payment_with_new_transaction(+ payment,+ payment_intent,+ TransactionKind.AUTH,+ payment_intent.amount,+ payment_intent.currency,+ )+ manager = get_plugins_manager()+ try_void_or_refund_inactive_payment(payment, transaction, manager)+ return+if payment.order_id:if payment.charge_status == ChargeStatus.PENDING:_update_payment_with_new_transaction(@@ -352,6 +365,10 @@ def handle_processing_payment_intent(if _channel_slug_is_different_from_payment_channel_slug(channel_slug, payment):return+ if not payment.is_active:+ # we can't cancel/refund processing payment+ return+if payment.order_id:# Order already createdreturn@@ -384,6 +401,17 @@ def handle_successful_payment_intent(_update_payment_method_metadata(payment, payment_intent, gateway_config)update_payment_method_details_from_intent(payment, payment_intent)+ if not payment.is_active:+ transaction = _update_payment_with_new_transaction(+ payment,+ payment_intent,+ TransactionKind.CAPTURE,+ payment_intent.amount_received,+ payment_intent.currency,+ )+ try_void_or_refund_inactive_payment(payment, transaction, get_plugins_manager())+ return+if payment.order_id:if payment.charge_status in [ChargeStatus.PENDING, ChargeStatus.NOT_CHARGED]:capture_transaction = _update_payment_with_new_transaction(diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex b13dea71cf..8f975b4b58 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -191,7 +191,7 @@ class Payment(ModelWithMetadata):return Truedef can_void(self):- return self.is_active and self.not_charged and self.is_authorized+ return self.not_charged and self.is_authorizeddef can_refund(self):can_refund_charge_status = (@@ -199,7 +199,7 @@ class Payment(ModelWithMetadata):ChargeStatus.FULLY_CHARGED,ChargeStatus.PARTIALLY_REFUNDED,)- return self.is_active and self.charge_status in can_refund_charge_status+ return self.charge_status in can_refund_charge_statusdef can_confirm(self):return self.is_active and self.not_chargeddiff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.pyindex e02e258834..c255538f27 100644--- a/saleor/payment/tests/test_payment.py+++ b/saleor/payment/tests/test_payment.py@@ -370,17 +370,6 @@ def test_create_transaction_no_gateway_response(transaction_data):assert txn.gateway_response == {}- "func",- [gateway.authorize, gateway.capture, gateway.confirm, gateway.refund, gateway.void],-)-def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):- payment_dummy.is_active = False- with pytest.raises(PaymentError) as exc:- func(payment_dummy, "token")- assert exc.value.message == NOT_ACTIVE_PAYMENT_ERROR--@patch.object(PluginsManager, "capture_payment")@patch("saleor.order.actions.handle_fully_paid_order")def test_gateway_charge_failed(@@ -560,7 +549,7 @@ def test_can_void(payment_txn_preauth: Payment):assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGEDpayment_txn_preauth.is_active = False- assert not payment_txn_preauth.can_void()+ assert payment_txn_preauth.can_void()payment_txn_preauth.is_active = Trueassert payment_txn_preauth.can_void()diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.pynew file mode 100644index 0000000000..9c2cf6f68e--- /dev/null+++ b/saleor/payment/tests/test_utils.py@@ -0,0 +1,61 @@+from unittest.mock import patch++from ..utils import get_channel_slug_from_payment, try_void_or_refund_inactive_payment+++def test_get_channel_slug_from_payment_with_order(payment_dummy):+ expected = payment_dummy.order.channel.slug+ assert get_channel_slug_from_payment(payment_dummy) == expected+++def test_get_channel_slug_from_payment_with_checkout(checkout_with_payments):+ payment = checkout_with_payments.payments.first()+ expected = checkout_with_payments.channel.slug+ assert get_channel_slug_from_payment(payment) == expected+++def test_get_channel_slug_from_payment_without_checkout_and_order(+ checkout_with_payments,+):+ payment = checkout_with_payments.payments.first()+ payment.checkout.delete()+ payment.refresh_from_db()+ assert not get_channel_slug_from_payment(payment)+++@patch("saleor.payment.utils.update_payment_charge_status")+@patch("saleor.payment.utils.get_channel_slug_from_payment")+@patch("saleor.payment.gateway.payment_refund_or_void")+def test_try_void_or_refund_inactive_payment_failed_transaction(+ refund_or_void_mock,+ get_channel_slug_from_payment_mock,+ update_payment_charge_status_mock,+ payment_txn_capture_failed,+):+ transaction = payment_txn_capture_failed.transactions.first()++ assert not try_void_or_refund_inactive_payment(+ payment_txn_capture_failed, transaction, None+ )+ assert not update_payment_charge_status_mock.called+ assert not get_channel_slug_from_payment_mock.called+ assert not refund_or_void_mock.called+++@patch("saleor.payment.utils.update_payment_charge_status")+@patch("saleor.payment.utils.get_channel_slug_from_payment")+@patch("saleor.payment.gateway.payment_refund_or_void")+def test_try_void_or_refund_inactive_payment_transaction_success(+ refund_or_void_mock,+ get_channel_slug_from_payment_mock,+ update_payment_charge_status_mock,+ payment_txn_captured,+):+ transaction = payment_txn_captured.transactions.first()++ assert not try_void_or_refund_inactive_payment(+ payment_txn_captured, transaction, None+ )+ assert update_payment_charge_status_mock.called+ assert get_channel_slug_from_payment_mock.called+ assert refund_or_void_mock.calleddiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 01a4d4ed51..c6e168d0d9 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -19,6 +19,7 @@ from . import (PaymentError,StorePaymentMethod,TransactionKind,+ gateway,)from .error_codes import PaymentErrorCodefrom .interface import (@@ -468,6 +469,39 @@ def price_to_minor_unit(value: Decimal, currency: str):return str(value_without_comma.quantize(Decimal("1")))+def get_channel_slug_from_payment(payment: Payment) -> Optional[str]:+ channel_slug = None++ if payment.checkout:+ channel_slug = payment.checkout.channel.slug+ elif payment.order:+ channel_slug = payment.order.channel.slug++ return channel_slug+++def try_void_or_refund_inactive_payment(+ payment: Payment, transaction: Transaction, manager: "PluginsManager"+):+ """Handle refund or void inactive payments.++ In case when we have open multiple payments for single checkout but only one is+ active. Some payment methods don't required confirmation so we can receive delayed+ webhook when we have order already paid.+ """+ if transaction.is_success:+ update_payment_charge_status(payment, transaction)+ channel_slug = get_channel_slug_from_payment(payment)+ try:+ gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)+ except PaymentError:+ logger.exception(+ "Unable to void/refund an inactive payment %s, %s.",+ payment.id,+ payment.psp_reference,+ )++def payment_owned_by_user(payment_pk: int, user) -> bool:if user.is_anonymous:return False