Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add supported currencies to payment gateways
IKarbowiakef135f2de6de
diff --git a/saleor/core/payments.py b/saleor/core/payments.pyindex f4f6d70029..4602a3a74f 100644--- a/saleor/core/payments.py+++ b/saleor/core/payments.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from typing import TYPE_CHECKING, List+from typing import TYPE_CHECKING, List, Optionalif TYPE_CHECKING:# flake8: noqa@@ -13,7 +13,9 @@ if TYPE_CHECKING:class PaymentInterface(ABC):@abstractmethod- def list_payment_gateways(self, active_only: bool = True) -> List[dict]:+ def list_payment_gateways(+ self, currency: Optional[str] = None, active_only: bool = True+ ) -> List[dict]:pass@abstractmethoddiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex d330329c19..87c0e56929 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1,4 +1,5 @@import uuid+import warningsfrom decimal import Decimalfrom unittest import mockfrom unittest.mock import ANY, patch@@ -556,7 +557,10 @@ def expected_dummy_gateway():return {"id": "mirumee.payments.dummy","name": "Dummy",- "config": [{"field": "store_customer_card", "value": "false"}],+ "config": [+ {"field": "store_customer_card", "value": "false"},+ {"field": "supported_currencies", "value": "['USD']"},+ ],}@@ -577,8 +581,13 @@ def test_checkout_available_payment_gateways(}}"""+ expected_warning = "Default currency for Dummy is used."variables = {"token": str(checkout_with_item.token)}- response = api_client.post_graphql(query, variables)+ with warnings.catch_warnings(record=True) as warns:+ response = api_client.post_graphql(query, variables)++ assert any([str(warning.message) == expected_warning for warning in warns])+content = get_graphql_content(response)data = content["data"]["checkout"]assert data["availablePaymentGateways"] == [expected_dummy_gateway]diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 0654df5161..47d6c8f8ce 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1167,6 +1167,7 @@ input ConfigurationItemInput {enum ConfigurationTypeFieldEnum {STRINGBOOLEAN+ LISTSECRETPASSWORD}diff --git a/saleor/payment/gateways/braintree/plugin.py b/saleor/payment/gateways/braintree/plugin.pyindex 9487061f68..4472b84da3 100644--- a/saleor/payment/gateways/braintree/plugin.py+++ b/saleor/payment/gateways/braintree/plugin.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Listfrom saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField+from ..utils import get_supported_currenciesfrom . import (GatewayConfig,authorize,@@ -42,6 +43,7 @@ class BraintreeGatewayPlugin(BasePlugin):{"name": "Store customers card", "value": False},{"name": "Automatic payment capture", "value": True},{"name": "Require 3D secure", "value": False},+ {"name": "Supported currencies", "value": []},]CONFIG_STRUCTURE = {@@ -81,6 +83,11 @@ class BraintreeGatewayPlugin(BasePlugin):"help_text": "Determines if Saleor should enforce 3D secure during payment.","label": "Require 3D secure",},+ "Supported currencies": {+ "type": ConfigurationTypeField.LIST,+ "help_text": "Determines currencies supported by gateway",+ "label": "Supported currencies",+ },}def __init__(self, *args, **kwargs):@@ -89,6 +96,7 @@ class BraintreeGatewayPlugin(BasePlugin):self.config = GatewayConfig(gateway_name=GATEWAY_NAME,auto_capture=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],connection_params={"sandbox_mode": configuration["Use sandbox"],"merchant_id": configuration["Merchant ID"],@@ -147,7 +155,9 @@ class BraintreeGatewayPlugin(BasePlugin):@require_active_plugindef get_payment_config(self, previous_value):config = self._get_gateway_config()+ currencies = get_supported_currencies(config, GATEWAY_NAME)return [{"field": "store_customer_card", "value": config.store_customer},{"field": "client_token", "value": get_client_token(config=config)},+ {"field": "supported_currencies", "value": currencies},]diff --git a/saleor/payment/gateways/braintree/tests/test_braintree.py b/saleor/payment/gateways/braintree/tests/test_braintree.pyindex e4283e9ef3..95e789b3ba 100644--- a/saleor/payment/gateways/braintree/tests/test_braintree.py+++ b/saleor/payment/gateways/braintree/tests/test_braintree.py@@ -84,6 +84,7 @@ def gateway_config():"public_key": "456","private_key": "789",},+ supported_currencies=["USD"],)diff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.pyindex b08db07883..04f9217b19 100644--- a/saleor/payment/gateways/dummy/plugin.py+++ b/saleor/payment/gateways/dummy/plugin.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKINGfrom saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField+from ..utils import get_supported_currenciesfrom . import (GatewayConfig,authorize,@@ -36,6 +37,7 @@ class DummyGatewayPlugin(BasePlugin):DEFAULT_CONFIGURATION = [{"name": "Store customers card", "value": False},{"name": "Automatic payment capture", "value": True},+ {"name": "Supported currencies", "value": []},]CONFIG_STRUCTURE = {"Store customers card": {@@ -48,6 +50,11 @@ class DummyGatewayPlugin(BasePlugin):"help_text": "Determines if Saleor should automaticaly capture payments.","label": "Automatic payment capture",},+ "Supported currencies": {+ "type": ConfigurationTypeField.LIST,+ "help_text": "Determines currencies supported by gateway",+ "label": "Supported currencies",+ },}def __init__(self, *args, **kwargs):@@ -56,6 +63,7 @@ class DummyGatewayPlugin(BasePlugin):self.config = GatewayConfig(gateway_name=GATEWAY_NAME,auto_capture=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],connection_params={},store_customer=configuration["Store customers card"],)@@ -106,4 +114,8 @@ class DummyGatewayPlugin(BasePlugin):@require_active_plugindef get_payment_config(self, previous_value):config = self._get_gateway_config()- return [{"field": "store_customer_card", "value": config.store_customer}]+ currencies = get_supported_currencies(config, GATEWAY_NAME)+ return [+ {"field": "store_customer_card", "value": config.store_customer},+ {"field": "supported_currencies", "value": currencies},+ ]diff --git a/saleor/payment/gateways/razorpay/plugin.py b/saleor/payment/gateways/razorpay/plugin.pyindex 1f883fcdc3..50ef747df9 100644--- a/saleor/payment/gateways/razorpay/plugin.py+++ b/saleor/payment/gateways/razorpay/plugin.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKINGfrom saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField+from ..utils import get_supported_currenciesfrom . import GatewayConfig, capture, process_payment, refundGATEWAY_NAME = "Razorpay"@@ -28,6 +29,7 @@ class RazorpayGatewayPlugin(BasePlugin):{"name": "Secret API key", "value": None},{"name": "Store customers card", "value": False},{"name": "Automatic payment capture", "value": True},+ {"name": "Supported currencies", "value": []},]CONFIG_STRUCTURE = {@@ -52,6 +54,11 @@ class RazorpayGatewayPlugin(BasePlugin):"help_text": "Determines if Saleor should automaticaly capture payments.","label": "Automatic payment capture",},+ "Supported currencies": {+ "type": ConfigurationTypeField.LIST,+ "help_text": "Determines currencies supported by gateway",+ "label": "Supported currencies",+ },}def __init__(self, *args, **kwargs):@@ -60,6 +67,7 @@ class RazorpayGatewayPlugin(BasePlugin):self.config = GatewayConfig(gateway_name=GATEWAY_NAME,auto_capture=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],connection_params={"public_key": configuration["Public API key"],"private_key": configuration["Secret API key"],@@ -94,4 +102,8 @@ class RazorpayGatewayPlugin(BasePlugin):@require_active_plugindef get_payment_config(self, previous_value):config = self._get_gateway_config()- return [{"field": "api_key", "value": config.connection_params["public_key"]}]+ currencies = get_supported_currencies(config, GATEWAY_NAME)+ return [+ {"field": "api_key", "value": config.connection_params["public_key"]},+ {"field": "supported_currencies", "value": currencies},+ ]diff --git a/saleor/payment/gateways/razorpay/tests/test_razorpay.py b/saleor/payment/gateways/razorpay/tests/test_razorpay.pyindex 733f605bc7..4ad625378d 100644--- a/saleor/payment/gateways/razorpay/tests/test_razorpay.py+++ b/saleor/payment/gateways/razorpay/tests/test_razorpay.py@@ -27,6 +27,7 @@ def gateway_config():return GatewayConfig(gateway_name="razorpay",auto_capture=False,+ supported_currencies=["USD"],connection_params={"public_key": "public","private_key": "secret",diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.pyindex 43852e1e8f..d67b856089 100644--- a/saleor/payment/gateways/stripe/plugin.py+++ b/saleor/payment/gateways/stripe/plugin.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Listfrom saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField+from ..utils import get_supported_currenciesfrom . import (GatewayConfig,authorize,@@ -38,6 +39,7 @@ class StripeGatewayPlugin(BasePlugin):{"name": "Secret API key", "value": None},{"name": "Store customers card", "value": False},{"name": "Automatic payment capture", "value": True},+ {"name": "Supported currencies", "value": []},]CONFIG_STRUCTURE = {@@ -62,6 +64,11 @@ class StripeGatewayPlugin(BasePlugin):"help_text": "Determines if Saleor should automaticaly capture payments.","label": "Automatic payment capture",},+ "Supported currencies": {+ "type": ConfigurationTypeField.LIST,+ "help_text": "Determines currencies supported by gateway",+ "label": "Supported currencies",+ },}def __init__(self, *args, **kwargs):@@ -70,6 +77,7 @@ class StripeGatewayPlugin(BasePlugin):self.config = GatewayConfig(gateway_name=GATEWAY_NAME,auto_capture=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],connection_params={"public_key": configuration["Public API key"],"private_key": configuration["Secret API key"],@@ -121,7 +129,9 @@ class StripeGatewayPlugin(BasePlugin):@require_active_plugindef get_payment_config(self, previous_value):config = self._get_gateway_config()+ currencies = get_supported_currencies(config, GATEWAY_NAME)return [{"field": "api_key", "value": config.connection_params["public_key"]},{"field": "store_customer_card", "value": config.store_customer},+ {"field": "supported_currencies", "value": currencies},]diff --git a/saleor/payment/gateways/stripe/tests/test_stripe.py b/saleor/payment/gateways/stripe/tests/test_stripe.pyindex 39f1043539..af854f15aa 100644--- a/saleor/payment/gateways/stripe/tests/test_stripe.py+++ b/saleor/payment/gateways/stripe/tests/test_stripe.py@@ -37,6 +37,7 @@ def gateway_config():return GatewayConfig(gateway_name="stripe",auto_capture=True,+ supported_currencies=["USD"],connection_params={"public_key": "public","private_key": "secret",diff --git a/saleor/payment/gateways/utils.py b/saleor/payment/gateways/utils.pynew file mode 100644index 0000000000..83fbe24134--- /dev/null+++ b/saleor/payment/gateways/utils.py@@ -0,0 +1,16 @@+import warnings+from typing import TYPE_CHECKING, List++from django.conf import settings++if TYPE_CHECKING:+ from ..interface import GatewayConfig+++def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]:+ currencies = config.supported_currencies+ print(config)+ if not currencies:+ currencies = [settings.DEFAULT_CURRENCY]+ warnings.warn(f"Default currency for {gateway_name} is used.")+ return currenciesdiff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 2335a22bee..6ef7296f76 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@@ -86,6 +86,7 @@ class GatewayConfig:gateway_name: strauto_capture: bool+ supported_currencies: List[str]# Each gateway has different connection data so we are not able to create# a unified structureconnection_params: Dict[str, Any]diff --git a/saleor/payment/tests/test_gateways_utils.py b/saleor/payment/tests/test_gateways_utils.pynew file mode 100644index 0000000000..79964d0fe1--- /dev/null+++ b/saleor/payment/tests/test_gateways_utils.py@@ -0,0 +1,39 @@+import warnings++import pytest++from ..gateways.utils import get_supported_currencies+from ..interface import GatewayConfig+++def gateway_config():+ return GatewayConfig(+ gateway_name="Dummy",+ auto_capture=True,+ supported_currencies=[],+ connection_params={"secret-key": "dummy"},+ )+++def test_get_supported_currencies(gateway_config):+ # given+ gateway_config.supported_currencies = ["PLN", "USD"]++ # when+ currencies = get_supported_currencies(gateway_config, "Test")++ # then+ assert currencies == ["PLN", "USD"]+++def test_get_supported_currencies_default_currency(gateway_config):+ # when+ with warnings.catch_warnings(record=True) as warns:+ currencies = get_supported_currencies(gateway_config, "Test")++ expected_warning = "Default currency for Test is used."+ assert any([str(warning.message) == expected_warning for warning in warns])++ # then+ assert currencies == ["USD"]diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.pyindex 3e03ebc36a..7f443f141b 100644--- a/saleor/payment/tests/test_payment.py+++ b/saleor/payment/tests/test_payment.py@@ -64,6 +64,7 @@ def gateway_config():return GatewayConfig(gateway_name="Dummy",auto_capture=True,+ supported_currencies=["USD"],connection_params={"secret-key": "nobodylikesspanishinqusition"},)diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 845f871436..23937c2d52 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -24,11 +24,13 @@ PluginConfigurationType = List[dict]class ConfigurationTypeField:STRING = "String"BOOLEAN = "Boolean"+ LIST = "List"SECRET = "Secret"PASSWORD = "Password"CHOICES = [(STRING, "Field is a String"),(BOOLEAN, "Field is a Boolean"),+ (LIST, "Field is a List"),(SECRET, "Field is a Secret"),(PASSWORD, "Field is a Password"),]diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex cbcef48f2e..cb00ceba81 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1,5 +1,5 @@from decimal import Decimal-from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Union+from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Unionimport opentracingfrom django.conf import settings@@ -320,8 +320,15 @@ class PluginsManager(PaymentInterface):if payment_method in type(plugin).__dict__]- def list_payment_gateways(self, active_only: bool = True) -> List[dict]:+ def list_payment_gateways(+ self, currency: Optional[str] = None, active_only: bool = True+ ) -> List[dict]:payment_plugins = self.list_payment_plugin_names(active_only=active_only)+ # if currency is given return only gateways which support given currency+ if currency:+ return self.__get_payment_gateways_for_specific_currency(+ currency, payment_plugins+ )return [{"id": plugin_id,@@ -331,6 +338,23 @@ class PluginsManager(PaymentInterface):for plugin_id, plugin_name in payment_plugins]+ def __get_payment_gateways_for_specific_currency(+ self, currency: str, payment_plugins: List[tuple]+ ) -> List[dict]:+ """Return only gateways which support given currency."""+ gateways = []+ for plugin_id, plugin_name in payment_plugins:+ config = self.__get_payment_config(plugin_id)+ for item in config:+ if (+ item["field"] == "supported_currencies"+ and currency in item["value"]+ ):+ gateways.append(+ {"id": plugin_id, "name": plugin_name, "config": config}+ )+ return gateways+def __get_payment_config(self, gateway: str) -> List[dict]:method_name = "get_payment_config"default_value: list = []diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.pyindex 26666b2d43..561d42406b 100644--- a/saleor/plugins/tests/sample_plugins.py+++ b/saleor/plugins/tests/sample_plugins.py@@ -109,7 +109,10 @@ class ActivePlugin(BasePlugin):class ActivePaymentGateway(BasePlugin):PLUGIN_ID = "gateway.active"- CLIENT_CONFIG = [{"field": "foo", "value": "bar"}]+ CLIENT_CONFIG = [+ {"field": "foo", "value": "bar"},+ {"field": "supported_currencies", "value": ["USD"]},+ ]PLUGIN_NAME = "braintree"DEFAULT_ACTIVE = True@@ -120,6 +123,22 @@ class ActivePaymentGateway(BasePlugin):return self.CLIENT_CONFIG+class ActiveDummyPaymentGateway(BasePlugin):+ PLUGIN_ID = "dummy.active"+ CLIENT_CONFIG = [+ {"field": "foo", "value": "bar"},+ {"field": "supported_currencies", "value": ["PLN", "USD"]},+ ]+ PLUGIN_NAME = "dummy"+ DEFAULT_ACTIVE = True++ def process_payment(self, payment_information, previous_value):+ pass++ def get_payment_config(self, previous_value):+ return self.CLIENT_CONFIG++class InactivePaymentGateway(BasePlugin):PLUGIN_ID = "gateway.inactive"PLUGIN_NAME = "stripe"diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex 76172ec172..6069d81c74 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -8,6 +8,7 @@ from ...core.taxes import TaxTypefrom ..manager import PluginsManager, get_plugins_managerfrom ..models import PluginConfigurationfrom ..tests.sample_plugins import (+ ActiveDummyPaymentGateway,ActivePaymentGateway,InactivePaymentGateway,PluginInactive,@@ -286,3 +287,50 @@ def test_manager_serve_list_all_payment_gateways():]manager = PluginsManager(plugins=plugins)assert manager.list_payment_gateways(active_only=False) == expected_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,+ },+ ]++ plugins = [+ "saleor.plugins.tests.sample_plugins.ActivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.InactivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.ActiveDummyPaymentGateway",+ ]+ manager = PluginsManager(plugins=plugins)+ assert (+ manager.list_payment_gateways(currency="PLN", active_only=False)+ == expected_gateways+ )+++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,+ },+ {+ "id": ActiveDummyPaymentGateway.PLUGIN_ID,+ "name": ActiveDummyPaymentGateway.PLUGIN_NAME,+ "config": ActiveDummyPaymentGateway.CLIENT_CONFIG,+ },+ ]++ plugins = [+ "saleor.plugins.tests.sample_plugins.ActivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.InactivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.ActiveDummyPaymentGateway",+ ]+ manager = PluginsManager(plugins=plugins)+ assert (+ manager.list_payment_gateways(currency="USD", active_only=False)+ == expected_gateways+ )