Skip to content

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

Adyene check giftcard balance mutation (#8472)

L3str4nge1b4da5a88d08
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 98f017b91f..2fd3edc6f9 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -16,6 +16,7 @@ from ...payment import PaymentError, StorePaymentMethod, gateway
from ...payment.error_codes import PaymentErrorCode
from ...payment.utils import create_payment, is_currency_supported
from ..account.i18n import I18nMixin
+from ..channel.utils import validate_channel
from ..checkout.mutations import get_checkout_by_token
from ..checkout.types import Checkout
from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT
@@ -416,3 +417,95 @@ class PaymentInitialize(BaseMutation):
}
)
return PaymentInitialize(initialized_payment=response)
+
+
+class MoneyInput(graphene.InputObjectType):
+ currency = graphene.String(description="Currency code.", required=True)
+ amount = PositiveDecimal(description="Amount of money.", required=True)
+
+
+class CardInput(graphene.InputObjectType):
+ code = graphene.String(
+ description=(
+ "Payment method nonce, a token returned "
+ "by the appropriate provider's SDK."
+ ),
+ required=True,
+ )
+ cvc = graphene.String(description="Card security code.", required=False)
+ money = MoneyInput(
+ description="Information about currency and amount.", required=True
+ )
+
+
+class PaymentCheckBalanceInput(graphene.InputObjectType):
+ gateway_id = graphene.types.String(
+ description="An ID of a payment gateway to check.", required=True
+ )
+ method = graphene.types.String(description="Payment method name.", required=True)
+ channel = graphene.String(
+ description="Slug of a channel for which the data should be returned.",
+ required=True,
+ )
+ card = CardInput(description="Information about card.", required=True)
+
+
+class PaymentCheckBalance(BaseMutation):
+ data = graphene.types.JSONString(description="Response from the gateway.")
+
+ class Arguments:
+ input = PaymentCheckBalanceInput(
+ description="Fields required to check payment balance.", required=True
+ )
+
+ class Meta:
+ description = "Check payment balance."
+ error_type_class = common_types.PaymentError
+ error_type_field = "payment_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ manager = info.context.plugins
+ gateway_id = data["input"]["gateway_id"]
+ money = data["input"]["card"].get("money", {})
+
+ cls.validate_gateway(gateway_id, manager)
+ cls.validate_currency(money.currency, gateway_id, manager)
+
+ channel = data["input"].pop("channel")
+ validate_channel(channel, PaymentErrorCode)
+
+ try:
+ data = manager.check_payment_balance(data["input"], channel)
+ except PaymentError as e:
+ raise ValidationError(
+ str(e), code=PaymentErrorCode.BALANCE_CHECK_ERROR.value
+ )
+
+ return PaymentCheckBalance(data=data)
+
+ @classmethod
+ def validate_gateway(cls, gateway_id, manager):
+ gateways_id = [gateway.id for gateway in manager.list_payment_gateways()]
+
+ if gateway_id not in gateways_id:
+ raise ValidationError(
+ {
+ "gateway_id": ValidationError(
+ f"The gateway_id {gateway_id} is not available.",
+ code=PaymentErrorCode.NOT_SUPPORTED_GATEWAY.value,
+ )
+ }
+ )
+
+ @classmethod
+ def validate_currency(cls, currency, gateway_id, manager):
+ if not is_currency_supported(currency, gateway_id, manager):
+ raise ValidationError(
+ {
+ "currency": ValidationError(
+ f"The currency {currency} is not available for {gateway_id}.",
+ code=PaymentErrorCode.NOT_SUPPORTED_GATEWAY.value,
+ )
+ }
+ )
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index f594b7afa7..c3d0a15c81 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -5,7 +5,13 @@ from ..core.fields import FilterInputConnectionField
from ..core.utils import from_global_id_or_error
from ..decorators import permission_required
from .filters import PaymentFilterInput
-from .mutations import PaymentCapture, PaymentInitialize, PaymentRefund, PaymentVoid
+from .mutations import (
+ PaymentCapture,
+ PaymentCheckBalance,
+ PaymentInitialize,
+ PaymentRefund,
+ PaymentVoid,
+)
from .resolvers import resolve_payment_by_id, resolve_payments
from .types import Payment
@@ -39,3 +45,4 @@ class PaymentMutations(graphene.ObjectType):
payment_refund = PaymentRefund.Field()
payment_void = PaymentVoid.Field()
payment_initialize = PaymentInitialize.Field()
+ payment_check_balance = PaymentCheckBalance.Field()
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index 3591f05176..fa2fa40785 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -1,6 +1,6 @@
import json
from decimal import Decimal
-from unittest.mock import ANY, patch
+from unittest.mock import ANY, Mock, patch
import graphene
import pytest
@@ -29,6 +29,7 @@ from ...tests.utils import (
get_graphql_content_from_response,
)
from ..enums import OrderAction, PaymentChargeStatusEnum
+from ..mutations import PaymentCheckBalance
DUMMY_GATEWAY = "mirumee.payments.dummy"
@@ -1231,3 +1232,188 @@ def test_resolve_available_capture_amount(
content = get_graphql_content(response)
assert content["data"]["payment"]["availableCaptureAmount"]["amount"] == 98.4
+
+
+MUTATION_CHECK_PAYMENT_BALANCE = """
+ mutation checkPaymentBalance($input: PaymentCheckBalanceInput!) {
+ paymentCheckBalance(input: $input){
+ data
+ errors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
[email protected](PluginsManager, "check_payment_balance")
+def test_payment_check_balance_mutation_validate_gateway_does_not_exist(
+ check_payment_balance_mock, staff_api_client, check_payment_balance_input
+):
+ check_payment_balance_input["gatewayId"] = "mirumee.payments.not_existing_gateway"
+ response = staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["paymentCheckBalance"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PaymentErrorCode.NOT_SUPPORTED_GATEWAY.value.upper()
+ assert errors[0]["field"] == "gatewayId"
+ assert errors[0]["message"] == (
+ "The gateway_id mirumee.payments.not_existing_gateway is not available."
+ )
+
+ assert check_payment_balance_mock.call_count == 0
+
+
[email protected](PluginsManager, "check_payment_balance")
[email protected](PaymentCheckBalance, "validate_gateway")
+@patch("saleor.graphql.channel.utils.validate_channel")
+def test_payment_check_balance_validate_not_supported_currency(
+ _, __, check_payment_balance_mock, staff_api_client, check_payment_balance_input
+):
+ check_payment_balance_input["card"]["money"]["currency"] = "ABSTRACT_CURRENCY"
+ response = staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["paymentCheckBalance"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PaymentErrorCode.NOT_SUPPORTED_GATEWAY.value.upper()
+ assert errors[0]["field"] == "currency"
+ assert errors[0]["message"] == (
+ "The currency ABSTRACT_CURRENCY is not "
+ "available for mirumee.payments.gateway."
+ )
+
+ assert check_payment_balance_mock.call_count == 0
+
+
[email protected](PluginsManager, "check_payment_balance")
[email protected](PaymentCheckBalance, "validate_gateway")
[email protected](PaymentCheckBalance, "validate_currency")
+def test_payment_check_balance_validate_channel_does_not_exist(
+ _, __, check_payment_balance_mock, staff_api_client, check_payment_balance_input
+):
+ check_payment_balance_input["channel"] = "not_existing_channel"
+ response = staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["paymentCheckBalance"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PaymentErrorCode.NOT_FOUND.value.upper()
+ assert errors[0]["field"] == "channel"
+ assert errors[0]["message"] == (
+ "Channel with 'not_existing_channel' slug does not exist."
+ )
+
+ assert check_payment_balance_mock.call_count == 0
+
+
[email protected](PluginsManager, "check_payment_balance")
[email protected](PaymentCheckBalance, "validate_gateway")
[email protected](PaymentCheckBalance, "validate_currency")
+def test_payment_check_balance_validate_channel_inactive(
+ _,
+ __,
+ check_payment_balance_mock,
+ staff_api_client,
+ channel_USD,
+ check_payment_balance_input,
+):
+ channel_USD.is_active = False
+ channel_USD.save(update_fields=["is_active"])
+ check_payment_balance_input["channel"] = "main"
+
+ response = staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["paymentCheckBalance"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PaymentErrorCode.CHANNEL_INACTIVE.value.upper()
+ assert errors[0]["field"] == "channel"
+ assert errors[0]["message"] == "Channel with 'main' is inactive."
+ assert check_payment_balance_mock.call_count == 0
+
+
[email protected](PluginsManager, "check_payment_balance")
[email protected](PaymentCheckBalance, "validate_gateway")
[email protected](PaymentCheckBalance, "validate_currency")
+@patch("saleor.graphql.payment.mutations.validate_channel")
+def test_payment_check_balance_payment(
+ _,
+ __,
+ ___,
+ check_payment_balance_mock,
+ staff_api_client,
+ check_payment_balance_input,
+):
+ staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ check_payment_balance_mock.assert_called_once_with(
+ {
+ "gateway_id": "mirumee.payments.gateway",
+ "method": "givex",
+ "card": {
+ "cvc": "9891",
+ "code": "12345678910",
+ "money": {"currency": "GBP", "amount": 100.0},
+ },
+ },
+ "channel_default",
+ )
+
+
[email protected](PluginsManager, "check_payment_balance")
[email protected](PaymentCheckBalance, "validate_gateway")
[email protected](PaymentCheckBalance, "validate_currency")
+@patch("saleor.graphql.payment.mutations.validate_channel")
+def test_payment_check_balance_balance_raises_error(
+ _,
+ __,
+ ___,
+ check_payment_balance_mock,
+ staff_api_client,
+ check_payment_balance_input,
+):
+ check_payment_balance_mock.side_effect = Mock(
+ side_effect=PaymentError("Test payment error")
+ )
+
+ response = staff_api_client.post_graphql(
+ MUTATION_CHECK_PAYMENT_BALANCE, {"input": check_payment_balance_input}
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["paymentCheckBalance"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PaymentErrorCode.BALANCE_CHECK_ERROR.value.upper()
+ assert errors[0]["message"] == "Test payment error"
+
+ check_payment_balance_mock.assert_called_once_with(
+ {
+ "gateway_id": "mirumee.payments.gateway",
+ "method": "givex",
+ "card": {
+ "cvc": "9891",
+ "code": "12345678910",
+ "money": {"currency": "GBP", "amount": 100.0},
+ },
+ },
+ "channel_default",
+ )
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 974f902bae..610e1bb69e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -804,6 +804,12 @@ type BulkStockError {
index: Int
}
+input CardInput {
+ code: String!
+ cvc: String
+ money: MoneyInput!
+}
+
input CatalogueInput {
products: [ID]
categories: [ID]
@@ -3732,6 +3738,11 @@ type Money {
amount: Float!
}
+input MoneyInput {
+ currency: String!
+ amount: PositiveDecimal!
+}
+
type MoneyRange {
start: Money
stop: Money
@@ -3831,6 +3842,7 @@ type Mutation {
paymentRefund(amount: PositiveDecimal, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
paymentInitialize(channel: String, gateway: String!, paymentData: JSONString): PaymentInitialize
+ paymentCheckBalance(input: PaymentCheckBalanceInput!): PaymentCheckBalance
pageCreate(input: PageCreateInput!): PageCreate
pageDelete(id: ID!): PageDelete
pageBulkDelete(ids: [ID]!): PageBulkDelete
@@ -4898,6 +4910,19 @@ enum PaymentChargeStatusEnum {
CANCELLED
}
+type PaymentCheckBalance {
+ data: JSONString
+ paymentErrors: [PaymentError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [PaymentError!]!
+}
+
+input PaymentCheckBalanceInput {
+ gatewayId: String!
+ method: String!
+ channel: String!
+ card: CardInput!
+}
+
type PaymentCountableConnection {
pageInfo: PageInfo!
edges: [PaymentCountableEdge!]!
@@ -4929,6 +4954,7 @@ enum PaymentErrorCode {
PAYMENT_ERROR
NOT_SUPPORTED_GATEWAY
CHANNEL_INACTIVE
+ BALANCE_CHECK_ERROR
}
input PaymentFilterInput {
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index 2549a107af..829f05993f 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -15,3 +15,4 @@ class PaymentErrorCode(Enum):
PAYMENT_ERROR = "payment_error"
NOT_SUPPORTED_GATEWAY = "not_supported_gateway"
CHANNEL_INACTIVE = "channel_inactive"
+ BALANCE_CHECK_ERROR = "balance_check_error"
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index c1a35f5968..c28ae8c39c 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -38,6 +38,7 @@ from .utils.common import (
api_call,
call_capture,
get_payment_method_info,
+ get_request_data_for_check_payment,
request_data_for_gateway_config,
request_data_for_payment,
request_for_payment_cancel,
@@ -321,6 +322,29 @@ class AdyenGatewayPlugin(BasePlugin):
)
return [gateway]
+ @require_active_plugin
+ def check_payment_balance(self, data: dict, previous_value=None) -> dict:
+ request_data = get_request_data_for_check_payment(
+ data, self.config.connection_params["merchant_account"]
+ )
+
+ with opentracing.global_tracer().start_active_span(
+ "adyen.checkout.payment_methods_balance"
+ ) as scope:
+ span = scope.span
+ span.set_tag(opentracing.tags.COMPONENT, "payment")
+ span.set_tag("service.name", "adyen")
+
+ try:
+ result = api_call(
+ request_data,
+ self.adyen.checkout.client.call_checkout_api,
+ action="paymentMethods/balance",
+ )
+ return result.message
+ except PaymentError as e:
+ return e.message
+
@property
def order_auto_confirmation(self):
site_settings = Site.objects.get_current().settings
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
index a059361a5f..039f3f9547 100644
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -1,6 +1,7 @@
from decimal import Decimal
from unittest import mock
+import Adyen
import pytest
from .....checkout import calculations
@@ -234,3 +235,14 @@ def adyen_additional_data_for_klarna():
"timeZoneOffset": -120,
},
}
+
+
+def adyen_check_balance_response():
+ return Adyen.client.AdyenResult(
+ message={
+ "pspReference": "851634546949980A",
+ "resultCode": "Success",
+ "balance": {"currency": "GBP", "value": 10000},
+ }
+ )
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index d93ead7519..5d11b016c7 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -2,6 +2,7 @@ import json
from decimal import Decimal
from unittest import mock
+import Adyen
import pytest
from django.core.exceptions import ValidationError
from requests.exceptions import RequestException, SSLError
@@ -627,3 +628,77 @@ def test_validate_plugin_configuration_without_apple_cert(adyen_plugin):
plugin_configuration = PluginConfiguration.objects.get()
plugin_configuration.configuration = configuration
plugin.validate_plugin_configuration(plugin_configuration)
+
+
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
+def test_adyen_check_payment_balance(
+ api_call_mock, adyen_plugin, adyen_check_balance_response
+):
+
+ api_call_mock.return_value = adyen_check_balance_response
+ plugin = adyen_plugin()
+
+ data = {
+ "gatewayId": "mirumee.payments.gateway",
+ "method": "givex",
+ "card": {
+ "cvc": "9891",
+ "code": "1234567910",
+ "money": {"currency": "GBP", "amount": Decimal(100.0)},
+ },
+ }
+
+ result = plugin.check_payment_balance(data)
+
+ assert result["pspReference"] == "851634546949980A"
+ assert result["resultCode"] == "Success"
+ assert result["balance"] == {"currency": "GBP", "value": 10000}
+ api_call_mock.assert_called_once_with(
+ {
+ "merchantAccount": "SaleorECOM",
+ "paymentMethod": {
+ "type": "givex",
+ "number": "1234567910",
+ "securityCode": "9891",
+ },
+ "amount": {"currency": "GBP", "value": "10000"},
+ },
+ plugin.adyen.checkout.client.call_checkout_api,
+ action="paymentMethods/balance",
+ )
+
+
[email protected]("saleor.payment.gateways.adyen.plugin.api_call")
+def test_adyen_check_payment_balance_adyen_raises_error(
+ api_call_mock, adyen_plugin, adyen_check_balance_response
+):
+
+ api_call_mock.return_value = Adyen.AdyenError("Error")
+ plugin = adyen_plugin()
+
+ data = {
+ "gatewayId": "mirumee.payments.gateway",
+ "method": "givex",
+ "card": {
+ "cvc": "9891",
+ "code": "1234567910",
+ "money": {"currency": "GBP", "amount": Decimal(100.0)},
+ },
+ }
+
+ result = plugin.check_payment_balance(data)
+
+ assert result == "Error"
+ api_call_mock.assert_called_once_with(
+ {
+ "merchantAccount": "SaleorECOM",
+ "paymentMethod": {
+ "type": "givex",
+ "number": "1234567910",
+ "securityCode": "9891",
+ },
+ "amount": {"currency": "GBP", "value": "10000"},
+ },
+ plugin.adyen.checkout.client.call_checkout_api,
+ action="paymentMethods/balance",
+ )
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
index a69c4dd0d9..26a53f1c29 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -10,6 +10,7 @@ from saleor.payment import PaymentError
from saleor.payment.gateways.adyen.utils.common import (
append_checkout_details,
get_payment_method_info,
+ get_request_data_for_check_payment,
get_shopper_locale_value,
request_data_for_gateway_config,
request_data_for_payment,
@@ -1009,3 +1010,65 @@ def test_prepare_address_request_data_with_city_area_without_country_area(
assert result["postalCode"] == "53-601"
assert result["stateOrProvince"] == "ZZ"
assert result["street"] == "Tęczowa 7"
+
+
+def test_get_request_data_for_check_payment():
+ data = get_request_data_for_check_payment(
+ {
+ "method": "test",
+ "card": {
+ "code": "1243456",
+ "cvc": "123",
+ "money": {"amount": Decimal(10.05), "currency": "EUR"},
+ },
+ },
+ merchant_account="TEST_ACCOUNT",
+ )
+
+ assert data["merchantAccount"] == "TEST_ACCOUNT"
+ assert data["paymentMethod"]["type"] == "test"
+ assert data["paymentMethod"]["number"] == "1243456"
+ assert data["paymentMethod"]["securityCode"] == "123"
+ assert data["amount"]["value"] == "1005"
+ assert data["amount"]["currency"] == "EUR"
+
+
+def test_get_request_data_for_check_payment_without_money():
+ data = get_request_data_for_check_payment(
+ {"method": "test", "card": {"code": "1243456", "cvc": "123"}},
+ merchant_account="TEST_ACCOUNT",
+ )
+
+ assert data["merchantAccount"] == "TEST_ACCOUNT"
+ assert data["paymentMethod"]["type"] == "test"
+ assert data["paymentMethod"]["number"] == "1243456"
+ assert data["paymentMethod"]["securityCode"] == "123"
+
+
+def test_get_request_data_for_check_payment_without_cvc():
+ data = get_request_data_for_check_payment(
+ {
+ "method": "test",
+ "card": {
+ "code": "1243456",
+ "money": {"amount": Decimal(10.05), "currency": "EUR"},
+ },
+ },
+ merchant_account="TEST_ACCOUNT",
+ )
+
+ assert data["merchantAccount"] == "TEST_ACCOUNT"
+ assert data["paymentMethod"]["type"] == "test"
+ assert data["paymentMethod"]["number"] == "1243456"
+ assert data["amount"]["value"] == "1005"
+ assert data["amount"]["currency"] == "EUR"
+
+
+def test_get_request_data_for_check_payment_without_cvc_and_money():
+ data = get_request_data_for_check_payment(
+ {"method": "test", "card": {"code": "1243456"}}, merchant_account="TEST_ACCOUNT"
+ )
+
+ assert data["merchantAccount"] == "TEST_ACCOUNT"
+ assert data["paymentMethod"]["type"] == "test"
+ assert data["paymentMethod"]["number"] == "1243456"
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index 07bec46f3e..3b2f760a94 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -47,12 +47,14 @@ def get_tax_percentage_in_adyen_format(total_gross, total_net):
return tax_percentage_in_adyen_format
-def api_call(request_data: Optional[Dict[str, Any]], method: Callable) -> Adyen.Adyen:
+def api_call(
+ request_data: Optional[Dict[str, Any]], method: Callable, **kwargs
+) -> Adyen.Adyen:
try:
- return method(request_data)
+ return method(request_data, **kwargs)
except (Adyen.AdyenError, ValueError, TypeError) as e:
logger.warning(f"Unable to process the payment: {e}")
- raise PaymentError("Unable to process the payment request.")
+ raise PaymentError(f"Unable to process the payment request: {e}.")
def prepare_address_request_data(address: Optional["AddressData"]) -> Optional[dict]:
@@ -444,3 +446,29 @@ def get_payment_method_info(
type="card" if payment_method == "scheme" else payment_method,
)
return payment_method_info
+
+
+def get_request_data_for_check_payment(data: dict, merchant_account: str) -> dict:
+ amount_input = data["card"].get("money")
+ security_code = data["card"].get("cvc")
+
+ request_data = {
+ "merchantAccount": merchant_account,
+ "paymentMethod": {
+ "type": data["method"],
+ "number": data["card"]["code"],
+ },
+ }
+
+ if amount_input:
+ currency = amount_input["currency"]
+ value = amount_input["amount"]
+ request_data["amount"] = {
+ "value": price_to_minor_unit(value, currency),
+ "currency": currency,
+ }
+
+ if security_code:
+ request_data["paymentMethod"]["securityCode"] = security_code # type: ignore
+
+ return request_data
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index c07b44d4c1..f00ceb4803 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -214,6 +214,9 @@ class BasePlugin:
["Address", Union[str, NoneType], Union["User", NoneType], "Address"], "Address"
]
+ # Retrieves the balance remaining on a shopper's gift card
+ check_payment_balance: Callable[[dict, str], dict]
+
# Trigger when checkout is created.
#
# Overwrite this method if you need to trigger specific logic when a checkout is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index a7cc94faf5..3b62a23b24 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -150,6 +150,11 @@ class PluginsManager(PaymentInterface):
return previous_value
return returned_value
+ def check_payment_balance(self, details: dict, channel_slug: str) -> dict:
+ return self.__run_method_on_plugins(
+ "check_payment_balance", None, details, channel_slug=channel_slug
+ )
+
def change_user_address(
self, address: "Address", address_type: Optional[str], user: Optional["User"]
) -> "Address":
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 6926c72bb5..485b4619bb 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -338,6 +338,9 @@ class ActiveDummyPaymentGateway(BasePlugin):
def get_payment_config(self, previous_value):
return self.CLIENT_CONFIG
+ def check_payment_balance(self, request_data: dict, previous_value):
+ return {"test_response": "success"}
+
class InactivePaymentGateway(BasePlugin):
PLUGIN_ID = "gateway.inactive"
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index ef9ee1522b..73573bf1ce 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1024,3 +1024,17 @@ def test_run_method_on_single_plugin_valid_response(plugins_manager):
)
== plugin.SUPPORTED_CURRENCIES
)
+
+
+def test_run_check_payment_balance(channel_USD):
+ plugins = ["saleor.plugins.tests.sample_plugins.ActiveDummyPaymentGateway"]
+
+ manager = PluginsManager(plugins=plugins)
+ assert manager.check_payment_balance({}, "main") == {"test_response": "success"}
+
+
+def test_run_check_payment_balance_not_implemented(channel_USD):
+ plugins = ["saleor.plugins.tests.sample_plugins.ActivePlugin"]
+
+ manager = PluginsManager(plugins=plugins)
+ assert not manager.check_payment_balance({}, "main")
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 2e55ab65ee..6e8ff585ce 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5316,3 +5316,17 @@ def app_manifest():
"configurationUrl": "http://127.0.0.1:5000/configuration/",
"tokenTargetUrl": "http://127.0.0.1:5000/configuration/install",
}
+
+
+def check_payment_balance_input():
+ return {
+ "gatewayId": "mirumee.payments.gateway",
+ "channel": "channel_default",
+ "method": "givex",
+ "card": {
+ "cvc": "9891",
+ "code": "12345678910",
+ "money": {"currency": "GBP", "amount": 100.0},
+ },
+ }