Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Show payment gateway in checkout based on checkout object (#5889)
Maciej Korycinskib6c7183b8fa6
diff --git a/saleor/core/payments.py b/saleor/core/payments.pyindex 4602a3a74f..9ae8c39164 100644--- a/saleor/core/payments.py+++ b/saleor/core/payments.py@@ -3,11 +3,13 @@ from typing import TYPE_CHECKING, List, Optionalif TYPE_CHECKING:# flake8: noqa- from saleor.payment.interface import (+ from ..checkout.models import Checkout+ from ..payment.interface import (PaymentData,GatewayResponse,TokenConfig,CustomerSource,+ PaymentGateway,)@@ -15,7 +17,13 @@ class PaymentInterface(ABC):@abstractmethoddef list_payment_gateways(self, currency: Optional[str] = None, active_only: bool = True- ) -> List[dict]:+ ) -> List["PaymentGateway"]:+ pass++ @abstractmethod+ def checkout_available_payment_gateways(+ self, checkout: "Checkout"+ ) -> List["PaymentGateway"]:pass@abstractmethoddiff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex b4ab2d85b5..aaee1681a2 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -109,8 +109,7 @@ def resolve_address_validation_rules(def resolve_payment_sources(user: models.User):stored_customer_accounts = (- (gtw["id"], fetch_customer_id(user, gtw["id"]))- for gtw in gateway.list_gateways()+ (gtw.id, fetch_customer_id(user, gtw.id)) for gtw in gateway.list_gateways())return list(chain(diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex f00047c552..ebaed7b76f 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -243,7 +243,7 @@ class Checkout(CountableDjangoObjectType):@staticmethoddef resolve_available_payment_gateways(root: models.Checkout, _info):- return get_plugins_manager().list_payment_gateways(currency=root.currency)+ return get_plugins_manager().checkout_available_payment_gateways(checkout=root)@staticmethoddef resolve_gift_cards(root: models.Checkout, _info):diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex b333f541ad..88a2fb57d4 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -18,7 +18,7 @@ from .utils import (if TYPE_CHECKING:# flake8: noqa- from ..payment.interface import CustomerSource+ from ..payment.interface import CustomerSource, PaymentGatewaylogger = logging.getLogger(__name__)@@ -202,7 +202,7 @@ def get_client_token(gateway: str, customer_id: str = None) -> str:return plugin_manager.get_client_token(gateway, token_config)-def list_gateways() -> List[dict]:+def list_gateways() -> List["PaymentGateway"]:return get_plugins_manager().list_payment_gateways()diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 7830f3428b..bbb78c7fde 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -1,6 +1,6 @@from dataclasses import dataclassfrom decimal import Decimal-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optional@dataclass@@ -101,3 +101,13 @@ class CustomerSource:id: strgateway: strcredit_card_info: Optional[CreditCardInfo] = None+++@dataclass+class PaymentGateway:+ """Dataclass for storing information about a payment gateway."""++ id: str+ name: str+ currencies: List[str]+ config: List[Dict[str, Any]]diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex f3e59fe486..9bda393a87 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -282,4 +282,4 @@ def get_payment_token(payment: Payment):def is_currency_supported(currency: str, gateway_id: str):"""Return true if the given gateway supports given currency."""available_gateways = get_plugins_manager().list_payment_gateways(currency=currency)- return any([gateway["id"] == gateway_id for gateway in available_gateways])+ return any([gateway.id == gateway_id for gateway in available_gateways])diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 48b5963ed5..29573dcbc7 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -7,6 +7,12 @@ from django.http import HttpResponsefrom django_countries.fields import Countryfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange+from ..payment.interface import (+ CustomerSource,+ GatewayResponse,+ PaymentData,+ PaymentGateway,+)from .models import PluginConfigurationif TYPE_CHECKING:@@ -18,7 +24,6 @@ if TYPE_CHECKING:from ..account.models import Address, Userfrom ..order.models import Fulfillment, OrderLine, Orderfrom ..invoice.models import Invoice- from ..payment.interface import GatewayResponse, PaymentData, CustomerSourcePluginConfigurationType = List[dict]@@ -391,6 +396,27 @@ class BasePlugin:def get_supported_currencies(self, previous_value):return NotImplemented+ def get_payment_gateway(+ self, currency: Optional[str], previous_value+ ) -> Optional["PaymentGateway"]:+ payment_config = self.get_payment_config(previous_value)+ payment_config = payment_config if payment_config != NotImplemented else []+ currencies = self.get_supported_currencies(previous_value=[])+ currencies = currencies if currencies != NotImplemented else []+ if currency and currency not in currencies:+ return None+ return PaymentGateway(+ id=self.PLUGIN_ID,+ name=self.PLUGIN_NAME,+ config=payment_config,+ currencies=currencies,+ )++ def get_payment_gateway_for_checkout(+ self, checkout: "Checkout", previous_value+ ) -> Optional["PaymentGateway"]:+ return self.get_payment_gateway(checkout.currency, previous_value)+@classmethoddef _update_config_items(cls, configuration_to_update: List[dict], current_config: List[dict]diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 02ff51ce4d..54ed3d0c00 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -17,8 +17,7 @@ from .models import PluginConfigurationif TYPE_CHECKING:# flake8: noqa- from django.db.models.query import QuerySet- from .base_plugin import BasePlugin, PluginConfigurationType+ from .base_plugin import BasePluginfrom ..checkout.models import Checkout, CheckoutLinefrom ..product.models import Product, ProductTypefrom ..account.models import Address, User@@ -29,6 +28,7 @@ if TYPE_CHECKING:TokenConfig,GatewayResponse,CustomerSource,+ PaymentGateway,)@@ -355,34 +355,28 @@ class PluginsManager(PaymentInterface):def list_payment_gateways(self, currency: Optional[str] = None, active_only: bool = True- ) -> List[dict]:+ ) -> List["PaymentGateway"]:payment_plugins = self.list_payment_plugin(active_only=active_only)# if currency is given return only gateways which support given currency- gateways = [- {- "id": plugin_id,- "name": plugin.PLUGIN_NAME,- "config": self.__get_payment_config(plugin),- "currencies": self.__get_payment_currencies(plugin),- }- for plugin_id, plugin in payment_plugins.items()- ]- if currency:- return [- gtw for gtw in gateways if currency in gtw["currencies"] # type: ignore- ]+ gateways = []+ for plugin in payment_plugins.values():+ gateway = plugin.get_payment_gateway(currency=currency, previous_value=None)+ if gateway:+ gateways.append(gateway)return gateways- def __get_payment_currencies(self, gateway: "BasePlugin") -> List[str]:- """Return gateway supported currencies."""- method_name = "get_supported_currencies"- default_value: list = []- return self.__run_method_on_single_plugin(gateway, method_name, default_value)-- def __get_payment_config(self, gateway: "BasePlugin") -> List[dict]:- method_name = "get_payment_config"- default_value: list = []- return self.__run_method_on_single_plugin(gateway, method_name, default_value)+ def checkout_available_payment_gateways(+ self, checkout: "Checkout"+ ) -> List["PaymentGateway"]:+ payment_plugins = self.list_payment_plugin(active_only=True)+ gateways = []+ for plugin in payment_plugins.values():+ gateway = plugin.get_payment_gateway_for_checkout(+ checkout, previous_value=None+ )+ if gateway:+ gateways.append(gateway)+ return gatewaysdef __run_payment_method(self,diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex c7096ed5e2..55ffc4367c 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -7,6 +7,7 @@ from django_countries.fields import Countryfrom prices import Money, TaxedMoneyfrom ...core.taxes import TaxType+from ...payment.interface import PaymentGatewayfrom ..manager import PluginsManager, get_plugins_managerfrom ..models import PluginConfigurationfrom ..tests.sample_plugins import (@@ -255,12 +256,12 @@ def test_plugin_add_new_configuration(def test_manager_serve_list_of_payment_gateways():- expected_gateway = {- "id": ActivePaymentGateway.PLUGIN_ID,- "name": ActivePaymentGateway.PLUGIN_NAME,- "config": ActivePaymentGateway.CLIENT_CONFIG,- "currencies": ActivePaymentGateway.SUPPORTED_CURRENCIES,- }+ expected_gateway = PaymentGateway(+ id=ActivePaymentGateway.PLUGIN_ID,+ name=ActivePaymentGateway.PLUGIN_NAME,+ config=ActivePaymentGateway.CLIENT_CONFIG,+ currencies=ActivePaymentGateway.SUPPORTED_CURRENCIES,+ )plugins = ["saleor.plugins.tests.sample_plugins.PluginSample","saleor.plugins.tests.sample_plugins.ActivePaymentGateway",@@ -272,18 +273,18 @@ def test_manager_serve_list_of_payment_gateways():def test_manager_serve_list_all_payment_gateways():expected_gateways = [- {- "id": ActivePaymentGateway.PLUGIN_ID,- "name": ActivePaymentGateway.PLUGIN_NAME,- "config": ActivePaymentGateway.CLIENT_CONFIG,- "currencies": ActivePaymentGateway.SUPPORTED_CURRENCIES,- },- {- "id": InactivePaymentGateway.PLUGIN_ID,- "name": InactivePaymentGateway.PLUGIN_NAME,- "config": [],- "currencies": [],- },+ PaymentGateway(+ id=ActivePaymentGateway.PLUGIN_ID,+ name=ActivePaymentGateway.PLUGIN_NAME,+ config=ActivePaymentGateway.CLIENT_CONFIG,+ currencies=ActivePaymentGateway.SUPPORTED_CURRENCIES,+ ),+ PaymentGateway(+ id=InactivePaymentGateway.PLUGIN_ID,+ name=InactivePaymentGateway.PLUGIN_NAME,+ config=[],+ currencies=[],+ ),]plugins = [@@ -296,12 +297,12 @@ def test_manager_serve_list_all_payment_gateways():def test_manager_serve_list_all_payment_gateways_specified_currency():expected_gateways = [- {- "id": ActiveDummyPaymentGateway.PLUGIN_ID,- "name": ActiveDummyPaymentGateway.PLUGIN_NAME,- "config": ActiveDummyPaymentGateway.CLIENT_CONFIG,- "currencies": ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,- },+ PaymentGateway(+ id=ActiveDummyPaymentGateway.PLUGIN_ID,+ name=ActiveDummyPaymentGateway.PLUGIN_NAME,+ config=ActiveDummyPaymentGateway.CLIENT_CONFIG,+ currencies=ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,+ )]plugins = [@@ -318,18 +319,18 @@ def test_manager_serve_list_all_payment_gateways_specified_currency():def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways():expected_gateways = [- {- "id": ActivePaymentGateway.PLUGIN_ID,- "name": ActivePaymentGateway.PLUGIN_NAME,- "config": ActivePaymentGateway.CLIENT_CONFIG,- "currencies": ActivePaymentGateway.SUPPORTED_CURRENCIES,- },- {- "id": ActiveDummyPaymentGateway.PLUGIN_ID,- "name": ActiveDummyPaymentGateway.PLUGIN_NAME,- "config": ActiveDummyPaymentGateway.CLIENT_CONFIG,- "currencies": ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,- },+ PaymentGateway(+ id=ActivePaymentGateway.PLUGIN_ID,+ name=ActivePaymentGateway.PLUGIN_NAME,+ config=ActivePaymentGateway.CLIENT_CONFIG,+ currencies=ActivePaymentGateway.SUPPORTED_CURRENCIES,+ ),+ PaymentGateway(+ id=ActiveDummyPaymentGateway.PLUGIN_ID,+ name=ActiveDummyPaymentGateway.PLUGIN_NAME,+ config=ActiveDummyPaymentGateway.CLIENT_CONFIG,+ currencies=ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,+ ),]plugins = [