Skip to content

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

Fix payment flow (#9504)

Iga Karbowiak0881beec1ac0
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index e74a331445..02eacf2ce3 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -44,7 +44,7 @@ from ..order.fetch import OrderInfo, OrderLineInfo
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
from ..order.search import prepare_order_search_document_value
-from ..payment import PaymentError, gateway
+from ..payment import PaymentError, TransactionKind, gateway
from ..payment.models import Payment, Transaction
from ..payment.utils import fetch_customer_id, store_customer_id
from ..product.models import ProductTranslation, ProductVariantTranslation
@@ -755,7 +755,7 @@ def complete_checkout(
)
order = None
- if not action_required:
+ if not action_required and not _is_refund_ongoing(payment):
try:
order = _create_order(
checkout_info=checkout_info,
@@ -789,6 +789,17 @@ def complete_checkout(
return order, action_required, action_data
+def _is_refund_ongoing(payment):
+ """Return True if refund is ongoing for given payment."""
+ return (
+ payment.transactions.filter(
+ kind=TransactionKind.REFUND_ONGOING, is_success=True
+ ).exists()
+ if payment
+ else False
+ )
+
+
def _get_order_total(
checkout_info: CheckoutInfo,
lines: List[CheckoutLineInfo],
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 01868be3a4..fb4c0e74d7 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -18,6 +18,7 @@ from ...graphql.checkout.tests.test_checkout_complete import (
from ...order import OrderEvents
from ...order.models import OrderEvent
from ...order.notifications import get_default_order_payload
+from ...payment import TransactionKind
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...product.models import ProductTranslation, ProductVariantTranslation
@@ -1254,3 +1255,54 @@ 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()
+
+
[email protected]("saleor.checkout.complete_checkout._create_order")
+def test_complete_checkout_order_not_created_when_the_refund_is_ongoing(
+ mocked_create_order,
+ customer_user,
+ checkout,
+ payment_txn_to_confirm,
+):
+ # given
+ payment = Payment.objects.create(
+ gateway="mirumee.payments.dummy", is_active=True, checkout=checkout
+ )
+ payment.to_confirm = False
+ payment.save()
+ payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.REFUND_ONGOING,
+ amount=payment.total,
+ currency=payment.currency,
+ token="test",
+ gateway_response={},
+ )
+
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order, _, _ = complete_checkout(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ )
+
+ # then
+ assert not order
+ mocked_create_order.assert_not_called()
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index a4e03c20c4..42d1a94369 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -344,11 +344,47 @@ def _validate_refund_amount(payment: Payment, amount: Decimal):
def payment_refund_or_void(
- payment: Optional[Payment], manager: "PluginsManager", channel_slug: Optional[str]
+ payment: Optional[Payment],
+ manager: "PluginsManager",
+ channel_slug: Optional[str],
+ transaction_id: Optional[str] = None,
):
if payment is None:
return
if payment.can_refund():
- refund(payment, manager, channel_slug=channel_slug)
+ refund_transaction = _get_success_transaction(
+ TransactionKind.REFUND_ONGOING, payment, transaction_id
+ )
+ # The refund should be called only if the refund process is not already started
+ # with amount equal payment captured amount.
+ # There is no need for summing the amount of all refund transactions,
+ # because we always called refund with the full amount that was captured.
+ # So if the refund wasn't called with current captured amount we should
+ # call refund again.
+ if (
+ not refund_transaction
+ or refund_transaction.amount < payment.captured_amount
+ ):
+ refund(payment, manager, channel_slug=channel_slug)
elif payment.can_void():
- void(payment, manager, channel_slug=channel_slug)
+ void_transaction = _get_success_transaction(
+ TransactionKind.VOID, payment, transaction_id
+ )
+ if not void_transaction:
+ void(payment, manager, channel_slug=channel_slug)
+
+
+def _get_success_transaction(
+ kind: str, payment: Payment, transaction_id: Optional[str]
+):
+ if not transaction_id:
+ try:
+ transaction_id = _get_past_transaction_token(payment, kind)
+ except PaymentError:
+ return
+ return payment.transactions.filter(
+ token=transaction_id,
+ action_required=False,
+ is_success=True,
+ kind=kind,
+ ).last()
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index 8e4cbb5574..07385d14fb 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -12,7 +12,7 @@ from ......checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ......order import OrderEvents, OrderStatus
from ......plugins.manager import get_plugins_manager
from ..... import ChargeStatus, TransactionKind
-from .....utils import price_to_minor_unit
+from .....utils import price_to_minor_unit, update_payment_charge_status
from ...webhooks import (
confirm_payment_and_set_back_to_confirm,
create_new_transaction,
@@ -337,18 +337,75 @@ def test_handle_authorization_with_adyen_auto_capture(
def test_handle_authorization_with_adyen_auto_capture_and_inactive_payment(
refund_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout
):
+ """
+ Ensure that the refund method is called and the new capture transaction is created,
+ when the payment is inactive and there is no success capture transaction for this
+ payment.
+ """
+ # given
payment = inactive_payment_adyen_for_checkout
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ assert payment.transactions.count() == 0
notification = notification(
merchant_reference=payment_id,
value=price_to_minor_unit(payment.total, payment.currency),
)
plugin = adyen_plugin(adyen_auto_capture=True)
+ # when
handle_authorization(notification, plugin.config)
+
+ # then
payment.refresh_from_db()
+ assert payment.transactions.count() == 1
+ txn = payment.transactions.first()
+ assert txn.kind == TransactionKind.CAPTURE
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.captured_amount == txn.amount
+ assert refund_mock.called
+
+@patch("saleor.payment.gateway.refund")
+def test_handle_authorization_adyen_auto_capture_inactive_payment_and_captured_txn(
+ refund_mock, notification, adyen_plugin, inactive_payment_adyen_for_checkout
+):
+ """
+ Ensure that the refund method is called and the new capture transaction
+ is not created, when the payment is inactive and already has capture transaction.
+ """
+ # given
+ payment = inactive_payment_adyen_for_checkout
+ psp_reference = "ABC"
+ txn = payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.CAPTURE,
+ amount=payment.total,
+ currency=payment.currency,
+ token=psp_reference,
+ gateway_response={},
+ )
+ update_payment_charge_status(payment, txn)
+ captured_amount = payment.captured_amount
+ assert payment.transactions.count() == 1
+
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ notification = notification(
+ psp_reference=psp_reference,
+ merchant_reference=payment_id,
+ value=price_to_minor_unit(payment.total, payment.currency),
+ )
+ plugin = adyen_plugin(adyen_auto_capture=True)
+
+ # when
+ handle_authorization(notification, plugin.config)
+
+ # then
+ payment.refresh_from_db()
+ assert payment.transactions.count() == 1
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.captured_amount == captured_amount
assert refund_mock.called
@@ -578,18 +635,77 @@ def test_handle_capture_inactive_payment(
address,
shipping_method,
):
+ """
+ Ensure that the refund method is called and the new capture transaction is created,
+ when the payment is inactive and there is no success capture transaction for this
+ payment.
+ """
+ # given
payment = inactive_payment_adyen_for_checkout
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ assert payment.transactions.count() == 0
notification = notification(
merchant_reference=payment_id,
value=price_to_minor_unit(payment.total, payment.currency),
)
config = adyen_plugin().config
+ # when
handle_capture(notification, config)
+
+ # then
payment.refresh_from_db()
+ assert payment.transactions.count() == 1
+ txn = payment.transactions.first()
+ assert txn.kind == TransactionKind.CAPTURE
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.captured_amount == txn.amount
+ assert refund_mock.called
+
+@patch("saleor.payment.gateway.refund")
+def test_handle_capture_inactive_payment_capture_txn_exists(
+ refund_mock,
+ notification,
+ adyen_plugin,
+ inactive_payment_adyen_for_checkout,
+ address,
+ shipping_method,
+):
+ """
+ Ensure that the refund method is called and the new capture transaction
+ is not created, when the payment is inactive and already has capture transaction.
+ """
+ # given
+ payment = inactive_payment_adyen_for_checkout
+ psp_reference = "ABC"
+ txn = payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.CAPTURE,
+ amount=payment.total,
+ currency=payment.currency,
+ token=psp_reference,
+ gateway_response={},
+ )
+ update_payment_charge_status(payment, txn)
+ captured_amount = payment.captured_amount
+ assert payment.transactions.count() == 1
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+ notification = notification(
+ psp_reference=psp_reference,
+ merchant_reference=payment_id,
+ value=price_to_minor_unit(payment.total, payment.currency),
+ )
+ config = adyen_plugin().config
+
+ # when
+ handle_capture(notification, config)
+
+ # then
+ assert payment.transactions.count() == 1
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.captured_amount == captured_amount
assert refund_mock.called
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index ec20550147..b1138d713f 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -44,6 +44,7 @@ from ....order.actions import (
from ....order.events import external_notification_event
from ....order.fetch import fetch_order_info
from ....payment.models import Payment, Transaction
+from ....payment.utils import update_payment_charge_status
from ....plugins.manager import get_plugins_manager
from ... import ChargeStatus, PaymentError, TransactionKind, gateway
from ...gateway import payment_refund_or_void
@@ -126,6 +127,25 @@ def get_transaction(
return transaction
+def _get_or_create_transaction(
+ payment: "Payment",
+ transaction_id: Optional[str],
+ allowed_kinds: Iterable[str],
+ kind: str,
+ notification,
+):
+ transaction = payment.transactions.filter(
+ token=transaction_id,
+ action_required=False,
+ is_success=True,
+ kind__in=allowed_kinds,
+ ).last()
+ if not transaction:
+ transaction = create_new_transaction(notification, payment, kind)
+ update_payment_charge_status(payment, transaction)
+ return transaction
+
+
def create_new_transaction(notification, payment, kind):
transaction_id = notification.get("pspReference")
currency = notification.get("amount", {}).get("currency")
@@ -296,7 +316,15 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
return
if not payment.is_active:
- transaction = create_new_transaction(notification, payment, kind)
+ # the `CAPTURE`` transaction should be created only when `AUTH` or `CAPTURE`
+ # transaction does not exist yet
+ transaction = _get_or_create_transaction(
+ payment,
+ transaction_id,
+ [TransactionKind.AUTH, TransactionKind.CAPTURE],
+ kind,
+ notification,
+ )
try_void_or_refund_inactive_payment(payment, transaction, manager)
return
@@ -406,8 +434,14 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
manager = get_plugins_manager()
if not payment.is_active:
- transaction = create_new_transaction(
- notification, payment, TransactionKind.CAPTURE
+ # the `CAPTURE`` transaction should be created only when `CAPTURE`
+ # transaction does not exist yet
+ transaction = _get_or_create_transaction(
+ payment,
+ transaction_id,
+ [TransactionKind.CAPTURE],
+ TransactionKind.CAPTURE,
+ notification,
)
try_void_or_refund_inactive_payment(payment, transaction, manager)
return
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 9ea7433fe8..08c06cc1aa 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -210,6 +210,22 @@ def _finalize_checkout(
return None
+def _get_or_create_transaction(
+ payment: Payment, stripe_object: StripeObject, kind: str, amount: str, currency: str
+):
+ transaction = payment.transactions.filter(
+ token=stripe_object.id,
+ action_required=False,
+ is_success=True,
+ kind=kind,
+ ).last()
+ if not transaction:
+ transaction = _update_payment_with_new_transaction(
+ payment, stripe_object, kind, amount, currency
+ )
+ return transaction
+
+
def _update_payment_with_new_transaction(
payment: Payment, stripe_object: StripeObject, kind: str, amount: str, currency: str
):
@@ -290,7 +306,7 @@ def handle_authorized_payment_intent(
update_payment_method_details_from_intent(payment, payment_intent)
if not payment.is_active:
- transaction = _update_payment_with_new_transaction(
+ transaction = _get_or_create_transaction(
payment,
payment_intent,
TransactionKind.AUTH,
@@ -402,7 +418,7 @@ def handle_successful_payment_intent(
update_payment_method_details_from_intent(payment, payment_intent)
if not payment.is_active:
- transaction = _update_payment_with_new_transaction(
+ transaction = _get_or_create_transaction(
payment,
payment_intent,
TransactionKind.CAPTURE,
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 043bbe7a46..8d47a9849a 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from ...plugins.manager import get_plugins_manager
from .. import ChargeStatus, CustomPaymentChoices, TransactionKind, gateway
@@ -313,3 +313,166 @@ def test_list_gateways(fake_payment_interface):
lst = gateway.list_gateways(fake_payment_interface)
fake_payment_interface.list_payment_gateways.assert_called_once()
assert lst == gateways
+
+
+@patch("saleor.payment.gateway.void")
+@patch("saleor.payment.gateway.refund")
+def test_payment_refund_or_void_no_payment(refund_mock, void_mock):
+ """Ensure that either refund or void method is not called when
+ there is no payment object."""
+ # when
+ gateway.payment_refund_or_void(None, get_plugins_manager(), None)
+
+ # then
+ refund_mock.assert_not_called()
+ void_mock.assert_not_called()
+
+
+@patch("saleor.payment.gateway.refund")
+def test_payment_refund_or_void_refund_called(refund_mock, payment):
+ """Ensure that the refund method is called when payment can be refunded
+ and there is no refund transaction."""
+ # given
+ payment.transactions.count() == 0
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.save(update_fields=["charge_status"])
+
+ # when
+ gateway.payment_refund_or_void(payment, get_plugins_manager(), None)
+
+ # then
+ assert refund_mock.called_once()
+
+
+@patch("saleor.payment.gateway.refund")
+def test_payment_refund_or_void_refund_not_called_refund_already_started(
+ refund_mock, payment
+):
+ """Ensure that the refund method is not called when the refund process
+ is already ongoing - there is a `REFUND_ONGOING` transaction with
+ the given transaction_id."""
+ # given
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.save(update_fields=["charge_status"])
+
+ assert payment.can_refund() is True
+
+ payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.REFUND_ONGOING,
+ amount=payment.total,
+ currency=payment.currency,
+ token="test",
+ gateway_response={},
+ )
+
+ # when
+ gateway.payment_refund_or_void(payment, get_plugins_manager(), None)
+
+ # then
+ refund_mock.assert_not_called()
+
+
+@patch("saleor.payment.gateway.refund")
+def test_payment_refund_or_void_refund_called_txn_exist(refund_mock, payment):
+ """Ensure that the refund method is called when the refund process
+ is already ongoing but not covered full payment captured amount."""
+ # given
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.save(update_fields=["charge_status"])
+ assert payment.can_refund() is True
+ payment.captured_amount = payment.total
+ payment.save(update_fields=["captured_amount"])
+ txn = payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.REFUND_ONGOING,
+ amount=payment.captured_amount / 2,
+ currency=payment.currency,
+ token="test",
+ gateway_response={},
+ )
+
+ # when
+ gateway.payment_refund_or_void(
+ payment, get_plugins_manager(), None, transaction_id=txn.token
+ )
+
+ # then
+ assert refund_mock.called_once()
+
+
+@patch("saleor.payment.gateway.refund")
+def test_payment_refund_or_void_refund_called_no_txn_with_given_transaction_id(
+ refund_mock, payment
+):
+ """Ensure that the refund method is called when payment has the refund ongoing
+ transaction but with different transaction_id that was provided."""
+ # given
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.save(update_fields=["charge_status"])
+ assert payment.can_refund() is True
+ payment.captured_amount = payment.total
+ payment.save(update_fields=["captured_amount"])
+ payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.REFUND_ONGOING,
+ amount=payment.captured_amount,
+ currency=payment.currency,
+ token="test",
+ gateway_response={},
+ )
+
+ # when
+ gateway.payment_refund_or_void(
+ payment, get_plugins_manager(), None, transaction_id="another value"
+ )
+
+ # then
+ assert refund_mock.called_once()
+
+
+@patch("saleor.payment.gateway.void")
+def test_payment_refund_or_void_void_called(void_mock, payment):
+ """Ensure that the refund method is called when payment can be voided
+ and there is no void transaction for given payment."""
+ # given
+ payment.can_void = Mock(return_value=True)
+ assert payment.can_void() is True
+ payment.transactions.count() == 0
+
+ # when
+ gateway.payment_refund_or_void(payment, get_plugins_manager(), None)
+
+ # then
+ assert void_mock.called_once()
+
+
+@patch("saleor.payment.gateway.void")
+def test_payment_refund_or_void_void_not_called_txn_exist(void_mock, payment):
+ """Ensure that void method is not called when VOID transaction already exists with
+ given transaction_id."""
+ # given
+ payment.can_void = Mock(return_value=True)
+ assert payment.can_refund() is False
+ assert payment.can_void() is True
+
+ txn = payment.transactions.create(
+ is_success=True,
+ action_required=False,
+ kind=TransactionKind.VOID,
+ amount=payment.total,
+ currency=payment.currency,
+ token="test",
+ gateway_response={},
+ )
+
+ # when
+ gateway.payment_refund_or_void(
+ payment, get_plugins_manager(), None, transaction_id=txn.token
+ )
+
+ # then
+ void_mock.assert_not_called()
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 50cab7d7ca..b166eb6415 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -201,13 +201,11 @@ def test_try_void_or_refund_inactive_payment_failed_transaction(
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()
@@ -215,6 +213,5 @@ def test_try_void_or_refund_inactive_payment_transaction_success(
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.called
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 2a9e5ada9f..2011d1a4a4 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -594,10 +594,14 @@ def try_void_or_refund_inactive_payment(
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)
+ gateway.payment_refund_or_void(
+ payment,
+ manager,
+ channel_slug=channel_slug,
+ transaction_id=transaction.token,
+ )
except PaymentError:
logger.exception(
"Unable to void/refund an inactive payment %s, %s.",