Skip to content

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

Handle payment errors in process payment and refactor flow

Jakub Draganek4de65c5411e9
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 267ee20818..0d7ce70739 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ImproperlyConfigured
from ..core.payments import Gateway, PaymentInterface
from ..extensions.manager import get_extensions_manager
-from . import GatewayError, TransactionKind
+from . import GatewayError, TransactionKind, PaymentError
from .models import Payment, Transaction
from .utils import (
create_payment_information,
@@ -15,12 +15,35 @@ from .utils import (
)
logger = logging.getLogger(__name__)
+ERROR_MSG = "Oops! Something went wrong."
+GENERIC_TRANSACTION_ERROR = "Transaction was unsuccessful"
+
+
+def raise_payment_error(fn):
+ def wrapped(*args, **kwargs):
+ result = fn(*args, **kwargs)
+ if not result.is_success:
+ raise PaymentError(result.error or GENERIC_TRANSACTION_ERROR)
+ return result
+
+ return wrapped
+
+
+def payment_postprocess(fn):
+ def wrapped(*args, **kwargs):
+ txn = fn(*args, **kwargs)
+ _gateway_postprocess(txn, txn.payment)
+ return txn
+
+ return wrapped
class PaymentGateway:
def __init__(self):
self.plugin_manager: PaymentInterface = get_extensions_manager()
+ @raise_payment_error
+ @payment_postprocess
def process_payment(
self, payment: Payment, token: str, store_source: bool = False
) -> Transaction:
@@ -28,25 +51,16 @@ class PaymentGateway:
payment=payment, payment_token=token, store_source=store_source
)
gateway = _get_gateway(payment)
- txn, response = None, None
- try:
- response = self.plugin_manager.process_payment(gateway, payment_data)
- validate_gateway_response(response)
- except GatewayError:
- error_msg = "Gateway response validation failed"
- logger.exception(error_msg)
- response = None # Set response empty as the validation failed
- except Exception:
- error_msg = "Gateway encountered an error"
- logger.exception(error_msg)
- finally:
- txn = create_transaction(
- payment,
- kind=TransactionKind.CAPTURE,
- payment_information=payment_data,
- gateway_response=response,
- )
- _gateway_postprocess(txn, payment)
+ response, error = _fetch_gateway_response(
+ self.plugin_manager.process_payment, gateway, payment_data
+ )
+ txn = create_transaction(
+ payment=payment,
+ kind=TransactionKind.CAPTURE,
+ payment_information=payment_data,
+ error_msg=error,
+ gateway_response=response,
+ )
return txn
@@ -57,3 +71,19 @@ def _get_gateway(payment: Payment) -> Gateway:
raise ImproperlyConfigured("Payment gateway %s is not configured." % gateway)
return gateway
+
+
+def _fetch_gateway_response(fn, *args, **kwargs):
+ response, error = None, None
+ try:
+ response = fn(*args, **kwargs)
+ validate_gateway_response(response)
+ except GatewayError:
+ logger.exception("Gateway reponse validation failed!")
+ response = None
+ error = ERROR_MSG
+ except Exception:
+ logger.exception("Error encountered while executing payment gateway.")
+ error = ERROR_MSG
+ response = None
+ return response, error
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 9e207a8eef..d955b758ed 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -6,22 +6,24 @@ import graphene
import pytest
from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney
+from tests.api.utils import get_graphql_content
from saleor.checkout.error_codes import CheckoutErrorCode
from saleor.checkout.models import Checkout
from saleor.checkout.utils import clean_checkout, is_fully_paid
from saleor.core.taxes import zero_money
+from saleor.core.payments import PaymentInterface
from saleor.graphql.checkout.mutations import (
clean_shipping_method,
update_checkout_shipping_method_if_invalid,
)
from saleor.graphql.core.utils import str_to_enum
from saleor.order.models import Order
-from saleor.payment import PaymentError
+from saleor.payment import TransactionKind
+from saleor.payment.interface import GatewayResponse
from saleor.payment.models import Transaction
from saleor.shipping import ShippingMethodType
from saleor.shipping.models import ShippingMethod
-from tests.api.utils import get_graphql_content
@pytest.fixture
@@ -35,6 +37,11 @@ def other_shipping_method(shipping_zone):
)
[email protected](autouse=True)
+def setup_dummy_gateway(settings):
+ settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
+
+
def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(
checkout_with_single_item, address, shipping_method, other_shipping_method
):
@@ -1057,6 +1064,7 @@ def test_checkout_complete(
address,
shipping_method,
):
+
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
@@ -1085,6 +1093,7 @@ def test_checkout_complete(
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id}
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
assert not data["errors"]
@@ -1114,32 +1123,58 @@ def test_checkout_complete(
).exists(), "Checkout should have been deleted"
-def _process_payment_raise_error(*args, **kwargs):
- raise PaymentError("Oops! Something went wrong.")
+ERROR_GATEWAY_RESPONSE = GatewayResponse(
+ is_success=False,
+ action_required=False,
+ kind=TransactionKind.CAPTURE,
+ amount=0.0,
+ currency="usd",
+ transaction_id="1234",
+ error="ERROR",
+)
-def _process_payment_transaction_returns_error(*args, **kwargs):
- return Transaction(error="Oops! Something went wrong.", is_success=False)
+def _process_payment_transaction_returns_error(*args, **kwards):
+ return ERROR_GATEWAY_RESPONSE
+def _process_payment_raise_error(*args, **kwargs):
+ raise Exception("Oops! Something went wrong.")
- "side_effect",
- (_process_payment_raise_error, _process_payment_transaction_returns_error),
+ params=[_process_payment_raise_error, _process_payment_transaction_returns_error]
)
-@patch("saleor.graphql.checkout.mutations.gateway_process_payment")
+def error_side_effect(request):
+ return request.param
+
+
+def fake_manager(mocker):
+ return mocker.Mock(spec=PaymentInterface)
+
+
[email protected](autouse=True, scope="function")
+def mock_get_manager(mocker, fake_manager):
+ mgr = mocker.patch(
+ "saleor.payment.gateway.get_extensions_manager",
+ auto_spec=True,
+ return_value=fake_manager,
+ )
+ yield mgr
+ mgr.assert_called_once()
+
+
def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
- mocked_process_payment,
+ mock_get_manager,
+ error_side_effect,
user_api_client,
checkout_with_voucher,
voucher,
payment_dummy,
address,
shipping_method,
- side_effect,
):
+ mock_get_manager.process_payment.side_effect = error_side_effect
expected_voucher_usage_count = voucher.used
- mocked_process_payment.side_effect = side_effect
-
checkout = checkout_with_voucher
checkout.shipping_address = address
checkout.shipping_method = shipping_method
diff --git a/tests/api/test_checkout_digital.py b/tests/api/test_checkout_digital.py
index f19cb303b4..d5f2101b20 100644
--- a/tests/api/test_checkout_digital.py
+++ b/tests/api/test_checkout_digital.py
@@ -30,7 +30,7 @@ def checkout_with_digital_item(checkout, digital_content):
@pytest.fixture(autouse=True)
def enable_dummy_gateway(settings):
- settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin", ]
+ settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
return settings