Who this is for. Developers adding a discount code field to a checkout page and showing discounts in its order summary. After this page you can apply and remove codes, show automatic discounts, and give the shopper the right message for every kind of code.
Automatic discounts and codes
A discount is one of two kinds:
- Automatic: it has no code and applies whenever its rules match the order.
- Code-based: it applies once the shopper adds one of its codes.
Both kinds show in the checkout's appliedDiscounts and add up in its discountTotal, which is in the checkout's currency like every other amount on it (Its currency, and the language of its lines). The codes a cart carries are copied onto the checkout when it is created, so a code the shopper added on the cart page is already there.
Discounts are worked out for the checkout's site, from discounts that are active and inside their from and to dates, in position order. A discount or rule marked final stops any discount after it from applying. Three details decide whether a given code can work:
- Codes are stored in upper case, so a shopper can type one in any case.
- A code whose
maxUsesis 0 cannot be used at all. - A person group condition checks the groups of the signed-in member, allowing or forbidding them. A guest has no groups, so a members-only discount needs the shopper to sign in first (Guest checkout and the captcha).
Adding and removing a code
A code is added with POST /cdna-api/checkout/<id>/discount-code and removed with DELETE /cdna-api/checkout/<id>/discount-code/<code>. Only one code per discount can be active at a time, so the production store's discount component removes any code already on the checkout before it adds a new one, and if that removal does not go through, tells the shopper a code is already applied instead of adding a second.
While the checkout is attached to its cart, the codes on the checkout are copied back onto the cart, and the cart worked out again, whenever the checkout changes. The cart and the checkout therefore always agree on which codes are active, and a shopper who goes back to the cart sees the code they added at checkout. Once a payment has split the checkout from its cart (From cart to order), its codes are its own.
Telling the shopper whether the code helped
A code that exists and is within its use limit is added to the checkout ("Discount code added to checkout") even when this order does not meet its dates or conditions. It then takes nothing off. So the message the checkout gives is not the message to show: compare discountTotal before and after, and tell the shopper what actually happened.