Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 28 ยท Platform APIs and Data

Basket, Checkout and Order Flow

Follow a purchase through Salesforce Commerce Cloud: BasketMgr, shipments, line items, the calculate hook, SFRA checkout stages, OrderMgr.createOrder and placeOrder.

A basket is a promise; an order is a record. In Salesforce B2C Commerce these are two different objects with two different managers. The shopper builds a basket while browsing and checking out, and the platform recalculates it every time something changes. When the shopper presses "Place order", your code turns the basket into an order, takes payment, and moves the order through a small set of statuses. Most checkout bugs come from not knowing exactly where that handover happens.

This lesson walks through the basket structure, the calculate hook that produces totals, the SFRA checkout stages, and the OrderMgr calls that create, place and fail an order. The platform-neutral theory lives in The Order Lifecycle, The Checkout Flow and Authorize, Capture and Refund, so here you see how this platform names and orders the steps. The real code is read-only, because the site cannot run a Commerce Cloud instance. The two stand-ins are JavaScript models of basket calculation and of the order state machine, and each says what is real and what is simplified.

The basket and its parts

A basket is obtained for the current shopper through BasketMgr:

JavaScript
var BasketMgr = require('dw/order/BasketMgr');

var basket = BasketMgr.getCurrentBasket();        // null if the shopper has none
var basketOrNew = BasketMgr.getCurrentOrNewBasket();  // creates one when needed

Use getCurrentBasket() in routes that only read (the mini cart, checkout pages), and getCurrentOrNewBasket() when you are adding a first product. Creating baskets on every page view fills the system with empty baskets.

What a basket contains:

  • Product line items: one per product (and option set) with a quantity. A line belongs to a shipment.
  • Shipments: groups of items that are delivered together. Every basket has a default shipment; split deliveries add more. A shipment holds the shipping address and the chosen shipping method.
  • Shipping line items: the cost of each shipment's shipping.
  • Price adjustments: discounts applied by promotions or by hand, attached to product lines, shipments or the whole basket.
  • Payment instruments: how the shopper pays, such as a credit card or PayPal, each with an amount.
  • Addresses and contact data: the billing address and the customer's email.
JavaScript
var Transaction = require('dw/system/Transaction');

Transaction.wrap(function () {
    var pli = basket.createProductLineItem('tee-red-m', basket.defaultShipment);
    pli.setQuantityValue(2);
    basket.setCustomerEmail('[email protected]');
});

Every change to a basket is a write, so it happens in a transaction (The Script API and Common Classes). After each change, totals must be recalculated.

The basket exposes its totals through properties: merchandizeTotalPrice, adjustedMerchandizeTotalPrice (after product-level discounts), shippingTotalPrice, adjustedShippingTotalPrice, totalTax and totalGrossPrice (or totalNetPrice for net-price taxation). Note the spelling merchandize: it is the API's historic spelling, and typing merchandise gives you undefined.

The calculate hook

Totals are not computed by the basket by itself. Calling HookMgr.callHook('dw.order.calculate', 'calculate', basket) runs the project's calculation hook, which SFRA registers in its hooks.json and implements in cart/calculate.js. In SFRA you rarely call it directly; the helper basketCalculationHelpers.calculateTotals(basket) does it.

JavaScript
'use strict';

var HookMgr = require('dw/system/HookMgr');
var PromotionMgr = require('dw/campaign/PromotionMgr');
var ShippingMgr = require('dw/order/ShippingMgr');
var Status = require('dw/system/Status');

exports.calculate = function (basket) {
    // 1. Product prices from price books
    // 2. Shipping costs for each shipment
    ShippingMgr.applyShippingCost(basket);
    // 3. Promotions (product, order and shipping)
    PromotionMgr.applyDiscounts(basket);
    // 4. Taxes through their own hook
    HookMgr.callHook('dw.order.calculateTax', 'calculateTax', basket);
    // 5. Totals
    basket.updateTotals();
    return new Status(Status.OK);
};

The exact steps in a project's version differ, but the order has a reason: promotions need prices, shipping promotions need shipping costs, taxes apply to the discounted amounts, and totals come last. Your own change to this hook is a high-risk edit, so most projects extend it through a plugin cartridge, as described in Hooks and Extension Mechanisms. For how the price in step 1 is selected, see Catalog, Products and Price Books.

The first TryIt models the calculation with integer cents, in the same order. What is real: the stages, discounted amounts feeding the tax, and a free-shipping threshold being checked against the discounted merchandise. What is simplified: real baskets handle per-line tax rates, multiple shipments, price adjustment types, and rounding rules that are configured per site; the shipping and promotion rules here are invented for the demo.

JS A basket calculation in the right order (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the medium basket: merchandise is 54.98, so the order promotion applies and the discounted amount is 49.48. Free shipping at 60.00 is checked against the discounted amount, so the shopper still pays shipping. That kind of interaction is why the order of steps matters.

SFRA checkout stages

SFRA's checkout is a single page (Checkout-Begin) with stages that are shown one after another: shipping, payment and place order. Each stage submits to its own route, usually through AJAX, and the server revalidates everything. Typical routes include CheckoutShippingServices-SubmitShipping, CheckoutServices-SubmitPayment and CheckoutServices-PlaceOrder, and the confirmation page is Order-Confirm. Registered customers can start from saved addresses and cards; guests enter everything. The route structure and middleware were introduced in Controllers, Routes and Middleware.

The place-order route does the following, with the shape (not the exact code) of SFRA's version:

JavaScript
server.post('PlaceOrder', server.middleware.https, csrfProtection.validateAjaxRequest, function (req, res, next) {
    var currentBasket = BasketMgr.getCurrentBasket();
    if (!currentBasket) {
        res.json({ error: true, cartError: true, redirectUrl: URLUtils.url('Cart-Show').toString() });
        return next();
    }

    // 1. Revalidate: products still sellable, shipments and addresses complete
    // 2. Recalculate so the totals the shopper saw are the real ones
    // 3. Turn the basket into an order
    var order = COHelpers.createOrder(currentBasket);
    if (!order) { /* error response */ return next(); }

    // 4. Authorize payment for the order
    var handlePaymentResult = COHelpers.handlePayments(order, order.orderNo);
    if (handlePaymentResult.error) {
        Transaction.wrap(function () { OrderMgr.failOrder(order, true); });
        res.json({ error: true, errorMessage: Resource.msg('error.payment.not.valid', 'checkout', null) });
        return next();
    }

    // 5. Fraud check hook, then place the order
    var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);
    if (placeOrderResult.error) { /* error response */ return next(); }

    // 6. Confirmation email and redirect to Order-Confirm
    COHelpers.sendConfirmationEmail(order, req.locale.id);
    res.json({ error: false, orderID: order.orderNo, orderToken: order.orderToken, continueUrl: URLUtils.url('Order-Confirm').toString() });
    return next();
});

Three design points are worth copying into your own work:

  • The route revalidates and recalculates even though the checkout page did so earlier. Between the page load and the click, a product can go out of stock or a promotion can end.
  • The order is created before payment, and a payment failure calls OrderMgr.failOrder(order, true). The second argument reopens the basket, so the shopper keeps their items and can try another card.
  • The confirmation URL carries an order token (in recent SFRA versions) so that a guest can only view their own order, not any order number.

For the payment details (authorization, capture, 3-D Secure), see Payments Overview; for the integration side with a processor, Service Framework and Third-Party Integrations.

OrderMgr and order status

OrderMgr creates and changes orders. The key calls:

  • OrderMgr.createOrder(basket) copies the basket into an order with the status CREATED and assigns an order number. Created orders do not count as real orders yet and are not shown to merchants as new orders. After creation the basket can no longer be edited.
  • OrderMgr.placeOrder(order) moves the order to NEW (a real, active order). Payment has been handled by now, and merchants and export jobs see it.
  • OrderMgr.failOrder(order, reopenBasketIfPossible) ends a created order as FAILED, optionally giving the basket back.
  • OrderMgr.cancelOrder(order) sets CANCELLED, and undoCancelOrder reverses it.

Later statuses such as OPEN, COMPLETED and REPLACED describe fulfilment progress. Next to the main status, an order has separate fields: payment status (not paid, part paid, paid), shipping status (not shipped, part shipped, shipped), a confirmation status and an export status. These are changed by integrations and jobs, in transactions, with calls like order.setPaymentStatus(Order.PAYMENT_STATUS_PAID).

stateDiagram-v2
    [*] --> Basket
    Basket --> CREATED: OrderMgr.createOrder
    CREATED --> NEW: OrderMgr.placeOrder
    CREATED --> FAILED: OrderMgr.failOrder
    FAILED --> Basket: basket reopened
    NEW --> CANCELLED: OrderMgr.cancelOrder
    NEW --> COMPLETED: fulfilment finished

Created orders are temporary; only placed orders (NEW and later) are real. A failed order can give the basket back.

The second TryIt models the handover with a tiny order manager. The rule it enforces, that only a CREATED order can be placed or failed, is real; the status names are the platform's, and everything else is simplified (no payment instruments, no order numbers from a sequence).

JS createOrder, placeOrder and failOrder (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each attempt produced its own order number, and the failed order is kept for diagnosis; this is normal on the platform, and you will see failed orders in Business Manager. The double-click shows why state checks matter: a second request must not place or charge an order twice. The general technique for that is Idempotency.

Practical rules

  • Always recalculate after changing a basket, and again inside place-order before taking payment.
  • Never trust prices or totals sent by the browser. Read them from the basket.
  • Keep order creation, payment handling and placeOrder in a clear sequence with failure handling for each step. Use failOrder when anything before placement goes wrong.
  • Do not do heavy work in the place-order request, such as slow third-party calls without timeouts. Export and fulfilment belong in jobs and hooks.
  • Test the failure paths: declined card, out-of-stock after the basket was built, expired promotion, and a shopper double-clicking.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between BasketMgr.getCurrentBasket() and getCurrentOrNewBasket()?

    getCurrentBasket() only returns an existing basket (or null). getCurrentOrNewBasket() creates one when needed, so use it only when you are about to add something.
  2. 2. Which hook produces the totals of a basket?

    HookMgr.callHook('dw.order.calculate', 'calculate', basket) runs the calculation, which applies prices, shipping, promotions and taxes in a defined order and then updates the totals.
  3. 3. A payment is declined after OrderMgr.createOrder. What should the route do to keep the shopper's cart?

    failOrder ends the created order as FAILED, and passing true reopens the basket so the shopper can retry with another payment method.
  4. 4. Which statement about orders in the CREATED status is correct?

    CREATED orders exist only to hold the data during checkout. placeOrder moves them to NEW; failOrder moves them to FAILED.
  5. 5. Why does SFRA's PlaceOrder route revalidate and recalculate the basket?

    Time passes between loading the checkout page and the final click. The server must verify the current state before it creates an order and takes payment.

Summary

  • A basket (via BasketMgr) holds product lines, shipments, shipping lines, adjustments, payment instruments and addresses; changes need transactions and a recalculation.
  • Totals come from the dw.order.calculate hook, which runs prices, shipping, promotions, taxes and totals in a meaningful order.
  • SFRA checkout has shipping, payment and place-order stages, each revalidated on the server.
  • OrderMgr.createOrder makes a CREATED order, placeOrder makes it NEW, and failOrder(order, true) ends it as FAILED and reopens the basket.
  • Guard against double submissions and always test the failure paths.

Next: Customers, Sessions and Profiles