How to add a discount row to an order
This page describes how to add a discount row by code, without setting up a discount in the UI.
When you add a discount row, it will be applied as an extra line item in your order, categorized as a discount. This means that it will appear alongside the other items in your cart. However, there are a few important points to note:
-
Application of the discount: When you apply a discount row, it will be factored into the total cost of your order. This can help reduce the overall price you pay.
-
Persistence of the discount: The added discount row will remain in your cart unless one of the following conditions is met:
- If you clear your cart (i.e., remove all items), the discount will also be removed.
- If you delete the discount row from your order, it will no longer be applied.
-
Coexistence with other cart items: As long as the discount remains in your cart, it will coexist with the other products you’ve added. So, whether you’re purchasing clothing, electronics, or any other items, the discount will be there, contributing to your overall savings.
Create the discount
Let's say we have a new action that allows a user to create a custom discount in the checkout process.
public async Task<IActionResult> CreateDiscount(CheckoutViewModel model)
{
var cartContext = await HttpContext.GetCartContextAsync();
AddOrUpdateDiscountArgs args = new AddOrUpdateDiscountArgs()
{
Description = "test",
DiscountId = "discountId",
ConstantQuantity = true,
DiscountAmount = 200
};
await cartContext.AddOrUpdateDiscountAsync(args);
await cartContext.CalculatePaymentsAsync();
if (model.PaymentWidget != null)
{
model.PaymentWidget = _paymentOptionViewModelBuilder.BuildWidget(cartContext, model.SelectedPaymentMethod?.Id);
}
return Ok(model);
}
The discount will give the user a 200 dicount on the total cart value.
Remove the discount
Once custom discounts are applied, they can be removed by adjusting the quantity to zero. Continuing the above example, lets modify the quantity but still keep the DiscountId value.
'
...
AddOrUpdateDiscountArgs args = new AddOrUpdateDiscountArgs()
{
Description = "test",
DiscountId = "discountId",
ConstantQuantity = true,
Quantity = 0
};
await cartContext.AddOrUpdateDiscountAsync(args);
await cartContext.CalculatePaymentsAsync();
...