Skip to content

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

Reorganize the checkout process logic over the API

NyanKiyoshi3cf32a0e87e7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe244976ed..0dd31c2daf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Default default PAGINATE_BY - #4238 by @dominik-zeglen
- Add basic Gift Cards support in the backend - #4025 by @fowczarek
- Create generic filtering interface - #4221 by @dominik-zeglen
+- API checkout payment can fail without creating an order and deleting checkout - #4154 by @NyanKiyoshi
+- Payment gateways are now optionally receiving the `order_id` field from the `PaymentData` object. Thus should not rely on that information. - #4154 by @NyanKiyoshi
## 2.6.0
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 81ed2cd0c0..4d4cd59137 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -22,7 +22,7 @@ from ..core.utils.promo_code import (
promo_code_is_gift_card,
promo_code_is_voucher,
)
-from ..core.utils.taxes import ZERO_MONEY, get_taxes_for_country
+from ..core.utils.taxes import ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_country
from ..discount import VoucherType
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
@@ -37,7 +37,8 @@ from ..giftcard.utils import (
)
from ..order import events
from ..order.emails import send_order_confirmation
-from ..order.models import Order
+from ..order.models import Order, OrderLine
+from ..product.models import ProductVariant
from ..shipping.models import ShippingMethod
from . import AddressType, logger
from .forms import (
@@ -46,7 +47,7 @@ from .forms import (
AnonymousUserShippingForm,
BillingAddressChoiceForm,
)
-from .models import Checkout
+from .models import Checkout, CheckoutLine
COOKIE_NAME = "checkout"
@@ -906,7 +907,11 @@ def clear_shipping_method(checkout):
def _process_voucher_data_for_order(checkout):
- """Fetch, process and return voucher/discount data from checkout."""
+ """
+ Fetch, process and return voucher/discount data from checkout.
+
+ :raises NotApplicable: When the voucher is not applicable in the current checkout.
+ """
vouchers = Voucher.objects.active(date=date.today()).select_for_update()
voucher = get_voucher_for_checkout(checkout, vouchers)
@@ -980,26 +985,45 @@ def validate_gift_cards(checkout: Checkout):
raise NotApplicable(msg)
-def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user: User):
- """Create an order from the checkout.
+def create_line_for_order(
+ variant: ProductVariant, quantity: int, discounts, taxes
+) -> OrderLine:
+ """
+ :raises InsufficientStock: when there is not enough items in stock for this variant
+ """
- Each order will get a private copy of both the billing and the shipping
- address (if shipping).
+ variant.check_quantity(quantity)
- If any of the addresses is new and the user is logged in the address
- will also get saved to that user's address book.
+ product_name = variant.display_product()
+ translated_product_name = variant.display_product(translated=True)
- Current user's language is saved in the order so we can later determine
- which language to use when sending email.
- """
- from ..order.utils import add_gift_card_to_order, add_variant_to_order
+ if translated_product_name == product_name:
+ translated_product_name = ""
- order = Order.objects.filter(checkout_token=checkout.token).first()
- if order is not None:
- return order
+ line = OrderLine(
+ product_name=product_name,
+ translated_product_name=translated_product_name,
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ quantity=quantity,
+ variant=variant,
+ unit_price=variant.get_price(discounts, taxes),
+ tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes),
+ )
+
+ return line
+
+
+def prepare_order_data(
+ *, checkout: Checkout, tracking_code: str, discounts, taxes
+) -> dict:
+ """
+ Runs checks and returns all the data from a given checkout to create an order.
+ :raises NotApplicable InsufficientStock:
+ """
order_data = {}
+
order_data.update(_process_voucher_data_for_order(checkout))
order_data.update(_process_shipping_data_for_order(checkout, taxes))
order_data.update(_process_user_data_for_order(checkout))
@@ -1011,30 +1035,67 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user:
}
)
+ order_data["lines"] = [
+ create_line_for_order(
+ variant=line.variant,
+ quantity=line.quantity,
+ discounts=discounts,
+ taxes=taxes,
+ )
+ for line in checkout # type: CheckoutLine
+ ]
+
# validate checkout gift cards
validate_gift_cards(checkout)
- order = Order.objects.create(**order_data, checkout_token=checkout.token)
-
- # create order lines from checkout lines
- for line in checkout:
- add_variant_to_order(order, line.variant, line.quantity, discounts, taxes)
-
# assign gift cards to the order
- total_price_left = (
+ order_data["total_price_left"] = (
checkout.get_subtotal(discounts, taxes)
+ checkout.get_shipping_price(taxes)
- checkout.discount_amount
).gross
+
+ return order_data
+
+
+def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
+ """Create an order from the checkout.
+
+ Each order will get a private copy of both the billing and the shipping
+ address (if shipping).
+
+ If any of the addresses is new and the user is logged in the address
+ will also get saved to that user's address book.
+
+ Current user's language is saved in the order so we can later determine
+ which language to use when sending email.
+ """
+ from ..product.utils import allocate_stock
+ from ..order.utils import add_gift_card_to_order
+
+ order = Order.objects.filter(checkout_token=checkout.token).first()
+ if order is not None:
+ return order
+
+ total_price_left = order_data.pop("total_price_left")
+ order_lines = order_data.pop("lines")
+ order = Order.objects.create(**order_data, checkout_token=checkout.token)
+ order.lines.set(order_lines, bulk=False)
+
+ # allocate stocks from the lines
+ for line in order_lines: # type: OrderLine
+ variant = line.variant
+ if variant.track_inventory:
+ allocate_stock(variant, line.quantity)
+
+ # Add gift cards to the order
for gift_card in checkout.gift_cards.select_for_update():
total_price_left = add_gift_card_to_order(order, gift_card, total_price_left)
# assign checkout payments to the order
checkout.payments.update(order=order)
- # remove checkout after order is created
- checkout.delete()
-
# Create the order placed
events.order_created_event(order=order, user=user)
diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.py
index d340725175..a3ccce1fb7 100644
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@ -12,6 +12,7 @@ from ..utils import (
create_order,
get_checkout_context,
get_taxes_for_checkout,
+ prepare_order_data,
update_billing_address_in_anonymous_checkout,
update_billing_address_in_checkout,
update_billing_address_in_checkout_with_shipping,
@@ -26,12 +27,12 @@ def _handle_order_placement(request, checkout):
and creating order history events.
"""
try:
- order = create_order(
+ # Run checks an prepare the data for order creation
+ order_data = prepare_order_data(
checkout=checkout,
tracking_code=analytics.get_client_id(request),
discounts=request.discounts,
taxes=get_taxes_for_checkout(checkout, request.taxes),
- user=request.user,
)
except InsufficientStock:
return redirect("checkout:index")
@@ -41,6 +42,12 @@ def _handle_order_placement(request, checkout):
)
return redirect("checkout:summary")
+ # Push the order data into the database
+ order = create_order(checkout=checkout, order_data=order_data, user=request.user)
+
+ # remove checkout after order is created
+ checkout.delete()
+
# Redirect the user to the payment page
return redirect("order:payment", token=order.token)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 2a0482b525..278f807cc3 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -17,6 +17,7 @@ from ...checkout.utils import (
get_or_create_user_checkout,
get_taxes_for_checkout,
get_voucher_for_checkout,
+ prepare_order_data,
recalculate_checkout_discount,
remove_promo_code_from_checkout,
remove_voucher_from_checkout,
@@ -26,6 +27,7 @@ from ...core.exceptions import InsufficientStock
from ...core.utils.taxes import get_taxes_for_address
from ...discount import models as voucher_model
from ...payment import PaymentError
+from ...payment.interface import AddressData
from ...payment.utils import gateway_process_payment
from ...shipping.models import ShippingMethod as ShippingMethodModel
from ..account.i18n import I18nMixin
@@ -501,24 +503,38 @@ class CheckoutComplete(BaseMutation):
payment = checkout.get_last_active_payment()
try:
- order = create_order(
+ order_data = prepare_order_data(
checkout=checkout,
tracking_code=analytics.get_client_id(info.context),
discounts=info.context.discounts,
- taxes=get_taxes_for_checkout(checkout, info.context.taxes),
- user=info.context.user,
+ taxes=taxes,
)
- except InsufficientStock:
- raise ValidationError("Insufficient product stock.")
+ except InsufficientStock as e:
+ raise ValidationError(f"Insufficient product stock: {e.item}")
except voucher_model.NotApplicable:
raise ValidationError("Voucher not applicable")
- payment.order = order
-
try:
- gateway_process_payment(payment=payment, payment_token=payment.token)
+ billing_address = order_data["billing_address"] # type: models.Address
+ shipping_address = order_data["shipping_address"] # type: models.Address
+ gateway_process_payment(
+ payment=payment,
+ payment_token=payment.token,
+ billing_address=AddressData(**billing_address.as_data()),
+ shipping_address=AddressData(**shipping_address.as_data()),
+ )
except PaymentError as e:
raise ValidationError(str(e))
+
+ # create the order into the database
+ order = create_order(
+ checkout=checkout, order_data=order_data, user=info.context.user
+ )
+
+ # remove checkout after order is successfully paid
+ checkout.delete()
+
+ # return the success response with the newly created order data
return CheckoutComplete(order=order)
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 377a84211a..807af6b3f5 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -44,7 +44,7 @@ class PaymentData:
currency: str
billing: Optional[AddressData]
shipping: Optional[AddressData]
- order_id: int
+ order_id: Optional[int]
customer_ip_address: str
customer_email: str
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 3ff8fa1da8..0d247089e6 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -56,7 +56,11 @@ def get_gateway_operation_func(gateway, operation_type):
def create_payment_information(
- payment: Payment, payment_token: str = None, amount: Decimal = None
+ payment: Payment,
+ payment_token: str = None,
+ amount: Decimal = None,
+ billing_address: AddressData = None,
+ shipping_address: AddressData = None,
) -> PaymentData:
"""Extracts order information along with payment details.
@@ -65,19 +69,21 @@ def create_payment_information(
"""
billing, shipping = None, None
- if payment.order.billing_address:
+ if billing_address is None and payment.order.billing_address:
billing = AddressData(**payment.order.billing_address.as_data())
- if payment.order.shipping_address:
+ if shipping_address is None and payment.order.shipping_address:
shipping = AddressData(**payment.order.shipping_address.as_data())
+ order_id = payment.order.pk if payment.order else None
+
return PaymentData(
token=payment_token,
amount=amount or payment.total,
currency=payment.currency,
billing=billing,
shipping=shipping,
- order_id=payment.order.id,
+ order_id=order_id,
customer_ip_address=payment.customer_ip_address,
customer_email=payment.billing_email,
)
@@ -381,13 +387,16 @@ def _gateway_postprocess(transaction, payment):
@require_active_payment
-def gateway_process_payment(payment: Payment, payment_token: str) -> Transaction:
+def gateway_process_payment(
+ payment: Payment, payment_token: str, **extras
+) -> Transaction:
"""Performs whole payment process on a gateway."""
transaction = call_gateway(
operation_type=OperationType.PROCESS_PAYMENT,
payment=payment,
payment_token=payment_token,
amount=payment.total,
+ **extras,
)
_gateway_postprocess(transaction, payment)
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index fa3f43082d..c9dff9459d 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -10,6 +10,7 @@ from saleor.checkout.utils import clean_checkout, is_fully_paid
from saleor.core.utils.taxes import ZERO_MONEY
from saleor.graphql.core.utils import str_to_enum
from saleor.order.models import Order
+from saleor.payment import PaymentError
from tests.api.utils import get_graphql_content
MUTATION_CHECKOUT_CREATE = """
@@ -931,9 +932,58 @@ def test_checkout_complete(
assert gift_card.current_balance == ZERO_MONEY
assert gift_card.last_used_on
- # assert that the checkout instance has been deleted after checkout
- with pytest.raises(Checkout.DoesNotExist):
- checkout.refresh_from_db()
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+
+
+@patch("saleor.graphql.checkout.mutations.gateway_process_payment")
+def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
+ mocked_process_payment,
+ user_api_client,
+ checkout_with_item,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ def _process_payment(*args, **kwargs):
+ raise PaymentError("Oops! Something went wrong.")
+
+ mocked_process_payment.side_effect = _process_payment
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ total = checkout.get_total()
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ variables = {"checkoutId": checkout_id}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["errors"] == [{"field": None, "message": "Oops! Something went wrong."}]
+
+ assert Order.objects.count() == orders_count
+
+ payment.refresh_from_db(fields=["order"])
+ assert payment.transactions.count() == 0
+ assert payment.order is None
+
+ assert Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should not have been deleted"
def test_checkout_complete_invalid_checkout_id(user_api_client):
@@ -964,7 +1014,7 @@ def test_checkout_complete_no_payment(
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
assert data["errors"][0]["message"] == (
- "Provided payment methods can not " "cover the checkout's total amount"
+ "Provided payment methods can not cover the checkout's total amount"
)
assert orders_count == Order.objects.count()
@@ -995,7 +1045,7 @@ def test_checkout_complete_insufficient_stock(
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
- assert data["errors"][0]["message"] == "Insufficient product stock."
+ assert data["errors"][0]["message"] == "Insufficient product stock: 123"
assert orders_count == Order.objects.count()
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 84db1f8ca1..1d75ce9af4 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -25,6 +25,7 @@ from saleor.checkout.utils import (
get_voucher_discount_for_checkout,
get_voucher_for_checkout,
is_valid_shipping_method,
+ prepare_order_data,
recalculate_checkout_discount,
remove_voucher_from_checkout,
)
@@ -575,10 +576,10 @@ def test_create_order_creates_expected_events(
# Place checkout
order = create_order(
- checkout,
- "tracking_code",
- discounts=None,
- taxes=None,
+ checkout=checkout,
+ order_data=prepare_order_data(
+ checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
+ ),
user=customer_user if not is_anonymous_user else AnonymousUser(),
)
@@ -627,12 +628,11 @@ def test_create_order_insufficient_stock(
request_checkout.save()
with pytest.raises(InsufficientStock):
- create_order(
- request_checkout,
- "tracking_code",
+ prepare_order_data(
+ checkout=request_checkout,
+ tracking_code="tracking_code",
discounts=None,
taxes=None,
- user=customer_user,
)
@@ -646,18 +646,15 @@ def test_create_order_doesnt_duplicate_order(
checkout.shipping_method = shipping_method
checkout.save()
- with patch.object(checkout, "delete") as mocked_delete:
- order_1 = create_order(
- checkout, tracking_code="", discounts=None, taxes=None, user=customer_user
- )
- assert order_1.checkout_token == checkout.token
+ order_data = prepare_order_data(
+ checkout=checkout, tracking_code="", discounts=None, taxes=None
+ )
- order_2 = create_order(
- checkout, tracking_code="", discounts=None, taxes=None, user=customer_user
- )
- assert order_1.pk == order_2.pk
+ order_1 = create_order(checkout=checkout, order_data=order_data, user=customer_user)
+ assert order_1.checkout_token == checkout.token
- assert mocked_delete.call_count == 1
+ order_2 = create_order(checkout=checkout, order_data=order_data, user=customer_user)
+ assert order_1.pk == order_2.pk
@pytest.mark.parametrize("is_anonymous_user", (True, False))
@@ -681,9 +678,9 @@ def test_create_order_with_gift_card(
order = create_order(
checkout=checkout,
- tracking_code="tracking_code",
- discounts=None,
- taxes=None,
+ order_data=prepare_order_data(
+ checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
+ ),
user=customer_user if not is_anonymous_user else AnonymousUser(),
)
@@ -710,9 +707,9 @@ def test_create_order_with_gift_card_partial_use(
order = create_order(
checkout=checkout,
- tracking_code="tracking_code",
- discounts=None,
- taxes=None,
+ order_data=prepare_order_data(
+ checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
+ ),
user=customer_user,
)
@@ -750,9 +747,9 @@ def test_create_order_with_many_gift_cards(
order = create_order(
checkout=checkout,
- tracking_code="tracking_code",
- discounts=None,
- taxes=None,
+ order_data=prepare_order_data(
+ checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
+ ),
user=customer_user,
)
@@ -771,10 +768,13 @@ def test_note_in_created_order(request_checkout_with_item, address, customer_use
request_checkout_with_item.note = "test_note"
request_checkout_with_item.save()
order = create_order(
- request_checkout_with_item,
- "tracking_code",
- discounts=None,
- taxes=None,
+ checkout=request_checkout_with_item,
+ order_data=prepare_order_data(
+ checkout=request_checkout_with_item,
+ tracking_code="tracking_code",
+ discounts=None,
+ taxes=None,
+ ),
user=customer_user,
)
assert order.customer_note == request_checkout_with_item.note
diff --git a/tests/test_order.py b/tests/test_order.py
index 0a5fbcbed3..d6b29bf02b 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -8,7 +8,7 @@ from prices import Money, TaxedMoney
from saleor.account import events as account_events
from saleor.account.models import User
-from saleor.checkout.utils import create_order
+from saleor.checkout.utils import create_order, prepare_order_data
from saleor.core.exceptions import InsufficientStock
from saleor.core.utils.taxes import (
DEFAULT_TAX_RATE_NAME,
@@ -459,10 +459,13 @@ def test_order_payment_flow(
request_checkout_with_item.save()
order = create_order(
- request_checkout_with_item,
- "tracking_code",
- discounts=None,
- taxes=None,
+ checkout=request_checkout_with_item,
+ order_data=prepare_order_data(
+ checkout=request_checkout_with_item,
+ tracking_code="tracking_code",
+ discounts=None,
+ taxes=None,
+ ),
user=customer_user,
)