Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Switch to PaymentGateway for process_payment in CheckoutComplete
Jakub Draganek19c8fd00a0dc
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.pyindex a999875d09..41849c6e26 100644--- a/saleor/extensions/manager.py+++ b/saleor/extensions/manager.py@@ -223,15 +223,18 @@ class ExtensionsManager(PaymentInterface):)def __run_payment_method(- self, gateway_name: str, method_name: str, payment_information: "PaymentData"+ self, gateway: str, method_name: str, payment_information: "PaymentData") -> Optional["GatewayResposne"]:default_value = None+ gateway_name = gateway.valuegtw = self.get_plugin(gateway_name)if gtw is not None and gtw.active:return self.__run_method_on_single_plugin(gtw, method_name, default_value, payment_information=payment_information)+ raise Exception(f"Payment plugin {gateway_name} is inaccessible!")+# FIXME these methods should be more genericdef assign_tax_code_to_object_meta(diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 99fe577edb..2346c525a4 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -30,8 +30,9 @@ from ...core.exceptions import InsufficientStockfrom ...core.taxes import TaxErrorfrom ...discount import models as voucher_modelfrom ...payment import PaymentError+from ...payment.gateway import PaymentGatewayfrom ...payment.interface import AddressData-from ...payment.utils import gateway_process_payment, store_customer_id+from ...payment.utils import store_customer_idfrom ...product import models as product_modelsfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInput, User@@ -642,6 +643,7 @@ class CheckoutComplete(BaseMutation):info, checkout_id, only_type=Checkout, field="checkout_id")+ gateway = PaymentGateway()user = info.context.userclean_checkout(checkout, info.context.discounts)@@ -678,12 +680,8 @@ class CheckoutComplete(BaseMutation):shipping_address = AddressData(**shipping_address.as_data())try:- txn = gateway_process_payment(- payment=payment,- payment_token=payment.token,- billing_address=billing_address,- shipping_address=shipping_address,- store_source=store_source,+ txn = gateway.process_payment(+ payment=payment, token=payment.token, store_source=store_source)if not txn.is_success:diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex 86ae902fac..89ef2297e7 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -1,7 +1,15 @@+import logging++from django.core.exceptions import ImproperlyConfigured+from ..core.payments import Gateway, PaymentInterfacefrom ..extensions.manager import get_extensions_manager++from . import GatewayError, TransactionKindfrom .models import Payment, Transaction-from .utils import create_payment_information, create_transaction+from .utils import create_payment_information, create_transaction, validate_gateway_response, _gateway_postprocess++logger = logging.getLogger(__name__)class PaymentGateway:@@ -9,15 +17,39 @@ class PaymentGateway:self.plugin_manager: PaymentInterface = get_extensions_manager()def process_payment(- self, gateway: Gateway, payment: Payment, token: str, store_source: bool = False+ self, payment: Payment, token: str, store_source: bool = False) -> Transaction:payment_data = create_payment_information(payment=payment, payment_token=token, store_source=store_source)- response = self.plugin_manager.process_payment(gateway, payment_data, token)- return create_transaction(- payment,- kind=response.kind,- payment_information=payment_data,- gateway_response=response,- )+ 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)+ return txn+++def _get_gateway(payment: Payment) -> Gateway:+ try:+ gateway = Gateway(payment.gateway)+ except AttributeError:+ raise ImproperlyConfigured(+ "Payment gateway %s is not configured." % gateway)++ return gatewaydiff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.pyindex e8f71366df..c9562af058 100644--- a/saleor/payment/gateways/dummy/plugin.py+++ b/saleor/payment/gateways/dummy/plugin.py@@ -15,7 +15,8 @@ if TYPE_CHECKING:class DummyGatewayPlugin(BasePlugin):- PLUGIN_NAME = "Dummy Gateway"+ #PLUGIN_NAME = "DUMMY_GATEWAY"+ PLUGIN_NAME = GATEWAY_NAMECONFIG_STRUCTURE = {"Store customers card": {"type": ConfigurationTypeField.BOOLEAN,diff --git a/tests/api/test_checkout_digital.py b/tests/api/test_checkout_digital.pyindex ac61a698eb..f19cb303b4 100644--- a/tests/api/test_checkout_digital.py+++ b/tests/api/test_checkout_digital.py@@ -28,6 +28,12 @@ def checkout_with_digital_item(checkout, digital_content):return checkout[email protected](autouse=True)+def enable_dummy_gateway(settings):+ settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin", ]+ return settings++@pytest.mark.parametrize("with_shipping_address", (True, False))def test_create_checkout(api_client, digital_content, graphql_address_data, with_shipping_addressdiff --git a/tests/conftest.py b/tests/conftest.pyindex 535f5a6424..73f74b2fb9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -80,6 +80,7 @@ def site_settings(db, settings):return obj+@pytest.fixturedef checkout(db):return Checkout.objects.create()diff --git a/tests/gateway/test_gateway.py b/tests/gateway/test_gateway.pyindex b5e0365139..aab3f05b6d 100644--- a/tests/gateway/test_gateway.py+++ b/tests/gateway/test_gateway.py@@ -20,6 +20,8 @@ PROCESS_PAYMENT_RESPONSE = GatewayResponse(error=None,raw_response=RAW_RESPONSE,)+TOKEN = "token"+USED_GATEWAY = Gateway.DUMMY@pytest.fixture@@ -38,21 +40,23 @@ def mock_get_manager(mocker, fake_manager):mgr.assert_called_once()-def test_process_payment(payment_txn_preauth):- TOKEN = "token"- USED_GATEWAY = Gateway.STRIPE- gateway = PaymentGateway()+def gateway():+ return PaymentGateway()+++def test_process_payment(gateway, payment_txn_preauth):PAYMENT_DATA = create_payment_information(payment=payment_txn_preauth, payment_token=TOKEN)gateway.plugin_manager.process_payment.return_value = PROCESS_PAYMENT_RESPONSEtransaction = gateway.process_payment(- payment=payment_txn_preauth, gateway=USED_GATEWAY, token=TOKEN+ payment=payment_txn_preauth, token=TOKEN)gateway.plugin_manager.process_payment.assert_called_once_with(- USED_GATEWAY, PAYMENT_DATA, TOKEN+ USED_GATEWAY, PAYMENT_DATA)assert transaction.amount == PROCESS_PAYMENT_RESPONSE.amountassert transaction.kind == TransactionKind.AUTH@@ -60,10 +64,7 @@ def test_process_payment(payment_txn_preauth):assert transaction.gateway_response == RAW_RESPONSE-def test_store_source_when_processing_payment(payment_txn_preauth):- TOKEN = "token"- USED_GATEWAY = Gateway.STRIPE- gateway = PaymentGateway()+def test_store_source_when_processing_payment(gateway, payment_txn_preauth):PAYMENT_DATA = create_payment_information(payment=payment_txn_preauth, payment_token=TOKEN, store_source=True)@@ -71,12 +72,11 @@ def test_store_source_when_processing_payment(payment_txn_preauth):transaction = gateway.process_payment(payment=payment_txn_preauth,- gateway=USED_GATEWAY,token=TOKEN,store_source=True,)gateway.plugin_manager.process_payment.assert_called_once_with(- USED_GATEWAY, PAYMENT_DATA, TOKEN+ USED_GATEWAY, PAYMENT_DATA)assert transaction.customer_id == PROCESS_PAYMENT_RESPONSE.customer_id