Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Switch payment methods to use new gateway
Jakub Draganekad0b6f876e52
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 5f96a66339..7f685e7573 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -32,7 +32,7 @@ from ...order.models import Fulfillment, Order, OrderLinefrom ...order.utils import update_order_statusfrom ...page.models import Pagefrom ...payment import gateway-from ...payment.utils import create_payment, gateway_authorize, gateway_refund+from ...payment.utils import create_paymentfrom ...product.models import (AssignedProductAttribute,AssignedVariantAttribute,@@ -384,7 +384,7 @@ def create_fake_payment(mock_email_confirmation, order):)# Create authorization transaction- gateway_authorize(payment, payment.token)+ gateway.authorize(payment, payment.token)# 20% chance to void the transaction at this stageif random.choice([0, 0, 0, 0, 1]):gateway.void(payment)@@ -396,7 +396,7 @@ def create_fake_payment(mock_email_confirmation, order):gateway.capture(payment)# 25% to refund the paymentif random.choice([0, 0, 0, 1]):- gateway_refund(payment)+ gateway.refund(payment)return paymentdiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex c96a98506a..f5b98b973a 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -28,7 +28,6 @@ from ...order.utils import (from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError, gatewayfrom ...payment.utils import (clean_mark_order_as_paid,- gateway_refund,mark_order_as_paid,)from ...product.models import Product, ProductVariant@@ -364,7 +363,7 @@ class RefundPaymentForm(BasePaymentForm):def refund(self, user):return self.try_payment_action(- user, gateway_refund, self.cleaned_data["amount"]+ user, gateway.refund, self.cleaned_data["amount"])diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 56f540e3bc..b38d342bac 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -13,7 +13,6 @@ from ....order.utils import (from ....payment import CustomPaymentChoices, PaymentError, gatewayfrom ....payment.utils import (clean_mark_order_as_paid,- gateway_refund,mark_order_as_paid,)from ...account.types import AddressInput@@ -415,7 +414,7 @@ class OrderRefund(BaseMutation):clean_refund_payment(payment)try_payment_action(- order, info.context.user, payment, gateway_refund, payment, amount+ order, info.context.user, payment, gateway.refund, payment, amount)events.payment_refunded_event(diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 9954871379..4cf1c9e1dc 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -6,7 +6,7 @@ from ...core.taxes import zero_taxed_moneyfrom ...core.utils import get_client_ipfrom ...payment import PaymentError, gateway, modelsfrom ...payment.error_codes import PaymentErrorCode-from ...payment.utils import create_payment, gateway_confirm, gateway_refund+from ...payment.utils import create_paymentfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..checkout.types import Checkout@@ -156,7 +156,7 @@ class PaymentRefund(PaymentCapture):info, payment_id, field="payment_id", only_type=Payment)try:- gateway_refund(payment, amount=amount)+ gateway.refund(payment, amount=amount)except PaymentError as e:raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)return PaymentRefund(payment=payment)@@ -203,7 +203,7 @@ class PaymentSecureConfirm(BaseMutation):info, payment_id, field="payment_id", only_type=Payment)try:- gateway_confirm(payment)+ gateway.confirm(payment)except PaymentError as e:raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)return PaymentSecureConfirm(payment=payment)diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex c20100c702..f3b54911e6 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -210,6 +210,7 @@ def cancel_order(user, order, restock):)from ..payment import gateway+for payment in payments:if payment.can_refund():gateway.refund(payment)diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex 386b7b0744..8d920b1da3 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -75,6 +75,7 @@ def process_payment(@payment_postprocess@raise_payment_error+@require_active_paymentdef authorize(payment: Payment, token: str, store_source: bool = False) -> Transaction:plugin_manager = get_extensions_manager()clean_authorize(payment)diff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.pyindex d8b81152de..45bd8d3685 100644--- a/saleor/payment/gateways/dummy/plugin.py+++ b/saleor/payment/gateways/dummy/plugin.py@@ -6,7 +6,7 @@ from django.utils.translation import pgettext_lazyfrom saleor.extensions import ConfigurationTypeFieldfrom saleor.extensions.base_plugin import BasePlugin-from . import GatewayConfig, authorize, capture, process_payment, refund, void+from . import GatewayConfig, authorize, capture, confirm, process_payment, refund, voidGATEWAY_NAME = "dummy"@@ -96,6 +96,11 @@ class DummyGatewayPlugin(BasePlugin):) -> "GatewayResponse":return capture(payment_information, self._get_gateway_config())+ def confirm_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return confirm(payment_information, self._get_gateway_config())+def refund_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 7e86a52011..2d20986cf9 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -425,73 +425,6 @@ def gateway_process_payment(return transaction-@require_active_payment-def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:- """Authorize the payment and create a relevant transaction.-- Args:- payment: the payment to process.- payment_token: One-time-use reference to payment information.-- """- clean_authorize(payment)-- return call_gateway(- operation_type=OperationType.AUTH, payment=payment, payment_token=payment_token- )---@require_active_payment-def gateway_confirm(payment) -> Transaction:- if not payment.can_confirm():- raise PaymentError("Only active and not paid payments can be confirmed.")-- payment_token = get_payment_token(payment)- transaction = call_gateway(- operation_type=OperationType.CONFIRM,- payment=payment,- payment_token=payment_token,- )- gateway_postprocess(transaction, payment)- return transaction---@require_active_payment-def gateway_refund(payment, amount: Decimal = None) -> Transaction:- """Refund the charged funds back to the customer.-- Refunds can be total or partial.- """- if amount is None:- # If no amount is specified, refund the maximum possible- amount = payment.captured_amount-- if not payment.can_refund():- raise PaymentError("This payment cannot be refunded.")-- if amount <= 0:- raise PaymentError("Amount should be a positive number.")- if amount > payment.captured_amount:- raise PaymentError("Cannot refund more than captured")-- transaction = payment.transactions.filter(- kind=TransactionKind.CAPTURE, is_success=True- ).first()- if transaction is None:- raise PaymentError("Cannot refund uncaptured transaction")- payment_token = transaction.token-- transaction = call_gateway(- operation_type=OperationType.REFUND,- payment=payment,- payment_token=payment_token,- amount=amount,- )-- gateway_postprocess(transaction, payment)- return transaction--def fetch_customer_id(user, gateway):"""Retrieve users customer_id stored for desired gateway."""key = prepare_namespace_name(gateway)diff --git a/tests/test_payment.py b/tests/test_payment.pyindex 93c84844ef..48075834ae 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -32,10 +32,8 @@ from saleor.payment.utils import (create_payment,create_payment_information,create_transaction,- gateway_authorize,gateway_get_client_token,gateway_process_payment,- gateway_refund,handle_fully_paid_order,mark_order_as_paid,require_active_payment,@@ -317,7 +315,8 @@ def test_gateway_get_client_token_not_existing_gateway(settings):@pytest.mark.parametrize(- "func", [gateway_authorize, gateway.capture, gateway_refund, gateway.void]+ "func",+ [gateway.authorize, gateway.capture, gateway.confirm, gateway.refund, gateway.void],)def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):payment_dummy.is_active = False@@ -326,63 +325,6 @@ def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):assert exc.value.message == NOT_ACTIVE_PAYMENT_ERROR-@patch("saleor.payment.utils.get_payment_gateway")-def test_gateway_authorize(- mock_get_payment_gateway,- payment_txn_preauth,- gateway_config,- transaction_token,- dummy_response,-):- payment = payment_txn_preauth- payment_token = transaction_token-- mock_authorize = Mock(return_value=dummy_response)- mock_get_payment_gateway.return_value = (- Mock(authorize=mock_authorize),- gateway_config,- )-- payment_info = create_payment_information(payment, payment_token)- gateway_authorize(payment, payment_token)-- mock_get_payment_gateway.assert_called_once_with(payment.gateway)- mock_authorize.assert_called_once_with(- payment_information=payment_info, config=gateway_config- )---@patch("saleor.payment.utils.get_payment_gateway")-def test_gateway_authorize_failed(- mock_get_payment_gateway,- payment_txn_preauth,- gateway_config,- transaction_token,- dummy_response,-):- payment_token = transaction_token- txn = payment_txn_preauth.transactions.first()- txn.is_success = False- payment = payment_txn_preauth-- dummy_response.is_success = False- mock_authorize = Mock(return_value=dummy_response)- mock_get_payment_gateway.return_value = (- Mock(authorize=mock_authorize),- gateway_config,- )- with pytest.raises(PaymentError) as exc:- gateway_authorize(payment, payment_token)- assert exc.value.message == EXAMPLE_ERROR---def test_gateway_authorize_errors(payment_dummy):- payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED- with pytest.raises(PaymentError) as exc:- gateway_authorize(payment_dummy, "payment-token")- assert exc.value.message == ("Charged transactions cannot be authorized again.")--@patch("saleor.payment.utils.handle_fully_paid_order")def test_gateway_charge_failed(mock_handle_fully_paid_order, mock_get_manager, payment_txn_preauth, dummy_response@@ -407,7 +349,7 @@ def test_gateway_charge_failed(def test_gateway_charge_errors(payment_dummy, transaction_token, settings):payment = payment_dummy- gateway_authorize(payment, transaction_token)+ gateway.authorize(payment, transaction_token)with pytest.raises(PaymentError) as exc:gateway.capture(payment, Decimal("0"))assert exc.value.message == "Amount should be a positive number."@@ -423,57 +365,6 @@ def test_gateway_charge_errors(payment_dummy, transaction_token, settings):assert exc.value.message == ("Unable to charge more than un-captured amount.")-@patch("saleor.payment.utils.get_payment_gateway")-def test_gateway_refund(- mock_get_payment_gateway, payment_txn_captured, gateway_config, dummy_response-):- txn = payment_txn_captured.transactions.first()- payment = payment_txn_captured- amount = payment.total-- dummy_response.kind = TransactionKind.REFUND- mock_refund = Mock(return_value=dummy_response)- mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)-- payment_info = create_payment_information(payment, txn.token, amount)- gateway_refund(payment, amount)-- mock_get_payment_gateway.assert_called_once_with(payment.gateway)- mock_refund.assert_called_once_with(- payment_information=payment_info, config=gateway_config- )-- payment.refresh_from_db()- assert payment.charge_status == ChargeStatus.FULLY_REFUNDED- assert not payment.captured_amount---@patch("saleor.payment.utils.get_payment_gateway")-def test_gateway_refund_partial_refund(- mock_get_payment_gateway,- payment_txn_captured,- gateway_config,- settings,- dummy_response,-):- payment = payment_txn_captured- amount = payment.total * Decimal("0.5")- txn = payment_txn_captured.transactions.first()- txn.amount = amount- txn.currency = settings.DEFAULT_CURRENCY-- dummy_response.kind = TransactionKind.REFUND- dummy_response.amount = amount- mock_refund = Mock(return_value=dummy_response)- mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)-- gateway_refund(payment, amount)-- payment.refresh_from_db()- assert payment.charge_status == ChargeStatus.PARTIALLY_REFUNDED- assert payment.captured_amount == payment.total - amount--@patch("saleor.payment.utils.get_payment_gateway")def test_gateway_refund_failed(mock_get_payment_gateway,@@ -493,7 +384,7 @@ def test_gateway_refund_failed(mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_config)with pytest.raises(PaymentError) as exc:- gateway_refund(payment, Decimal("10.00"))+ gateway.refund(payment, Decimal("10.00"))assert exc.value.message == EXAMPLE_ERRORpayment.refresh_from_db()assert payment.captured_amount == captured_before@@ -502,16 +393,16 @@ def test_gateway_refund_failed(def test_gateway_refund_errors(payment_txn_captured):payment = payment_txn_capturedwith pytest.raises(PaymentError) as exc:- gateway_refund(payment, Decimal("1000000"))+ gateway.refund(payment, Decimal("1000000"))assert exc.value.message == "Cannot refund more than captured"with pytest.raises(PaymentError) as exc:- gateway_refund(payment, Decimal("0"))+ gateway.refund(payment, Decimal("0"))assert exc.value.message == "Amount should be a positive number."payment.charge_status = ChargeStatus.NOT_CHARGEDwith pytest.raises(PaymentError) as exc:- gateway_refund(payment, Decimal("1"))+ gateway.refund(payment, Decimal("1"))assert exc.value.message == "This payment cannot be refunded."