Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor payments
Michał Jelonek6b5679716e1a
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 2ce558ebf4..7a6bfe1f91 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -31,7 +31,9 @@ from ...order.models import Fulfillment, Orderfrom ...order.utils import update_order_statusfrom ...page.models import Pagefrom ...payment.models import Payment-from ...payment.utils import get_billing_data+from ...payment.utils import (+ get_billing_data, gateway_authorize, gateway_capture, gateway_refund,+ gateway_void)from ...product.models import (Attribute, AttributeValue, Category, Collection, Product, ProductImage,ProductType, ProductVariant)@@ -323,19 +325,19 @@ def create_payment(mock_email_confirmation, order):**get_billing_data(order))# Create authorization transaction- payment.authorize(payment.token)+ gateway_authorize(payment, payment.token)# 20% chance to void the transaction at this stageif random.choice([0, 0, 0, 0, 1]):- payment.void()+ gateway_void(payment)return payment# 25% to end the payment at the authorization stageif not random.choice([1, 1, 1, 0]):return payment# Create capture transaction- payment.capture()+ gateway_capture(payment)# 25% to refund the paymentif random.choice([0, 0, 0, 1]):- payment.refund()+ gateway_refund(payment)return paymentdiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex d047cd75bc..90e8c600d1 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -20,7 +20,8 @@ from ...order.utils import (change_order_line_quantity, recalculate_order)from ...payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom ...payment.models import Payment-from ...payment.utils import get_billing_data+from ...payment.utils import (+ get_billing_data, gateway_capture, gateway_refund, gateway_void)from ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockfrom ...shipping.models import ShippingMethod@@ -274,7 +275,7 @@ class ManagePaymentForm(forms.Form):def try_payment_action(self, action):amount = self.cleaned_data['amount']try:- action(amount)+ action(self.payment, amount)except (PaymentError, ValueError) as e:self.payment_error(str(e))return False@@ -288,7 +289,7 @@ class CapturePaymentForm(ManagePaymentForm):'Only pre-authorized payments can be captured')def capture(self):- return self.try_payment_action(self.payment.capture)+ return self.try_payment_action(gateway_capture)class RefundPaymentForm(ManagePaymentForm):@@ -306,7 +307,7 @@ class RefundPaymentForm(ManagePaymentForm):'Manual payments can not be refunded'))def refund(self):- return self.try_payment_action(self.payment.refund)+ return self.try_payment_action(gateway_refund)class VoidPaymentForm(forms.Form):@@ -329,7 +330,7 @@ class VoidPaymentForm(forms.Form):def void(self):try:- self.payment.void()+ gateway_void(self.payment)except (PaymentError, ValueError) as e:self.payment_error(str(e))return Falsediff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex a1c22f4918..c429309254 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -7,7 +7,7 @@ from ....order import OrderEvents, modelsfrom ....order.utils import cancel_orderfrom ....payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom ....payment.models import Payment-from ....payment.utils import get_billing_data+from ....payment.utils import get_billing_data, gateway_voidfrom ....shipping.models import ShippingMethod as ShippingMethodModelfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation@@ -43,9 +43,9 @@ def clean_order_update_shipping(order, method, errors):return errors-def try_payment_action(action, amount, errors):+def try_payment_action(action, payment, amount, errors):try:- action(amount)+ action(payment, amount)except (PaymentError, ValueError) as e:errors.append(Error(field='payment', message=str(e)))@@ -91,7 +91,7 @@ def clean_void_payment(payment, errors):Error(field='payment',message='Only pre-authorized payments can be voided'))try:- payment.void()+ gateway_void(payment)except (PaymentError, ValueError) as e:errors.append(Error(field='payment', message=str(e)))return errors@@ -383,7 +383,7 @@ class OrderRefund(BaseMutation):if order:payment = order.get_last_payment()clean_refund_payment(payment, amount, errors)- try_payment_action(payment.refund, amount, errors)+ try_payment_action(gateway_refund, payment, amount, errors)if errors:return OrderRefund(errors=errors)diff --git a/saleor/order/forms.py b/saleor/order/forms.pyindex 695eb37514..3315d15ba4 100644--- a/saleor/order/forms.py+++ b/saleor/order/forms.py@@ -4,6 +4,7 @@ from django.utils.translation import pgettext_lazyfrom ..account.forms import SignupFormfrom ..payment.models import Payment+from ..payment.utils import gateway_voidfrom .models import OrderPAYMENT_CHOICES = [@@ -44,7 +45,7 @@ class PaymentDeleteForm(forms.Form):def save(self):payment = self.cleaned_data['payment']- payment.void()+ gateway_void(payment)class PasswordForm(SignupForm):diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 1d183dc530..08f857e157 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -13,6 +13,7 @@ from ..discount.models import NotApplicablefrom ..order import FulfillmentStatus, OrderStatusfrom ..order.models import OrderLinefrom ..payment import ChargeStatus+from ..payment.utils import gateway_refund, gateway_voidfrom ..product.utils import allocate_stock, deallocate_stock, increase_stock@@ -114,9 +115,9 @@ def cancel_order(order, restock):for payment in payments:if payment.can_refund():- payment.refund()+ gateway_refund(payment)elif payment.can_void():- payment.void()+ gateway_void(payment)def update_order_status(order):diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 7cb2882baf..2fd7c6797f 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -18,7 +18,7 @@ from ..core.utils import get_client_ipfrom ..payment import (ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)from ..payment.models import Payment-from ..payment.utils import get_billing_data+from ..payment.utils import gateway_process_payment, get_billing_datafrom .forms import (CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentsForm)from .models import Order@@ -107,24 +107,25 @@ def start_payment(request, order, gateway):order.is_fully_paid()or payment.charge_status == ChargeStatus.FULLY_REFUNDED):return redirect(order.get_absolute_url())+payment_gateway, gateway_params = get_payment_gateway(payment.gateway)client_token = payment_gateway.get_client_token(**gateway_params)- form = payment_gateway.get_form_class()- form = form(- data=request.POST or None, payment=payment,- gateway=payment_gateway, gateway_params=gateway_params)+ form = payment_gateway.get_form_class()(+ data=request.POST or None, amount=payment.total,+ currency=payment.currency, gateway_params=gateway_params)if form.is_valid():try:- form.process_payment()- except PaymentError as exc:- form.add_error(None, exc.message)+ gateway_process_payment(payment=payment,+ payment_token=form.get_payment_token())+ except Exception as exc:+ form.add_error(None, str(exc))else:return redirect(order.get_absolute_url())- template = PAYMENT_TEMPLATE % gateway+ctx = {'form': form, 'payment': payment,'client_token': client_token, 'order': order}- return TemplateResponse(request, template, ctx)+ return TemplateResponse(request, payment_gateway.get_template(), ctx)@check_order_statusdiff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex ed24d3db3a..01b4333f93 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -12,6 +12,10 @@ class PaymentError(Exception):self.message = message+class GatewayError(Exception):+ pass++class CustomPaymentChoices:MANUAL = 'manual'diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex 6bea997a5d..1c3589edd3 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -8,9 +8,6 @@ from django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazyfrom prices import Money-from ... import TransactionKind-from ...models import Payment, Transaction-from ...utils import create_transactionfrom .forms import BraintreePaymentFormlogger = logging.getLogger(__name__)@@ -33,23 +30,23 @@ ERROR_CODES_WHITELIST = {}-def get_customer_data(payment: Payment) -> Dict:+def get_customer_data(payment: Dict) -> Dict:return {- "order_id": payment.order_id,+ 'order_id': payment['order'],'billing': {- 'first_name': payment.billing_first_name,- 'last_name': payment.billing_last_name,- 'company': payment.billing_company_name,- 'postal_code': payment.billing_postal_code,- 'street_address': payment.billing_address_1,- 'extended_address': payment.billing_address_2,- "locality": payment.billing_city,- 'region': payment.billing_country_area,- 'country_code_alpha2': payment.billing_country_code},+ 'first_name': payment['billing_first_name'],+ 'last_name': payment['billing_last_name'],+ 'company': payment['billing_company_name'],+ 'postal_code': payment['billing_postal_code'],+ 'street_address': payment['billing_address_1'],+ 'extended_address': payment['billing_address_2'],+ "locality": payment['billing_city'],+ 'region': payment['billing_country_area'],+ 'country_code_alpha2': payment['billing_country_code']},'risk_data': {- 'customer_ip': payment.customer_ip_address or ''},+ 'customer_ip': payment['customer_ip_address'] or ''},'customer': {- 'email': payment.billing_email}}+ 'email': payment['billing_email']}}def get_error_for_client(errors: List) -> str:@@ -67,26 +64,6 @@ def get_error_for_client(errors: List) -> str:return default_msg-def transaction_and_incorrect_token_error(- payment: Payment,- token: str,- kind: TransactionKind,- amount: Decimal = None) -> Tuple[Transaction, str]:- amount = amount or payment.total- txn = create_transaction(- payment=payment,- kind=kind,- currency=payment.currency,- amount=amount,- gateway_response={},- token=token,- is_success=False)- error = (- 'Unable to process the transaction. Transaction\'s token is incorrect '- 'or expired.')- return txn, error--def extract_gateway_response(braintree_result) -> Dict:"""Extract data from Braintree response that will be stored locally."""errors = []@@ -103,6 +80,7 @@ def extract_gateway_response(braintree_result) -> Dict:# FIXME we should have a predefined list of fields that will be supported# in the APIgateway_response = {+ 'transaction_id': getattr(bt_transaction, 'id', ''),'currency': bt_transaction.currency_iso_code,'amount': bt_transaction.amount, # Decimal type'credit_card': bt_transaction.credit_card,@@ -110,6 +88,10 @@ def extract_gateway_response(braintree_result) -> Dict:return gateway_response+def get_template():+ return 'order/payment/braintree.html'++def get_form_class():return BraintreePaymentForm@@ -136,14 +118,35 @@ def get_client_token(**connection_params: Dict) -> str:return client_token+def process_payment(+ payment: Dict, payment_token: str, amount: Decimal,+ **connection_params: Dict) -> Tuple[bool, str, Dict, str]:+ auth_success, auth_response, auth_errors = authorize(+ payment, payment_token, **connection_params)+ transaction_token = auth_response['transaction_id']++ try:+ capture_success, capture_response, capture_errors = capture(+ transaction_token, amount, **connection_params)+ except Exception as e:+ void(transaction_token, **connection_params)++ return {+ 'is_successful': capture_success,+ 'transaction_token': capture_response['transaction_id'],+ 'gateway_response': capture_response,+ 'errors': capture_errors}++def authorize(- payment: Payment,+ payment: Dict,payment_token: str,- **connection_params: Dict) -> Tuple[Transaction, str]:+ **connection_params: Dict) -> Tuple[bool, Dict, str]:gateway = get_braintree_gateway(**connection_params)+try:result = gateway.transaction.sale({- 'amount': str(payment.total),+ 'amount': str(payment['total']),'payment_method_nonce': payment_token,'options': {'submit_for_settlement': CONFIRM_MANUALLY,@@ -151,113 +154,67 @@ def authorize('required': THREE_D_SECURE_REQUIRED}},**get_customer_data(payment)})except braintree_sdk.exceptions.NotFoundError:- return transaction_and_incorrect_token_error(- payment, kind=TransactionKind.AUTH, token=payment_token)+ # FIXME: make this a payment generic exception+ raise Exception('Unable to process the transaction. '+ 'Transaction\'s token is incorrect or expired.')+gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])- credit_card_data = gateway_response.pop('credit_cart', None)- if credit_card_data:- payment.cc_first_digits = credit_card_data.bin- payment.cc_last_digits = credit_card_data.last_4- payment.cc_brand = credit_card_data.card_type- payment.cc_exp_month = credit_card_data.expiration_month- payment.cc_exp_year = credit_card_data.expiration_year- payment.save(update_fields=[- 'cc_first_digits', 'cc_last_digits', 'cc_brand',- 'cc_exp_month', 'cc_exp_year'])-- txn = create_transaction(- payment=payment,- kind=TransactionKind.AUTH,- amount=gateway_response.pop('amount', payment.total),- currency=gateway_response.pop('currency', payment.currency),- gateway_response=gateway_response,- token=getattr(result.transaction, 'id', ''),- is_success=result.is_success)- return txn, error++ return result.is_success, gateway_response, errordef capture(- payment: Payment,+ payment_token: str,amount: Decimal,- **connection_params: Dict) -> Tuple[Transaction, str]:+ **connection_params: Dict) -> Tuple[bool, Dict, str]:gateway = get_braintree_gateway(**connection_params)- auth_transaction = payment.transactions.filter(- kind=TransactionKind.AUTH, is_success=True).first()+try:result = gateway.transaction.submit_for_settlement(- transaction_id=auth_transaction.token, amount=str(amount))+ transaction_id=payment_token, amount=str(amount))except braintree_sdk.exceptions.NotFoundError:- return transaction_and_incorrect_token_error(- payment,- kind=TransactionKind.CAPTURE,- token=auth_transaction.token,- amount=amount)+ raise Exception('Unable to process the transaction. '+ 'Transaction\'s token is incorrect or expired.')gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])- txn = create_transaction(- payment=payment,- kind=TransactionKind.CAPTURE,- amount=gateway_response.pop('amount', amount),- currency=gateway_response.pop('currency', payment.currency),- token=getattr(result.transaction, 'id', ''),- is_success=result.is_success,- gateway_response=gateway_response)- return txn, error+ return result.is_success, gateway_response, errordef void(- payment: Payment,- **connection_params: Dict) -> Tuple[Transaction, str]:+ payment_token: str,+ **connection_params: Dict) -> Tuple[bool, Dict, str]:gateway = get_braintree_gateway(**connection_params)- auth_transaction = payment.transactions.filter(- kind=TransactionKind.AUTH, is_success=True).first()+try:- result = gateway.transaction.void(- transaction_id=auth_transaction.token)+ result = gateway.transaction.void(transaction_id=payment_token)except braintree_sdk.exceptions.NotFoundError:- return transaction_and_incorrect_token_error(- payment, kind=TransactionKind.VOID, token=auth_transaction.token)+ raise Exception('Unable to process the transaction. '+ 'Transaction\'s token is incorrect or expired.')gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])- txn = create_transaction(- payment=payment,- kind=TransactionKind.VOID,- amount=gateway_response.pop('amount', payment.total),- currency=gateway_response.pop('currency', payment.currency),- gateway_response=gateway_response,- token=getattr(result.transaction, 'id', ''),- is_success=result.is_success)- return txn, error++ return result.is_success, gateway_response, errordef refund(- payment: Payment,+ payment_token: str,amount: Decimal,- **connection_params: Dict) -> Tuple[Transaction, str]:+ **connection_params: Dict) -> Tuple[bool, Dict, str]:gateway = get_braintree_gateway(**connection_params)- capture_txn = payment.transactions.filter(- kind=TransactionKind.CAPTURE, is_success=True).first()+try:result = gateway.transaction.refund(- transaction_id=capture_txn.token,+ transaction_id=payment_token,amount_or_options=str(amount))except braintree_sdk.exceptions.NotFoundError:- return transaction_and_incorrect_token_error(- payment, kind=TransactionKind.REFUND, token=capture_txn.token,- amount=amount)+ raise Exception('Unable to process the transaction. '+ 'Transaction\'s token is incorrect or expired.')gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])- txn = create_transaction(- payment=payment,- kind=TransactionKind.REFUND,- amount=gateway_response.pop('amount', amount),- currency=gateway_response.pop('currency', payment.currency),- token=getattr(result.transaction, 'id', ''),- is_success=result.is_success,- gateway_response=gateway_response)- return txn, error++ return result.is_success, gateway_response, errordiff --git a/saleor/payment/gateways/braintree/forms.py b/saleor/payment/gateways/braintree/forms.pyindex 530a2f1e12..530480b7ed 100644--- a/saleor/payment/gateways/braintree/forms.py+++ b/saleor/payment/gateways/braintree/forms.py@@ -2,11 +2,8 @@ from django import formsfrom django.core.exceptions import ValidationErrorfrom django.utils.translation import pgettext_lazy-from ... import PaymentError-from ...forms import PaymentForm--class BraintreePaymentForm(PaymentForm):+class BraintreePaymentForm(forms.Form):amount = forms.DecimalField()# Unique transaction identifier returned by Braintree@@ -16,9 +13,11 @@ class BraintreePaymentForm(PaymentForm):# responsepayment_method_nonce = forms.CharField()- def __init__(self, *args, **kwargs):+ def __init__(self, amount, currency, gateway_params, *args, **kwargs):super().__init__(*args, **kwargs)- self.fields['amount'].initial = self.payment.total+ self._amount = amount+ self.fields['amount'].initial = amount+# FIXME IMPROVEMENT:# if environment is Sandbox, we could provide couple of predefined# nounces for easier testing@@ -30,23 +29,12 @@ class BraintreePaymentForm(PaymentForm):# when manually adjusting the template value as we do not allow# partial-payments at this moment, error is returned instead.amount = cleaned_data.get('amount')- if amount and amount != self.payment.total:+ if amount and amount != self._amount:msg = pgettext_lazy('payment error','Unable to process transaction. Please try again in a moment')raise ValidationError(msg)return cleaned_data- def process_payment(self):- # FIXME add tests- payment_token = self.cleaned_data['payment_method_nonce']- self.payment.token = payment_token- self.payment.save(update_fields=['token'])- self.payment.authorize(payment_token)- try:- self.payment.capture(self.payment.total)- except PaymentError as exc:- # Void authorization if the capture failed- self.payment.void()- raise exc- return self.payment+ def get_payment_token(self):+ return self.cleaned_data['payment_method_nonce']diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex 102129bdf6..41952387cd 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -19,24 +19,30 @@ def get_client_token(**connection_params):return str(uuid.uuid4())+def get_template():+ return 'order/payment/dummy.html'++def get_form_class():return DummyPaymentForm+def process_payment(+ payment: Payment, payment_token: str, amount: Decimal,+ **connection_params):+ authorize(payment_token)+ capture_success, capture_response, capture_errors = capture(+ payment, payment_token)++ return capture_success, capture_response, capture_errors++def authorize(payment: Payment, payment_token: str, **connection_params):success = dummy_success()error = Noneif not success:error = 'Unable to authorize transaction'- txn = create_transaction(- payment=payment,- kind=TransactionKind.AUTH,- amount=payment.total,- currency=payment.currency,- gateway_response={},- token=payment_token,- is_success=success)- return txn, error+ return success, {}, errordef void(payment: Payment, **connection_params: Dict):@@ -44,53 +50,30 @@ def void(payment: Payment, **connection_params: Dict):success = dummy_success()if not success:error = 'Unable to void the transaction.'- txn = create_transaction(- payment=payment,- kind=TransactionKind.VOID,- amount=payment.total,- currency=payment.currency,- gateway_response={},- token=str(uuid.uuid4()),- is_success=success)- return txn, error---def capture(payment: Payment, amount: Decimal):+ return success, {}, error+++def capture(payment: Payment, amount: Decimal, **connection_params: Dict):error = Nonesuccess = dummy_success()if not success:error = 'Unable to process capture'- txn = create_transaction(- payment=payment,- kind=TransactionKind.CAPTURE,- amount=amount,- currency=payment.currency,- token=str(uuid.uuid4()),- is_success=success)- return txn, error+ return success, {}, error-def refund(payment: Payment, amount: Decimal):+def refund(payment: Payment, amount: Decimal, **connection_params: Dict):error = Nonesuccess = dummy_success()if not success:error = 'Unable to process refund'- txn = create_transaction(- payment=payment,- kind=TransactionKind.REFUND,- amount=amount,- currency=payment.currency,- token=str(uuid.uuid4()),- is_success=success)- return txn, error+ return success, {}, errordef charge(payment: Payment, payment_token: str, amount: Decimal,**connection_params):"""Performs Authorize and Capture transactions in a single run."""- txn, error = authorize(payment, payment_token)+ is_success, response, error = authorize(payment, payment_token)if error:- return txn, error- capture_txn, capture_error = capture(payment, amount)- return capture_txn, capture_error+ return is_success, response, error+ return capture(payment, amount)diff --git a/saleor/payment/gateways/dummy/forms.py b/saleor/payment/gateways/dummy/forms.pyindex c1c4f7cded..8c34489465 100644--- a/saleor/payment/gateways/dummy/forms.py+++ b/saleor/payment/gateways/dummy/forms.py@@ -1,24 +1,19 @@+import uuid+from django import formsfrom django.utils.translation import pgettext_lazyfrom ... import ChargeStatus-from ...forms import PaymentForm-class DummyPaymentForm(PaymentForm):+class DummyPaymentForm(forms.Form):charge_status = forms.ChoiceField(label=pgettext_lazy('Payment status form field', 'Payment status'),choices=ChargeStatus.CHOICES, initial=ChargeStatus.NOT_CHARGED,widget=forms.RadioSelect)- def process_payment(self):- # Dummy provider requires no real token- fake_token = self.gateway.get_client_token(**self.gateway_params)- self.payment.authorize(fake_token)- charge_status = self.cleaned_data['charge_status']- if charge_status == ChargeStatus.NOT_CHARGED:- return- self.payment.capture()- if charge_status == ChargeStatus.FULLY_REFUNDED:- self.payment.refund()- return self.payment+ def __init__(self, amount, currency, gateway_params, *args, **kwargs):+ super().__init__(*args, **kwargs)++ def get_payment_token(self):+ return str(uuid.uuid4())diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 26a0aa8944..33da282189 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -131,35 +131,6 @@ class Payment(models.Model):"""Retrieve the maximum capture possible."""return self.total - self.captured_amount- def authorize(self, payment_token):- from . import utils- return utils.gateway_authorize(- payment=self, payment_token=payment_token)-- def charge(self, payment_token, amount=None):- from . import utils- if amount is None:- amount = self.get_charge_amount()- return utils.gateway_charge(- payment=self, payment_token=payment_token, amount=amount)-- def void(self):- from . import utils- return utils.gateway_void(payment=self)-- def capture(self, amount=None):- from . import utils- if amount is None:- amount = self.get_charge_amount()- return utils.gateway_capture(payment=self, amount=amount)-- def refund(self, amount=None):- from . import utils- if amount is None:- # If no amount is specified, refund the maximum possible- amount = self.captured_amount- return utils.gateway_refund(payment=self, amount=amount)-@propertydef is_authorized(self):return any([diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex e26df40653..46f1fb3268 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -5,9 +5,12 @@ from typing import Dict, Optionalfrom django.conf import settingsfrom django.db import transaction+from django.forms.models import model_to_dictfrom prices import Money-from . import ChargeStatus, PaymentError, get_payment_gateway+from . import (+ ChargeStatus, GatewayError, PaymentError, get_payment_gateway,+ TransactionKind)from ..core import analyticsfrom ..order import OrderEvents, OrderEventsEmailsfrom ..order.emails import send_payment_confirmation@@ -69,22 +72,14 @@ def create_payment(**payment_data):def create_transaction(- payment: Payment,- token: str,- kind: str,- is_success: bool,- amount: Decimal,- currency: str,- gateway_response: Optional[Dict] = None) -> Transaction:- if not gateway_response:- gateway_response = {}+ payment: Payment, kind: str, gateway_response: Dict) -> Transaction:txn, _ = Transaction.objects.get_or_create(payment=payment,- token=token,kind=kind,- is_success=is_success,- amount=amount,- currency=currency,+ token=gateway_response['transaction_id'],+ is_success=gateway_response['is_success'],+ amount=payment.total,+ currency=payment.currency,gateway_response=gateway_response)return txn@@ -125,9 +120,55 @@ def clean_authorize(payment: Payment):raise PaymentError('Charged transactions cannot be authorized again.')+def validate_gateway_response(response):+ """Validates response to be a correct format for Saleor to process."""+ if not isinstance(response, dict):+ raise GatewayError('gateway needs to return a dictionary')+ # TODO: check if required fields are in the dictionary+++@validate_payment+def gateway_process_payment(+ payment: Payment, payment_token: str, **kwargs) -> Transaction:+ """Performs whole payment process on a gateway."""+ gateway, gateway_params = get_payment_gateway(payment.gateway)++ try:+ gateway_response = gateway.process_payment(+ payment=model_to_dict(payment), payment_token=payment_token,+ amount=payment.total, **gateway_params)+ except Exception as e:+ return create_transaction(+ payment=payment,+ kind=TransactionKind.CAPTURE,+ currency=payment.currency,+ amount=payment.total,+ token=payment_token,+ is_success=False)++ validate_gateway_response(gateway_response)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.CAPTURE,+ gateway_response=gateway_response)++ if txn.is_success:+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += txn.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)+ else:+ raise PaymentError(error)++ return txn++@validate_paymentdef gateway_charge(- payment: Payment, payment_token: str, amount: Decimal) -> Transaction:+ payment: Payment, payment_token: str, amount: Decimal=None) -> Transaction:"""Performs authorization and capture in a single run.For gateways not supporting the authorization it should be a@@ -137,24 +178,43 @@ def gateway_charge(it should create two transaction - auth and capture, but only the last oneis returned."""+ if amount is None:+ amount = payment.get_charge_amount()clean_charge(payment, amount)gateway, gateway_params = get_payment_gateway(payment.gateway)- with transaction.atomic():- txn, error = gateway.charge(+ try:+ is_success, gateway_response, error = gateway.charge(+ payment=model_to_dict(payment), payment_token=payment_token,+ amount=amount, **gateway_params)+ except Exception as e:+ return create_transaction(payment=payment,- payment_token=payment_token,- amount=amount,- **gateway_params)- if txn.is_success:- payment.charge_status = ChargeStatus.CHARGED- payment.captured_amount += txn.amount- payment.save(update_fields=['charge_status', 'captured_amount'])- order = payment.order- if order and order.is_fully_paid():- handle_fully_paid_order(order)- if not txn.is_success:+ kind=TransactionKind.CHARGE,+ currency=payment.currency,+ amount=payment.total,+ token=payment_token,+ is_success=False)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.AUTH,+ amount=gateway_response.get('amount', payment.total),+ currency=gateway_response.get('currency', payment.currency),+ gateway_response=gateway_response,+ token=gateway_response.get('transaction_id', ''),+ is_success=is_success)++ if txn.is_success:+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += txn.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)+ else:raise PaymentError(error)+return txn@@ -168,32 +228,77 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:clean_authorize(payment)gateway, gateway_params = get_payment_gateway(payment.gateway)- with transaction.atomic():- txn, error = gateway.authorize(- payment=payment, payment_token=payment_token, **gateway_params)+ try:+ is_success, gateway_response, error = gateway.authorize(+ payment=model_to_dict(payment), payment_token=payment_token,+ **gateway_params)+ except Exception as e:+ return create_transaction(+ payment=payment,+ kind=TransactionKind.AUTH,+ currency=payment.currency,+ amount=payment.total,+ token=payment_token,+ is_success=False)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.AUTH,+ amount=gateway_response.get('amount', payment.total),+ currency=gateway_response.get('currency', payment.currency),+ gateway_response=gateway_response,+ token=gateway_response.get('transaction_id', ''),+ is_success=is_success)+if not txn.is_success:raise PaymentError(error)+return txn@validate_payment-def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:+def gateway_capture(payment: Payment, amount: Decimal=None) -> Transaction:"""Captures the money that was reserved during the authorization stage."""+ if amount is None:+ amount = payment.get_charge_amount()clean_capture(payment, amount)+ auth_transaction = payment.transactions.filter(+ kind=TransactionKind.AUTH, is_success=True).first()+ payment_token = auth_transaction.token+gateway, gateway_params = get_payment_gateway(payment.gateway)- with transaction.atomic():- txn, error = gateway.capture(- payment=payment, amount=amount, **gateway_params)- if txn.is_success:- payment.charge_status = ChargeStatus.CHARGED- payment.captured_amount += txn.amount- payment.save(update_fields=['charge_status', 'captured_amount'])- order = payment.order- if order and order.is_fully_paid():- handle_fully_paid_order(order)- if not txn.is_success:+ try:+ is_success, gateway_response, error = gateway.capture(+ payment_token=payment_token, amount=amount, **gateway_params)+ except:+ return create_transaction(+ payment=payment,+ kind=TransactionKind.CAPTURE,+ currency=payment.currency,+ amount=amount,+ token=payment_token,+ is_success=False)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.CAPTURE,+ amount=gateway_response.get('amount', amount),+ currency=gateway_response.get('currency', payment.currency),+ gateway_response=gateway_response,+ token=gateway_response.get('transaction_id'),+ is_success=is_success)++ if txn.is_success:+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += txn.amount+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)+ else:raise PaymentError(error)+return txn@@ -201,41 +306,95 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:def gateway_void(payment) -> Transaction:if not payment.can_void():raise PaymentError('Only pre-authorized transactions can be voided.')++ auth_transaction = payment.transactions.filter(+ kind=TransactionKind.AUTH, is_success=True).first()+ payment_token = auth_transaction.token+gateway, gateway_params = get_payment_gateway(payment.gateway)- with transaction.atomic():- txn, error = gateway.void(payment=payment, **gateway_params)- if txn.is_success:- payment.is_active = False- payment.save(update_fields=['is_active'])- if not txn.is_success:+ try:+ is_success, gateway_response, error = gateway.void(+ payment_token=payment_token, **gateway_params)+ except:+ return create_transaction(+ payment=payment,+ kind=TransactionKind.VOID,+ currency=payment.currency,+ amount=payment.total,+ token=payment_token,+ is_success=False)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.CAPTURE,+ amount=gateway_response.get('amount', payment.total),+ currency=gateway_response.get('currency', payment.currency),+ gateway_response=gateway_response,+ token=payment_token,+ is_success=is_success)++ if txn.is_success:+ payment.is_active = False+ payment.save(update_fields=['is_active'])+ else:raise PaymentError(error)+return txn@validate_payment-def gateway_refund(payment, amount: Decimal) -> Transaction:+def gateway_refund(payment, amount: Decimal=None) -> Transaction:"""Refunds 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:+ elif amount > payment.captured_amount:raise PaymentError('Cannot refund more than captured')- if not payment.can_refund():- raise PaymentError('This payment cannot be refunded.')++ transaction = payment.transactions.filter(+ kind__in=[TransactionKind.CAPTURE, TransactionKind.CHARGE],+ is_success=True).first()+ payment_token = transaction.tokengateway, gateway_params = get_payment_gateway(payment.gateway)- with transaction.atomic():- txn, error = gateway.refund(- payment=payment, amount=amount, **gateway_params)- if txn.is_success:- changed_fields = ['captured_amount']- payment.captured_amount -= txn.amount- if not payment.captured_amount:- payment.charge_status = ChargeStatus.FULLY_REFUNDED- payment.is_active = False- changed_fields += ['charge_status', 'is_active']- payment.save(update_fields=changed_fields)- if not txn.is_success:+ try:+ is_success, gateway_response, error = gateway.refund(+ payment_token=payment_token, amount=amount, **gateway_params)+ except:+ return create_transaction(+ payment=payment,+ kind=TransactionKind.REFUND,+ currency=payment.currency,+ amount=amount,+ token=payment_token,+ is_success=False)++ txn = create_transaction(+ payment=payment,+ kind=TransactionKind.REFUND,+ amount=gateway_response.get('amount', amount),+ currency=gateway_response.get('currency', payment.currency),+ gateway_response=gateway_response,+ token=payment_token,+ is_success=is_success)++ if txn.is_success:+ changed_fields = ['captured_amount']+ payment.captured_amount -= txn.amount+ if not payment.captured_amount:+ payment.charge_status = ChargeStatus.FULLY_REFUNDED+ payment.is_active = False+ changed_fields += ['charge_status', 'is_active']+ payment.save(update_fields=changed_fields)+ else:raise PaymentError(error)+return txndiff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.pyindex 0841e3b9ff..1cdcd7276b 100644--- a/tests/gateway/test_dummy.py+++ b/tests/gateway/test_dummy.py@@ -4,6 +4,9 @@ import pytestfrom saleor.payment import (ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)+from saleor.payment.utils import (+ gateway_authorize, gateway_capture, gateway_charge, gateway_void,+ gateway_process_payment, gateway_refund)from saleor.payment.gateways.dummy.forms import DummyPaymentForm@@ -31,7 +34,9 @@ def test_charge_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.gateways.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_dummy.charge(payment_token='Fake', amount=payment_dummy.total)+ txn = gateway_charge(+ payment=payment_dummy, payment_token='Fake',+ amount=payment_dummy.total)assert txn.kind == TransactionKind.CHARGEassert not txn.is_successassert txn.payment == payment_dummy@@ -49,12 +54,12 @@ def test_charge_failed(is_active, charge_status, payment_dummy):payment.charge_status = charge_statuspayment.save()with pytest.raises(PaymentError):- txn = payment.charge(payment_token='Fake')+ txn = gateway_charge(payment=payment, payment_token='Fake')assert txn is Nonedef test_authorize_success(payment_dummy):- txn = payment_dummy.authorize(payment_token='Fake')+ txn = gateway_authorize(payment=payment_dummy, payment_token='Fake')assert txn.is_successassert txn.kind == TransactionKind.AUTHassert txn.payment == payment_dummy@@ -75,7 +80,7 @@ def test_authorize_failed(is_active, charge_status, payment_dummy):payment.charge_status = charge_statuspayment.save()with pytest.raises(PaymentError):- txn = payment.authorize(payment_token='Fake')+ txn = gateway_authorize(payment=payment, payment_token='Fake')assert txn is None@@ -83,7 +88,7 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.gateways.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_dummy.authorize(payment_token='Fake')+ txn = gateway_authorize(payment=payment_dummy, payment_token='Fake')assert txn.kind == TransactionKind.AUTHassert not txn.is_successassert txn.payment == payment_dummy@@ -92,7 +97,7 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):def test_void_success(payment_txn_preauth):assert payment_txn_preauth.is_activeassert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED- txn = payment_txn_preauth.void()+ txn = gateway_void(payment=payment_txn_preauth)assert txn.is_successassert txn.kind == TransactionKind.VOIDassert txn.payment == payment_txn_preauth@@ -113,7 +118,7 @@ def test_void_failed(is_active, charge_status, payment_dummy):payment.charge_status = charge_statuspayment.save()with pytest.raises(PaymentError):- txn = payment.void()+ txn = gateway_void(payment=payment)assert txn is None@@ -121,7 +126,7 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):monkeypatch.setattr('saleor.payment.gateways.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_txn_preauth.void()+ txn = gateway_void(payment=payment_txn_preauth)assert txn.kind == TransactionKind.VOIDassert not txn.is_successassert txn.payment == payment_txn_preauth@@ -129,7 +134,7 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):@pytest.mark.parametrize('amount', [80, 70])def test_capture_success(amount, payment_txn_preauth):- txn = payment_txn_preauth.capture(amount=amount)+ txn = gateway_capture(payment=payment_txn_preauth, amount=amount)assert txn.is_successassert txn.payment == payment_txn_preauthpayment_txn_preauth.refresh_from_db()@@ -152,7 +157,7 @@ def test_capture_failed(payment.charge_status = charge_statuspayment.save()with pytest.raises(PaymentError):- txn = payment.capture(amount=amount)+ txn = gateway_capture(payment=payment, amount=amount)assert txn is None@@ -160,7 +165,7 @@ def test_capture_gateway_error(payment_txn_preauth, monkeypatch):monkeypatch.setattr('saleor.payment.gateways.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_txn_preauth.capture(80)+ txn = gateway_capture(payment=payment_txn_preauth, amount=80)assert txn.kind == TransactionKind.CHARGEassert not txn.is_successassert txn.payment == payment_txn_preauth@@ -173,12 +178,12 @@ def test_capture_gateway_error(payment_txn_preauth, monkeypatch):(80, 10, 70, ChargeStatus.CHARGED, True), ])def test_refund_success(initial_captured_amount, refund_amount, final_captured_amount,- final_charge_status, active_after, payment_dummy):- payment = payment_dummy+ final_charge_status, active_after, payment_txn_captured):+ payment = payment_txn_capturedpayment.charge_status = ChargeStatus.CHARGEDpayment.captured_amount = initial_captured_amountpayment.save()- txn = payment.refund(refund_amount)+ txn = gateway_refund(payment=payment, amount=refund_amount)assert txn.kind == TransactionKind.REFUNDassert txn.is_successassert txn.payment == payment@@ -200,19 +205,19 @@ def test_refund_failed(payment.captured_amount = Decimal(initial_captured_amount)payment.save()with pytest.raises(PaymentError):- txn = payment.refund(refund_amount)+ txn = gateway_refund(payment=payment, amount=refund_amount)assert txn is None-def test_refund_gateway_error(payment_dummy, monkeypatch):+def test_refund_gateway_error(payment_txn_captured, monkeypatch):monkeypatch.setattr('saleor.payment.gateways.dummy.dummy_success', lambda: False)- payment = payment_dummy+ payment = payment_txn_capturedpayment.charge_status = ChargeStatus.CHARGEDpayment.captured_amount = Decimal('80.00')payment.save()with pytest.raises(PaymentError):- payment.refund(Decimal('80.00'))+ gateway_refund(payment=payment, amount=Decimal('80.00'))payment.refresh_from_db()txn = payment.transactions.first()@@ -234,11 +239,11 @@ def test_dummy_payment_form(kind, charge_status, settings, payment_dummy):data = {'charge_status': charge_status}payment_gateway, gateway_params = get_payment_gateway(payment.gateway)- form = DummyPaymentForm(- data=data, payment=payment, gateway=payment_gateway,- gateway_params=gateway_params)+ form = DummyPaymentForm(data=data, amount=payment.total,+ currency=payment.currency, gateway_params=gateway_params)assert form.is_valid()- form.process_payment()+ gateway_process_payment(+ payment=payment, payment_token=form.get_payment_token())payment.refresh_from_db()assert payment.transactions.last().kind == kinddiff --git a/tests/test_payment.py b/tests/test_payment.pyindex 16d149239b..0ab66e35f5 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -381,7 +381,7 @@ def test_gateway_charge_failed(payment = payment_txn_preauthamount = payment.total- mock_charge = Mock(return_value=(txn, EXAMPLE_ERROR))+ mock_charge = Mock(return_value=(False, {}, EXAMPLE_ERROR))mock_get_payment_gateway.return_value = (Mock(charge=mock_charge), gateway_params)with pytest.raises(PaymentError) as exc:@@ -419,12 +419,13 @@ def test_gateway_void(mock_get_payment_gateway, payment_txn_preauth, gateway_parpayment = payment_txn_preauthassert payment.is_active- mock_void = Mock(return_value=(txn, ''))+ mock_void = Mock(return_value=(True, {}, ''))mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)gateway_void(payment)mock_get_payment_gateway.assert_called_once_with(payment.gateway)- mock_void.assert_called_once_with(payment=payment, **gateway_params)+ mock_void.assert_called_once_with(+ payment_token=txn.transaction_id, **gateway_params)payment.refresh_from_db()assert payment.is_active == False@@ -437,7 +438,7 @@ def test_gateway_void_failed(txn.is_success = Falsepayment = payment_txn_preauth- mock_void = Mock(return_value=(txn, EXAMPLE_ERROR))+ mock_void = Mock(return_value=(False, {}, EXAMPLE_ERROR))mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)with pytest.raises(PaymentError) as exc:gateway_void(payment)@@ -461,7 +462,7 @@ def test_gateway_refund(payment = payment_txn_capturedamount = payment.total- mock_refund = Mock(return_value=(txn, ''))+ mock_refund = Mock(return_value=(True, {}, ''))mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)@@ -484,7 +485,7 @@ def test_gateway_refund_partial_refund(txn.amount = amounttxn.currency = settings.DEFAULT_CURRENCY- mock_refund = Mock(return_value=(txn, ''))+ mock_refund = Mock(return_value=(True, {}, ''))mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)@@ -503,7 +504,7 @@ def test_gateway_refund_failed(captured_before = payment.captured_amounttxn.is_success = False- mock_refund = Mock(return_value=(txn, EXAMPLE_ERROR))+ mock_refund = Mock(return_value=(False, {}, EXAMPLE_ERROR))mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)