Skip to content

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

Charge payments at the end of CheckoutComplete

Pacu22b32e87dcfa0
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 10537c2ef5..def1ca1df2 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -888,7 +888,7 @@ def create_order(cart, tracking_code, discounts, taxes):
def is_fully_paid(cart: Cart):
payments = cart.payments.filter(is_active=True)
total_paid = sum(
- [p.captured_amount.amount for p in payments])
+ [p.total.amount for p in payments])
return total_paid >= cart.get_total().gross.amount
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 355b92153f..d68f49c8ee 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -10,6 +10,8 @@ from ...checkout.utils import (
from ...core import analytics
from ...core.exceptions import InsufficientStock
from ...core.utils.taxes import get_taxes_for_address
+from ...payment import PaymentError
+from ...payment.utils import gateway_authorize, gateway_capture, gateway_void
from ...shipping.models import ShippingMethod as ShippingMethodModel
from ..account.i18n import I18nMixin
from ..account.types import AddressInput, User
@@ -423,4 +425,23 @@ class CheckoutComplete(BaseMutation):
cls.add_error(
field=None, message='Insufficient product stock.',
errors=errors)
+
+ payment = checkout.payments.filter(is_active=True).first()
+ # FIXME there could be a situation where order was created but payment
+ # failed. we should cancel the order at this moment I think
+ # authorize payment
+ try:
+ gateway_authorize(payment, payment.token)
+ except PaymentError as exc:
+ msg = str(exc)
+ cls.add_error(field=None, message=msg, errors=errors)
+ return CheckoutComplete(order=order, errors=errors)
+ # capture payment
+ try:
+ gateway_capture(payment, payment.total.amount)
+ except PaymentError as exc:
+ msg = str(exc)
+ cls.add_error(field=None, message=msg, errors=errors)
+ # Void payment if the capture failed
+ gateway_void(payment)
return CheckoutComplete(order=order, errors=errors)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 7d9dd525a9..fc17e54835 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -58,21 +58,17 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
billing_data = cls.clean_billing_address(billing_address)
extra_data = cls.get_extra_info(info)
gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)
+ # FIXME as we allow only one payment make sure that amount
+ # is same as checkout's total
payment = create_payment(
total=gross,
variant=input['gateway'],
billing_email=checkout.email,
+ is_active=True,
extra_data=extra_data,
checkout=checkout,
+ token=input['transaction_token'],
**billing_data)
-
- # authorize payment
- try:
- gateway_authorize(payment, input['transaction_token'])
- except PaymentError as exc:
- msg = str(exc)
- cls.add_error(field=None, message=msg, errors=errors)
-
return CheckoutPaymentCreate(payment=payment, errors=errors)
@classmethod
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
index 54aeaebd63..fbc2e49662 100644
--- a/saleor/payment/forms.py
+++ b/saleor/payment/forms.py
@@ -74,5 +74,10 @@ class BraintreePaymentForm(forms.Form):
def process_payment(self):
# FIXME add tests
self.instance.authorize(self.cleaned_data['payment_method_nonce'])
- self.instance.capture(self.instance.total.amount)
+ try:
+ self.instance.capture(self.instance.total.amount)
+ except PaymentError as exc:
+ # Void authorization if the capture failed
+ self.instance.void()
+ raise exc
return self.instance
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index d783ee0575..65762c19ff 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -83,29 +83,21 @@ class Payment(models.Model):
return txn
def authorize(self, transaction_token):
- # FIXME Used for backwards compatibility, remove after moving to
- # dashboard 2.0
from . import utils
return utils.gateway_authorize(
payment=self, transaction_token=transaction_token)
def void(self):
- # FIXME Used for backwards compatibility, remove after moving to
- # dashboard 2.0
from . import utils
return utils.gateway_void(payment=self)
def capture(self, amount=None):
- # FIXME Used for backwards compatibility, remove after moving to
- # dashboard 2.0
from . import utils
if amount is None:
amount = self.total.amount
return utils.gateway_capture(payment=self, amount=amount)
def refund(self, amount=None):
- # FIXME Used for backwards compatibility, remove after moving to
- # dashboard 2.0
from . import utils
if amount is None:
amount = self.total.amount
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 03cd4e2116..67d6110cc0 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -370,16 +370,10 @@ def test_checkout_complete(
payment.is_active = True
payment.order = None
payment.total = total.gross
- payment.captured_amount = total.gross
payment.checkout = checkout
payment.save()
- payment.transactions.create(
- transaction_type=TransactionType.AUTH,
- is_success=True,
- gateway_response={},
- amount=total.gross.amount)
checkout_id = graphene.Node.to_global_id('Checkout', checkout.pk)
-
+ assert not payment.transactions.exists()
query = """
mutation checkoutComplete($checkoutId: ID!) {
checkoutComplete(checkoutId: $checkoutId) {
@@ -414,6 +408,7 @@ def test_checkout_complete(
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
+ assert payment.transactions.count() == 2
def test_fetch_checkout_by_token(user_api_client, cart_with_item):
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index d58bb16e81..6064f504ee 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -1,8 +1,8 @@
import graphene
-from saleor.payment.models import (
- ChargeStatus, Transaction, TransactionType)
from tests.api.utils import get_graphql_content
+from saleor.payment.models import (
+ ChargeStatus, Payment, Transaction, TransactionType)
VOID_QUERY = """
mutation PaymentVoid($paymentId: ID!) {
@@ -63,6 +63,7 @@ def test_payment_charge_gateway_error(
assert txn.transaction_type == TransactionType.VOID
assert not txn.is_success
+
CREATE_QUERY = """
mutation CheckoutPaymentCreate($input: PaymentInput!) {
checkoutPaymentCreate(input: $input) {
@@ -104,14 +105,12 @@ def test_checkout_add_payment(
content = get_graphql_content(response)
data = content['data']['checkoutPaymentCreate']
assert not data['errors']
- transaction_token = data['payment']['transactions']['edges'][0]['node'][
- 'token']
- txn = Transaction.objects.filter(token=transaction_token).first()
- assert txn.transaction_type == TransactionType.AUTH
- assert txn is not None
- payment = txn.payment
+ transactions = data['payment']['transactions']['edges']
+ assert not transactions
+ payment = Payment.objects.get()
assert payment.checkout == cart
assert payment.is_active
+ assert payment.token == 'sample-token'
assert payment.total == cart.get_total().gross
assert payment.charge_status == ChargeStatus.NOT_CHARGED