---
title: Free gifts
related:
  - https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/cart-item-discounts.md
  - https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/free-shipping.md
  - https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/coupon-codes.md
  - https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/customer-eligibility-customization.md
  - https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/checkout-process/order-creation.md
---

> **Documentation indexes**
> The indexes below list current page URLs with titles and descriptions. Links on this page point to the Markdown versions of the linked pages.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

> **License:** Advanced license required.
>
> Features described on this page require the Xperience by Kentico **Advanced** license tier.

Free gifts allow you to create custom promotion rules that offer customers products for free, based on the content of the shopping cart. Unlike discounts, a free gift doesn't reduce the price of anything the customer bought. The customer gets an extra product, and the order total stays the same. Free gifts are evaluated during [price calculation](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation.md).

Use free gifts to implement:

- Gifts with a purchase (e.g., "Buy a coffee machine, choose a free bag of coffee")
- Gifts for a minimum spend (e.g., "Spend $20 on merchandise, take a free coffee")
- Repeated gifts (e.g., "One free mug for every three bags of coffee")

![Promotion types in the order the price calculation evaluates them, with free gifts highlighted: catalog discounts reduce unit prices of products; cart item discounts reduce prices of units already in the cart; free gifts add claimed products for free, with no price change; order discounts reduce the order total; free shipping removes the shipping price.](https://docs.kentico.com/docsassets/documentation/free-gifts/free-gifts-promotion-flow.drawio.svg "Promotion types in calculation order")

For the other promotion types and how they combine, see [Promotions](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions.md#discount-applicability-and-priority). Every promotion type can optionally require a [coupon code](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/coupon-codes.md).

## How free gifts work

A free gift promotion never adds a product to the cart by itself. Instead, every gift goes through three stages:

1. **Offer** – The promotion rule evaluates the cart and returns one or more [promotion offers](#promotion-offer). Each offer lists the products the customer can choose from and how many units they can claim. The price calculation result contains the offers, so the storefront can show them in the shopping cart.
2. **Claim** – When the customer selects a gift, the storefront adds it to the claimed gifts of the next price calculation request.
3. **Grant** – The price calculation evaluates the promotion again and grants every claimed gift that a current offer of the same promotion covers. The granted gifts are in a separate collection of the calculation result.

A claimed gift that the current offers don't cover isn't granted. For example, when the customer removes the products that earned the gift from the cart, the rule returns no offer and the claim stops having any effect. To let the customer refuse a gift they claimed before, remove the claim from the request.

> **Info:** **Gifts are separate from the purchased items**
>
> The customer sees a gift in the cart together with the purchased items, but the gift has no price, discount, or tax, and no total includes it. The calculation request and result keep gifts in their own `FreeGiftItems` collections, separate from the `Items` collections of the purchased items. Steps that price the cart, such as taxes and totals, don't process gifts.

## General promotion capabilities

Free gifts use the general promotion configuration and evaluation framework, so you can use the following capabilities:

- [Coupon codes](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/coupon-codes.md) – Optionally require a discount code for redemption.
- [Customer eligibility](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/customer-eligibility-customization.md) – Restrict the promotion to all visitors, registered members only, or a custom eligibility rule.
- [Activation scheduling](https://docs.kentico.com/documentation/business-users/manage-commerce-stores.md#create-a-promotion) – Set start and end dates for time-limited offers.

Store managers create and manage free gift promotions in the **Cart item discounts** section of the **Promotions** application, together with cart item discounts. The promotion rule that they select decides the type of the promotion.

## Free gift promotion rule overview

A **promotion rule** defines the logic that decides which gifts the cart earns. You implement promotion rules as classes that inherit from `FreeGiftPromotionRule` or `FreeGiftPromotionRuleBase`.

The rule receives the calculation data for the whole cart. It runs after the line subtotals are calculated, so the cart item prices it reads already include catalog and cart item discounts. Free gift rules run only in the shopping cart and checkout [calculation modes](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation.md#calculation-modes).

### Promotion offer

A **promotion offer** represents gifts that a rule offers to the customer. The rule returns a list of `FreeGiftPromotionOffer` objects. Each offer contains:

- `ClaimableProducts` – The products the customer can claim. For a product with variants, list its variants.
- `ClaimableQuantity` – The number of units the customer can claim from all the `ClaimableProducts` together.
- `PromotionTriggerItems` – The cart items that earned the offer, each with a `ProductIdentifier` and the `Quantity` of units that count toward the reward. The system stores the trigger items with the order and shows them in the administration (see [Create orders with free gifts](#create-orders-with-free-gifts)). When no particular cart items earn the offer, such as for a minimum purchase amount, provide an empty list.

When the cart doesn't qualify, return an empty list.

A list is necessary because one promotion can earn a reward more than once. Each offer has its own `ClaimableQuantity`, and the customer can claim from all of them. To link every gift on the order to the cart items that earned it, return one offer for every reward, each with the trigger items of that reward.

### Granting claimed gifts

The price calculation grants the claimed gifts in the following way:

- A claimed gift is granted only when an offer of the same promotion lists the claimed product.
- The claimed units are taken from the offers of the promotion in the order the rule returned them, up to the `ClaimableQuantity` of each offer. An offer that has no units left doesn't grant more.
- A claimed gift can contain more units than one offer covers, so several offers grant it together. The result then contains a separate gift item for each of those offers, and each gift item references its offer and that offer's trigger items. For example, a promotion offers one free mug for every three bags of coffee, and the cart holds six bags. The rule returns two offers, each with one claimable mug and three bags as trigger items. When the customer claims two mugs, the result contains two gift items with one mug each, and each gift item references a different offer.
- A gift whose product data the [product data retriever](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation/implementation.md#implement-product-data-retrieval) doesn't return is removed from the result.

The calculation doesn't limit the number of gifts a customer claims from one promotion beyond the quantity of its offers. If your store offers one gift per promotion, enforce the limit in the storefront, for example, by replacing the previous claim of the promotion when the customer claims another gift.

### Promotion rule properties

Promotion rules can define configurable properties that store managers set when creating promotions in the administration interface. Properties are defined in a separate class implementing `IPromotionRuleProperties` and are decorated with [editing components](https://docs.kentico.com/documentation/developers-and-admins/customization/extend-the-administration-interface/ui-form-components/editing-components.md) to generate the UI. For details, see [Define promotion rule properties](#define-promotion-rule-properties).

## Create free gift promotion rules

Implementing a free gift promotion rule involves creating two components:

1. **Properties class** – Defines configurable settings that store managers can adjust in the administration interface (e.g., the minimum purchase requirement, the gift products). The properties class inherits from `FreeGiftPromotionRuleProperties` or implements `IPromotionRuleProperties`.
2. **Logic class** – Contains the rule's evaluation logic. It decides whether the cart earns gifts and returns the promotion offers. The logic class inherits from `FreeGiftPromotionRule` or `FreeGiftPromotionRuleBase`.

These two components work together: the properties class stores the configuration, and the logic class uses those configured values to evaluate the cart during price calculation.

![Free gift promotion rule class hierarchy. Properties component: FreeGiftPromotionRuleProperties implements IPromotionRuleProperties and defines MinimumRequirementType, MinimumRequirementValue, Frequency, and GiftQuantityPerReward. Your custom properties class either inherits FreeGiftPromotionRuleProperties (the standard fields plus your own fields) or implements IPromotionRuleProperties directly (all fields defined by you). Logic component: FreeGiftPromotionRuleBase with the type parameters TPromotionRuleProperties, TPriceCalculationRequest, and TPriceCalculationResult defines IsApplicable, GetPromotionOffers, and GetDiscountValueLabel, and returns FreeGiftPromotionOffer objects with ClaimableProducts, ClaimableQuantity, and PromotionTriggerItems. FreeGiftPromotionRule inherits FreeGiftPromotionRuleBase and adds GetRewardCount, GetItemsMeetingMinimumRequirement, and GetDiscountValueLabel. Your custom rule either inherits FreeGiftPromotionRule (with built-in helpers), which uses your properties class with the standard fields, or inherits FreeGiftPromotionRuleBase (fully custom logic).](https://docs.kentico.com/docsassets/documentation/free-gifts/free-gift-promotion-rule-hierarchy.drawio.svg "Free gift promotion rule class hierarchy showing the relationship between properties and logic components")

> **Tip:** **Sample implementation**
>
> See **DancingGoatChosenFreeGiftPromotionRule.cs** and **DancingGoatAutomaticFreeGiftPromotionRule.cs** in the Dancing Goat [project template](https://docs.kentico.com/documentation/developers-and-admins/installation.md#available-project-templates). The first rule lets the customer choose the gift from several products. The second rule offers one gift product, and the Dancing Goat shopping cart claims it on the customer's behalf. Both rules count the products in a scope of any product, categories, products, or tags toward the minimum purchase requirement.

### Define promotion rule properties

The system provides `FreeGiftPromotionRuleProperties` as a base class with common properties already defined and configurable via the administration interface:

- **MinimumRequirementType** – Radio group to select a minimum quantity of items, a minimum purchase amount, or a minimum single item price
- **MinimumRequirementValue** – Decimal input for the minimum value
- **Frequency** – Radio group to select whether the promotion offers a gift once per cart or for every reached threshold
- **GiftQuantityPerReward** – The number of gift units every reward gives. The default is 1. The property has no editing component, so store managers don't see it. To let them set the quantity, override the property and add an editing component.

The base class groups its fields into two categories of the promotion form, **Purchase requirements** and **Reward**. Properties of a derived class with an `Order` between 1 and 99 appear at the end of the **Purchase requirements** category. Properties with an `Order` above 100 appear in the **Reward** category.

You can inherit from this base class to include these standard fields and add your own custom properties. The following example adds a selector for the gift products:

```csharp title="Free gift promotion rule properties"
using System.Collections.Generic;

using CMS.ContentEngine;

using Kentico.Xperience.Admin.Base.FormAnnotations;
using Kentico.Xperience.Admin.DigitalCommerce;

/// <summary>
/// Properties of a free gift promotion that offers a choice of gift products.
/// </summary>
public class FreeGiftWithPurchaseProperties : FreeGiftPromotionRuleProperties
{
    // MinimumRequirementType, MinimumRequirementValue, Frequency and
    // GiftQuantityPerReward are inherited from FreeGiftPromotionRuleProperties

    /// <summary>
    /// Products the customer chooses the gift from.
    /// </summary>
    // An order above 100 places the field in the "Reward" category
    [ContentItemSelectorComponent(
        ProductSKU.CONTENT_TYPE_NAME,
        Label = "Gift products",
        MinimumItems = 1,
        AllowContentItemCreation = false,
        Order = 110)]
    [RequiredValidationRule]
    public IEnumerable<ContentItemReference> GiftProducts { get; set; } = [];
}
```

Alternatively, you can directly implement `IPromotionRuleProperties` if you need full control over all configuration properties used by the rule.

### Implement the promotion rule

The framework provides two base classes for free gift promotion rules:

- **FreeGiftPromotionRule** – Use when your properties class inherits from `FreeGiftPromotionRuleProperties`. Provides built-in helper methods that work with the base properties.
- **FreeGiftPromotionRuleBase** – Use when you need fully custom properties implementing `IPromotionRuleProperties` directly. You implement all the requirement logic yourself.

Both base classes use the same generic type parameters:

1. `TPromotionRuleProperties` – The rule's [properties class](#define-promotion-rule-properties). Must inherit from `FreeGiftPromotionRuleProperties` for `FreeGiftPromotionRule`, or implement `IPromotionRuleProperties` for `FreeGiftPromotionRuleBase`.
2. `TPriceCalculationRequest` – The price calculation request type.
3. `TPriceCalculationResult` – The price calculation result type.

Implement the following members:

- `GetPromotionOffers(IPriceCalculationData<TPriceCalculationRequest, TPriceCalculationResult> calculationData, CancellationToken cancellationToken)` – Required. Returns the list of [promotion offers](#promotion-offer) for the whole cart.
- `GetDiscountValueLabel()` – Optional. Returns a short label for the administration listing. `FreeGiftPromotionRuleBase` returns `null` by default.

`FreeGiftPromotionRule` provides the following built-in methods, which evaluate the standard properties of `FreeGiftPromotionRuleProperties`:

- `GetRewardCount(items)` – Returns how many rewards the given cart items earn under `MinimumRequirementType`, `MinimumRequirementValue`, and `Frequency`. The method returns 0 when the items don't reach the requirement, and 1 for a promotion offered once per cart. For a promotion offered for every reached threshold, it returns the number of times the items reach the requirement value. For a minimum single item price, every unit that reaches the value earns one reward. A minimum quantity counts units, a minimum purchase amount counts the line subtotals after catalog and cart item discounts, and a minimum single item price counts the units whose price after those discounts reaches the value.
- `GetItemsMeetingMinimumRequirement(items)` – Returns the cart items that count toward the requirement: for a minimum single item price, the items with at least one unit whose price after catalog and cart item discounts reaches the value, and for the other requirement types, all the given items. A cart item discount can cover only some units of an item, so not every unit of a returned item has to qualify. To get the number of qualifying units of an item, for example, as the quantity of a trigger item, call `FreeGiftPromotionRuleUtils.GetQuantityMeetingMinimumRequirement(Properties, item)`. Use these items as the trigger items of the offer.
- `GetDiscountValueLabel()` – Already overridden to return a localized "Free gift" label.

The following sample offers a choice of the selected gift products once the cart reaches the minimum purchase requirement. It returns one offer for all the rewards the cart earns:

```csharp title="Free gift promotion rule"
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using CMS.Commerce;

using Kentico.Content.Web.Mvc;
using Kentico.Xperience.Admin.DigitalCommerce;

// ...

public class FreeGiftWithPurchaseRule(IContentRetriever contentRetriever)
    : FreeGiftPromotionRule<FreeGiftWithPurchaseProperties,
        PriceCalculationRequest, PriceCalculationResult>
{
    public const string IDENTIFIER = "Acme.FreeGiftWithPurchase";


    public override async Task<IReadOnlyList<FreeGiftPromotionOffer>> GetPromotionOffers(
        IPriceCalculationData<PriceCalculationRequest, PriceCalculationResult> calculationData,
        CancellationToken cancellationToken)
    {
        IEnumerable<IPriceCalculationResultItem<ProductIdentifier, ProductData>> cartItems =
            calculationData.Result.Items;

        // Counts how many times the cart reached the minimum purchase requirement
        decimal rewardCount = GetRewardCount(cartItems);

        // The cart doesn't qualify
        if (rewardCount == 0)
        {
            return [];
        }

        // Gets the content item ID of every selected gift product
        IEnumerable<ProductSKU> giftProducts =
            await contentRetriever.RetrieveContentByGuids<ProductSKU>(
                Properties.GiftProducts.Select(product => product.Identifier),
                new RetrieveContentParameters
                {
                    LanguageName = calculationData.Request.LanguageName
                },
                cancellationToken);

        List<ProductIdentifier> claimableProducts = giftProducts
            .Select(product => new ProductIdentifier
            {
                Identifier = product.SystemFields.ContentItemID
            })
            .ToList();

        // None of the gift products exists
        if (claimableProducts.Count == 0)
        {
            return [];
        }

        // A purchase amount earns the gift as a whole, so no cart item triggers it
        List<PromotionTriggerItem> triggerItems =
            Properties.MinimumRequirementType == FreeGiftMinimumRequirementType.Price
                ? []
                : GetItemsMeetingMinimumRequirement(cartItems)
                    .Select(item => new PromotionTriggerItem
                    {
                        ProductIdentifier = item.ProductIdentifier,
                        // For a minimum single item price, only some units of an item can reach the value
                        Quantity = FreeGiftPromotionRuleUtils.GetQuantityMeetingMinimumRequirement(Properties, item)
                    })
                    .ToList();

        return
        [
            new FreeGiftPromotionOffer
            {
                ClaimableProducts = claimableProducts,
                ClaimableQuantity = rewardCount * Properties.GiftQuantityPerReward,
                PromotionTriggerItems = triggerItems
            }
        ];
    }
}
```

The sample identifies products by the ID of their content item, the same way as the sample [product data retriever](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation/implementation.md#implement-product-data-retrieval). Use the identifiers of your own product data retriever, so that the calculation can load the product data of the gifts.

### Register the promotion rule

Register the rule using the `RegisterPromotionRuleAttribute` assembly attribute. Set the attribute's parameters to a unique string identifier of the rule, `PromotionType.FreeGift`, and a display name shown in the administration interface.

```csharp title="Register a free gift promotion rule"
using CMS.Commerce;

using Kentico.Content.Web.Mvc;
using Kentico.Xperience.Admin.DigitalCommerce;

// ...

[assembly: RegisterPromotionRule<FreeGiftWithPurchaseRule>(
    identifier: FreeGiftWithPurchaseRule.IDENTIFIER,
    promotionType: PromotionType.FreeGift,
    name: "Free gift with purchase")]
```

The registered type must inherit from `FreeGiftPromotionRuleBase`. Registering any other type for `PromotionType.FreeGift` throws an `ArgumentException`.

Without registration, the rule doesn't appear in the administration interface. Until at least one rule is registered, the **Cart item discounts** section of the **Promotions** application asks you to implement one.

### Filter promotion applicability

Override the `IsApplicable` method to add high-level conditions that determine whether the promotion should be evaluated at all. This method runs **once per promotion** before `GetPromotionOffers`.

The evaluation pipeline works as follows:

1. **Get active promotions** – The system retrieves all active free gift promotions for the calculation date, starting with the most recently created one.
2. **Check requirements** – The system validates the coupon code and customer eligibility. Promotions that don't pass are skipped.
3. **Check IsApplicable** – For each remaining promotion, `IsApplicable` is called once. If it returns `false`, the promotion is skipped entirely.
4. **Get offers** – For promotions that pass, `GetPromotionOffers` is called once for the whole cart. The system records every returned offer.
5. **Grant gifts** – The system grants the claimed gifts that the recorded offers cover (see [Granting claimed gifts](#granting-claimed-gifts)).

If a promotion's rule isn't registered in the system, the calculation throws an `InvalidOperationException`.

For an example of an `IsApplicable` override that restricts a promotion to registered members, see [Filter promotion applicability](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/promotions/cart-item-discounts.md#filter-promotion-applicability).

## Claim gifts in the shopping cart

The storefront decides when a gift is claimed. A typical shopping cart shows the offers, lets the customer claim a gift, and shows the claimed gift with a way to refuse it.

The calculation result stores the recorded offers in the `PromotionData.FreeGiftPromotionOffers` collection. Each offer is wrapped in `IPriceCalculationFreeGiftPromotionOffer<FreeGiftPromotionOffer>`, which exposes the promotion ID, the coupon code that activated the promotion (if any), and the offer itself. The collection also contains offers the customer hasn't claimed anything from.

```csharp title="Read free gift offers"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using CMS.Commerce;

// ...

public class FreeGiftCalculationExample(
    IPriceCalculationService<PriceCalculationRequest, PriceCalculationResult> priceCalculationService)
{
    // ...

public async Task ReadFreeGiftOffers(
    PriceCalculationRequest request,
    CancellationToken cancellationToken)
{
    PriceCalculationResult result =
        await priceCalculationService.Calculate(request, cancellationToken);

    foreach (IPriceCalculationFreeGiftPromotionOffer<FreeGiftPromotionOffer> offer
        in result.PromotionData.FreeGiftPromotionOffers)
    {
        // The promotion the customer claims the gift from
        int promotionId = offer.PromotionID;

        // The products the customer chooses from, and how many units they can claim
        IReadOnlyList<ProductIdentifier> giftProducts =
            offer.PromotionOffer.ClaimableProducts;
        decimal claimableQuantity = offer.PromotionOffer.ClaimableQuantity;
    }
}
```

To claim a gift, add a `PriceCalculationRequestFreeGiftItem` to the `FreeGiftItems` collection of the request. The item contains the gift's `ProductIdentifier`, the `Quantity` of units, and the `PromotionID` of the promotion that offers the gift. Store the claims with the shopping cart, so that every calculation of the cart includes them.

```csharp title="Claim a free gift"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using CMS.Commerce;

// ...

public async Task<PriceCalculationResult> ClaimFreeGift(
    ICollection<PriceCalculationRequestItem> cartItems,
    ProductIdentifier giftProduct,
    int promotionId,
    CancellationToken cancellationToken)
{
    var request = new PriceCalculationRequest
    {
        Items = cartItems,
        // Claims one unit of the gift product from the promotion's offer
        FreeGiftItems =
        [
            new PriceCalculationRequestFreeGiftItem
            {
                ProductIdentifier = giftProduct,
                Quantity = 1,
                PromotionID = promotionId
            }
        ],
        LanguageName = "en",
        Mode = PriceCalculationMode.ShoppingCart
    };

    return await priceCalculationService.Calculate(request, cancellationToken);
}
```

The granted gifts are in the `FreeGiftItems` collection of the result. Each gift item contains the `ProductIdentifier`, the `ProductData`, and the `Quantity` of the gift, and references the offer it was granted from in `PromotionData.FreeGiftPromotionOffer`.

```csharp title="Read granted free gifts"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using CMS.Commerce;

// ...

public void ReadGrantedGifts(PriceCalculationResult result)
{
    foreach (PriceCalculationResultFreeGiftItem gift in result.FreeGiftItems)
    {
        // Gift items have no price, discount or tax
        string productName = gift.ProductData.ProductName;
        decimal quantity = gift.Quantity;

        // The offer the gift was granted from, with the cart items that earned it
        FreeGiftPromotionOffer offer =
            gift.PromotionData.FreeGiftPromotionOffer.PromotionOffer;
        IReadOnlyList<PromotionTriggerItem> triggerItems =
            offer.PromotionTriggerItems;
    }
}
```

Show the customer the gifts from the last calculation result, and remove claims that the result didn't grant. Otherwise, an old claim takes effect again when the cart qualifies for the offer later.

> **Tip:** **Sample implementation**
>
> The Dancing Goat [project template](https://docs.kentico.com/documentation/developers-and-admins/installation.md#available-project-templates) stores the claims with the shopping cart, shows the offers and the claimed gifts in the cart, and marks products that count toward a free gift promotion in the product listing. See **ShoppingCartFreeGiftService.cs** for storing and synchronizing the claims, including claiming the gifts of automatic promotions, **FreeGiftViewModelProvider.cs** for building the offers and claimed gifts shown in the cart, and **FreeGiftEligibilityService.cs** for the free gift badge in the product listing.

### Include gifts in shipping

The default shipping step doesn't take gifts into account. The free gift steps run before the shipping step, so a [custom shipping step](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation/customization.md#modify-existing-calculation-steps) can read the `FreeGiftItems` collection of the result. For example, when the cart contains only digital products and the gift is a physical product, the step can charge shipping for the gift.

## Create orders with free gifts

To add the claimed gifts to an order, set the `FreeGiftItems` collection of the order data to `OrderFreeGiftItem` objects with the same `ProductIdentifier`, `Quantity`, and `PromotionID` as the claims in the shopping cart. The [order creation service](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/checkout-process/order-creation.md) passes the gifts to the price calculation of the order.

If the calculation doesn't grant every claimed gift in the claimed quantity, for example, because the promotion ended after the customer claimed the gift, `CreateOrder` throws an `OrderFreeGiftsNotGrantedException` and doesn't create the order. The `NotGrantedFreeGifts` property of the exception lists the promotion ID and the product of every gift that wasn't granted.

```csharp title="Create an order with free gifts"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using CMS.Commerce;

// ...

public class FreeGiftOrderCreationExample(
    IOrderCreationService<OrderData, PriceCalculationRequest,
        PriceCalculationResult, AddressDto> orderCreationService)
{
    public async Task<int?> CreateOrder(
        OrderData orderData,
        ProductIdentifier giftProduct,
        int promotionId,
        CancellationToken cancellationToken)
    {
        // Passes the gifts the customer claimed in the shopping cart
        orderData.FreeGiftItems =
        [
            new OrderFreeGiftItem
            {
                ProductIdentifier = giftProduct,
                Quantity = 1,
                PromotionID = promotionId
            }
        ];

        try
        {
            return await orderCreationService.CreateOrder(orderData, cancellationToken);
        }
        catch (OrderFreeGiftsNotGrantedException ex)
        {
            // The promotion no longer grants some of the claimed gifts, for example,
            // because it ended. The order isn't created.
            IReadOnlyCollection<NotGrantedFreeGift> notGrantedGifts = ex.NotGrantedFreeGifts;

            // Removes the gifts from the cart and asks the customer to check it again
            return null;
        }
    }
}
```

The order creation service stores every granted gift in the following way:

- **Order item** – The gift is an order item with a unit price, total price, and tax of 0. Gifts of one promotion with the same product and the same trigger products share one order item.
- **Order promotion** – An `OrderPromotionInfo` record of the `FreeGift` promotion type, linked to the gift's order item, with a discount amount of 0.
- **Trigger items** – For every product among the trigger items of the offers the gift order item was granted from, an `OrderPromotionTriggerItemInfo` record links the promotion record to the order item of that product, with the triggering quantities added together. An offer without trigger items, such as an offer for a minimum purchase amount, stores no trigger item records.

To add custom data to the order items of gifts, implement `IOrderFreeGiftItemInfoMapper<TOrderData, TPriceCalculationResult>`. Its `PopulateInfo` method receives the order item, the order data, the calculation result, and the gift items of the calculation result that the order item stores. The `IOrderItemInfoMapper` isn't used for gifts. For more information about mappers, see [Customize order creation](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/checkout-process/customize-order-creation.md).

In the **Orders** application, the order detail lists free gift promotions without an amount. The detail of a gift's order item lists the items that earned the gift, and the detail of a bought item lists the gifts it earned.

## Extend free gift data objects

To add data to gifts, extend the free gift types in the same way as other [price calculation data objects](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation/customization.md#extend-data-transfer-objects):

- **Claimed gifts** – Extend `PriceCalculationRequestFreeGiftItem`, and use it through `PriceCalculationRequestBase<TPriceCalculationRequestItem, TPriceCalculationRequestFreeGiftItem, TAddressDto>`.
- **Granted gifts** – Extend `PriceCalculationResultFreeGiftItem`, and use it through `PriceCalculationResultBase<TPriceCalculationResultItem, TPriceCalculationResultFreeGiftItem>`.
- **Gifts in order data** – Extend `OrderFreeGiftItem`, and use it through `OrderDataBase<TOrderItem, TOrderFreeGiftItem, TAddressDto>`.

To use your own product identifier or product data type, inherit from the generic base classes (see [Extend data transfer objects](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/price-calculation/customization.md#extend-data-transfer-objects) and [Extend order data objects](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/checkout-process/customize-order-creation.md#extend-order-data-objects)). Custom fields of gifts in order data reach the price calculation only through a [price calculation request mapper](https://docs.kentico.com/documentation/developers-and-admins/digital-commerce-setup/checkout-process/customize-order-creation.md#price-calculation-customization).
