For the complete documentation index, see llms.txt. This page is also available as Markdown.

Cart Tutorial

The Cart Service stores the products a customer intends to buy and calculates prices, shipping estimates, fees, tax, and discounts on that cart.

This tutorial shows how to create and update carts, add items and custom attributes, merge carts, and work with those cart-level calculations.

How to create a new cart

1

To create a new cart, send a request to the Creating a new cart endpoint.

curl -i -X POST 
  'https://api.emporix.io/cart/{tenant}/carts' 
  -H 'Authorization: Bearer {{OAUTH2_ACCESS_TOKEN}}' 
  -H 'Content-Type: application/json' 
  -H 'saas-token: string' 
  -H 'session-id: string' 
  -d '{
    "siteCode": "main",
    "currency": "EUR",
    "type": "shopping",
    "channel": {
      "name": "storefront",
      "source": "https://your-storefront.com/"
    },
    "sessionValidated": true
  }'
API Reference

How to add an item and retrieve the calculated cart in one request

Use Executing a chain of cart commands to add an item and retrieve the calculated cart in one HTTP request. The existing two-call sequence of Adding a product to cart then Retrieving cart details by ID still works. The cart id is the path parameter.

One /execute request uses one session-id and one legal-entity-id. Commands cannot override those headers. To act as a different session or legal entity, send another request. The default versioning=skip value ignores options.resourceVersion.

Prerequisites

  • An existing cart ID (cartId)

  • A customer access token, or a service token with cart.cart_manage

  • cart.cart_manage_external_prices – required when a command includes an external price, product, fee, or discount

  • session-id – required for an anonymous cart

1

Send AddCartItem and GetCart in one request

Send AddCartItem, then send GetCart with expandCalculation set to true. The 207 results array contains the created item and the calculated cart, so you do not need a follow-up GET unless you want a later refresh.

curl -i -X POST \
  'https://api.emporix.io/cart/{tenant}/carts/{cartId}/execute?onError=fail' \
  -H 'Authorization: Bearer {{CUSTOMER_ACCESS_TOKEN}}' \
  -H 'Content-Type: application/json' \
  -H 'session-id: 4f8a2c1e9b7d6a0c3e5f8b12' \
  -d '{
    "commands": [
      {
        "type": "AddCartItem",
        "data": {
          "itemYrn": "urn:yaas:saasag:caasproduct:product:yourTenant;mobile-phone-s24-gross",
          "quantity": 2,
          "price": {
            "priceId": "679ca63dbcdefe5b380c98bc",
            "originalAmount": 350,
            "effectiveAmount": 350,
            "currency": "EUR"
          }
        }
      },
      {
        "type": "GetCart",
        "options": {
          "expandCalculation": true
        }
      }
    ]
  }'
2

Read the 207 results

The HTTP status is 207 Multi-Status when the chain is accepted. results is ordered. results[0].data is the same JSON as POST .../items (itemId, yrn). With default versioning=skip, that result has no hybris-resource-version header. results[1].data is the same JSON as GET .../carts/{cartId} including item calculatedPrice.

{
  "results": [
    {
      "index": 0,
      "type": "AddCartItem",
      "code": 201,
      "status": "Created",
      "data": {
        "itemId": "3",
        "yrn": "urn:yaas:saasag:caascart:item:yourTenant;6a86b20c2f5961330a8b3eb6;3"
      }
    },
    {
      "index": 1,
      "type": "GetCart",
      "code": 200,
      "status": "OK",
      "data": {
        "id": "6a86b20c2f5961330a8b3eb6",
        "items": [
          {
            "id": "3",
            "quantity": 2,
            "calculatedPrice": {
              "price": {
                "netValue": 588.235,
                "grossValue": 700,
                "taxValue": 111.765,
                "taxCode": "STANDARD",
                "taxRate": 19,
                "calculated": "INTERNAL"
              },
              "finalPrice": {
                "netValue": 588.235,
                "grossValue": 700,
                "taxValue": 111.765,
                "taxCode": "STANDARD",
                "taxRate": 19,
                "calculated": "INTERNAL"
              }
            }
          }
        ],
        "calculatedPrice": {
          "price": {
            "netValue": 588.235,
            "grossValue": 700,
            "taxValue": 111.765
          },
          "finalPrice": {
            "netValue": 588.235,
            "grossValue": 700,
            "taxValue": 111.765
          }
        }
      }
    }
  ]
}

For request-level validation rules, see Whole-request validation errors. onError=fail treats command code 207 as success. UpdateCartItemsBatch always returns 207, even when every entry failed, so inspect data[].status.

On a different chain (AddCartItem then a missing UpdateCartItem), onError=fail omits later commands from results after the first non-2xx command. Earlier successful mutations stay committed:

Command types

Each command has a type, optional data (the REST request body), and options. Option fields are the remaining path and query equivalents of the REST operation. Commands do not send cartId, session, or legal-entity fields.

type

data

options

REST equivalent

Success code / data

AddCartItem

Item body

optional resourceVersion. Does not take siteCode; the cart already stores it.

POST /cart/{tenant}/carts/{cartId}/items

201 {itemId, yrn}

UpdateCartItem

Item update body

itemId, partial, optional resourceVersion

PUT /cart/{tenant}/carts/{cartId}/items/{itemId}

204, no data

DeleteCartItem

none

itemId

DELETE /cart/{tenant}/carts/{cartId}/items/{itemId}

204

DeleteCartItems

none

none

DELETE /cart/{tenant}/carts/{cartId}/items

204

GetCart

none

expandCalculation (default true), zipCode, countryCode

GET /cart/{tenant}/carts/{cartId}

200 full cart

AddCartItemsBatch

List of item bodies

none

POST /cart/{tenant}/carts/{cartId}/itemsBatch

Same mixed status as REST; data is the batch entry list

UpdateCartItemsBatch

List of item updates (max 50)

partial

PUT /cart/{tenant}/carts/{cartId}/itemsBatch

Command code 207; data is the entry list

UpdateCart

Cart update body

optional resourceVersion

PUT /cart/{tenant}/carts/{cartId}

204, no data

ApplyCartDiscount

Discount body

optional resourceVersion

POST /cart/{tenant}/carts/{cartId}/discounts

201 applied discount

GetCartDiscounts

none

none

GET /cart/{tenant}/carts/{cartId}/discounts

200 list of discounts

DeleteCartDiscounts

none

optional codes

DELETE /cart/{tenant}/carts/{cartId}/discounts

204

DeleteCartDiscount

none

discountIndex

DELETE /cart/{tenant}/carts/{cartId}/discounts/{discountIndex}

204

RefreshCart

none

none

PUT /cart/{tenant}/carts/{cartId}/refresh

204

ValidateCart

none

none

GET /cart/{tenant}/carts/{cartId}/validate

200 cart validation result

Creating or deleting carts, merging carts, changing the site or currency, searching, and retrieving cart items are not supported command operations in this release.

The chain accepts at most 10 commands. A commands array of 1 through 10 items is valid. 11 or more commands return 400 and no command runs. An empty commands array also returns 400. This cap is independent of the UpdateCartItemsBatch payload limit of 50.

Error handling

  • fail (default) – stops after the first non-2xx command. results contains only the commands that ran, including the failed one. Earlier successful mutations stay committed. A command code of 207 counts as success for onError. UpdateCartItemsBatch always returns 207, even when every entry failed, so fail continues. Inspect data[].status. AddCartItemsBatch uses a mixed global status (400 or 500) so fail does stop.

  • resume – runs every command. Later commands still see earlier successful mutations.

When the chain is accepted, the HTTP status is always 207 Multi-Status, including all-2xx chains and including a command whose code is 409. results is ordered. Each data field is the same JSON the equivalent endpoint would return. Commands that return 204 omit data. Failures put the existing error shape (code, status, message) in data. A conflict stays inside that 207 body as command code 409. The execute call itself does not return HTTP 409.

When a participating write applied If-Match, headers contains hybris-resource-version set to the version after the write (the version that was sent, plus 1). versioning=skip does not send If-Match, so that header is absent. AddCartItemsBatch sets each data[].headers.location the same way as REST POST .../itemsBatch. UpdateCartItemsBatch can use command code 207; that value is an entry in results, and the outer execute response is still one 207.

session-id and legal-entity-id are request headers shared by every command. Commands cannot override them. One /execute call is one shopper context. To act as a different session or legal entity, send another request. A B2B legal-entity switch remains a token refresh, not a per-command header.

Authorization is checked per command, the same as the equivalent REST calls, not as a preflight for the whole chain. A storefront token without cart.cart_manage can run commands only on a cart it owns. A service token with cart.cart_manage can touch any cart in the tenant, the same as two separate REST calls. cart.cart_manage_external_prices is required when a command payload includes an external price, product, fee, or discount.

Versioning

/execute reuses the existing If-Match mechanism on REST writes. On execute, the version is options.resourceVersion plus a request-level versioning query parameter. A single execute-level If-Match would make the second write on the same cart fail the version check, because the client submits the whole command array at once and cannot see command 1’s result before composing command 2.

Participating writes (send If-Match and bump the follow cursor): AddCartItem, UpdateCartItem, UpdateCart, ApplyCartDiscount. For versioning=follow or versioning=explicit, set options.resourceVersion on the first participating write to the cart metadata.version from GET /cart/{tenant}/carts/{cartId} or a prior GetCart.

GetCart and ValidateCart do not send If-Match and do not bump the cursor. They cannot seed it. Extra resourceVersion on these commands is ignored.

After a follow cursor exists for the cart, a successful RefreshCart, delete, or itemsBatch also bumps that cursor. Those commands cannot seed the cursor. Extra resourceVersion on them is ignored.

  • skip (default) – never passes a version. Ignores options.resourceVersion if present. The add-then-GET storefront flow uses this.

  • explicit – every participating command must send options.resourceVersion. The service checks the whole commands array before command 1. If any participating write is missing a version, the request returns 400 and results is not returned. Nothing is mutated. explicit is not skip: omitting resourceVersion on a participating write is a client error, not a last-write-wins strategy. Later commands are not rewritten; the client pre-computes N, N+1, and so on. The same N on two writes after a valid preflight yields command code 409 on the second command; the execute HTTP status stays 207 and the first write stays committed. GetCart, ValidateCart, RefreshCart, deletes, and itemsBatch do not require a version. A chain of only those commands has no participating writes, so preflight passes. Mixing explicit and skip behavior for different writes in one request is not supported; use skip or two requests.

  • follow – seeds from the first participating write. After that write succeeds, later participating writes use the version that was sent, plus 1. Follow state is an internal cursor and is not part of the HTTP body.

follow rules:

  • The first participating write must have options.resourceVersion. Missing version returns 400 for that command (not a whole-request preflight).

  • Later participating follow writes omit resourceVersion. A differing value versus the cursor returns 400 for that command. A matching value is accepted.

  • The bump is +1, the same as REST, for participating writes. After the cursor is seeded, a successful RefreshCart, delete, or itemsBatch also bumps it. A concurrent REST or /execute conflict is command code 409 inside the 207 body.

  • GetCart and ValidateCart do not bump the cursor and do not seed it.

  • If a write returns 409, the cursor does not bump. onError=fail stops; resume leaves later writes trying the old cursor.

Sequential commands run one after another. A concurrent REST or /execute conflict on the same cart is command code 409 inside the 207 body. A lock is not held across the whole chain.

Whole-request validation errors

The following fail with 400 for the entire call (not 207) before any command runs:

  • empty commands or more than 10 commands

  • unknown type

  • invalid onError or versioning query value

  • versioning=explicit with a participating command missing resourceVersion

  • request-body Bean Validation failures (for example a missing options.itemId or an invalid zipCode length). The response is the error body. results is not returned. This is schema-invalid for the whole request, not a per-command 400.

API Reference

How to follow cart resource versions in a command chain

versioning=follow keeps an internal version cursor for the cart identified by {cartId}. Set options.resourceVersion on the first participating write (AddCartItem, UpdateCartItem, UpdateCart, ApplyCartDiscount) to seed that cursor, then omit resourceVersion on later writes. GetCart and ValidateCart do not send If-Match and do not bump the cursor. After a cursor exists, a successful RefreshCart, delete, or itemsBatch also bumps it.

Use versioning=explicit only when every participating write sends resourceVersion. A missing version on explicit returns 400 for the whole request. That is a client error, not a last-write-wins strategy.

1

Read metadata.version from the cart

Call Retrieving cart details by ID to read metadata.version. Use that value as options.resourceVersion on the first participating write. You can also take it from a prior GetCart.

2

Send the follow chain

Send Executing a chain of cart commands with versioning=follow. Set options.resourceVersion on the first participating write to the metadata.version you read, and omit resourceVersion on later writes.

Cursor: PUT item 1 uses 5 and stores 6; PUT item 2 uses 6 and stores 7; GetCart leaves the cursor at 7; PUT item 3 uses 7 and stores 8.

API Reference

How to add custom attributes to a cart

You can define custom attributes for a cart through mixins.

1

Define your custom attributes schema

Create a schema that defines the custom cart fields by sending a request to the Creating a schema endpoint.

2

Retrieve the schema URL

Retrieve the created schema to get the schema URL by calling the Retrieving a schema endpoint.

3

Update a cart with custom attributes

To add custom attributes to a cart, send a request to the Updating a cart endpoint.

API Reference

How to merge carts

1

To merge an anonymous cart with a customer cart, send a request to the Merging carts endpoint. Provide the customer cart's ID in the cartId path parameter and the anonymous cart's ID in the request body.

API Reference

How to use external sources to modify a cart

Learn the ways to use external sources, like for example ERP systems, for modifying carts. It's possible to source externally price calculations, products, fees, or discounts.

How to source pricing information from an external price calculation tool

For B2B scenarios, you might want to integrate an external application for price calculation for your products. Usually, the systems, such as ERPs, store all the relevant customer-specific pricing information needed for customer-specific pricing. The external system then can communicate with the Cart Service directly to overwrite the price of the product added to the cart.

1

Once external pricing is enabled, you can add a product that is available within Commerce Engine, but with an external price. Send the request to the Adding a product to cart endpoint. Provide the customer cart's ID in the cartId path parameter.

Notice the "itemType": "EXTERNAL" definition which allows the Cart Service to overwrite the pricing from Commerce Engine. The payload must include the price and tax information.

API Reference

How to add a product from an external source to a cart

For some cases, you might want to allow adding products from an external system to cart, and not only from your online store. The products from external product management sources can be added directly to the customer's cart, bypassing the standard product catalog.

1

To add a product outside Commerce Engine, send the request to the Adding a product to cart endpoint. Provide the customer cart's ID in the cartId path parameter. The payload has to include the "itemType" : "EXTERNAL" parameter, as well as the price and tax information.

API Reference

How to add an external fee

For some cases, you might need to calculate and charge additional fees, for example for packaging, freight, or any additional reasons. The fees calculated externally can be added directly to the customer's cart.

1

To add a custom fee to the cart, send the request to the Adding a product to cart endpoint. Provide the customer cart's ID in the cartId path parameter. Custom fee can be configured both for EXTERNAL and INTERNAL products, the payload should include the "itemType" : "EXTERNAL" or "itemType" : "INTERNAL" parameter. If the parameter is not provided, then "INTERNAL" is taken as default.

API Reference

How to apply an external discount on a cart level

External discounts can be applied to the entire cart, allowing external systems (like ERP or pricing engines) to manage cart-wide promotions and discounts.

1

To apply an external discount to a cart, use the externalDiscounts attribute when creating or updating a cart. Send a request to the Updating a cart endpoint.

External cart discount attributes:

  • id - unique identifier of the external discount

  • discountType - type of discount:

    • PERCENT - percentage discount (e.g., 15.00 for 15%)

    • ABSOLUTE - monetary amount discount (e.g., 10.00 for 10 EUR)

    • FREE_SHIPPING - fully discounts the shipping cost

  • value - the discount value (percentage or absolute amount depending on discountType)

  • discountCalculationType - determines how the discount is applied:

    • TOTAL - discount is spread across products, product fees, and shipping cost

    • SUBTOTAL - discount is spread across products only, without fees or shipping

  • sequence - defines the order in which multiple discounts are applied (lower numbers are applied first)

The external discounts applied at cart level appear in the calculatedPrice.totalDiscount.appliedDiscounts array with origin: "EXTERNAL".

API Reference

How to apply an external discount on an item level

Adding an external discount to an item in a cart is done with the cart.cart_manage_external_prices scope.

1

Use the externalDiscounts attribute when adding an item to the cart or updating an existing one.

API Reference

How to pass externally calculated line price and line tax to items added or updated in the cart?

The Cart Service supports externally calculated pricing and tax amounts for cart items. This allows integrated systems to override cart's internal pricing logic with the values determined by external systems.

If you don’t want Emporix to calculate the line price by multiplying quantity × unit price, but instead want to provide the calculation from your ERP system, you can do so by supplying both linePrice and lineTax. These values are reflected in the line’s calculated price with calculated: EXTERNAL.

In the response, the lineTax will include the quantity information that was used in the add-to-cart request.

  • linePrice - externally calculated total price for the item line (unit price × quantity)

  • lineTax - externally calculated total tax for the item line, allowed only for external product type

The attributes are only allowed when itemType = EXTERNAL. If these values are provided, they are stored and returned unchanged in cart responses.

Payload example for Adding a product to cart:

Returned response example:

The price.calculated field indicates the source of the total price:

  • INTERNAL – for the price calculated by Emporix (unitPrice × quantity).

  • EXTERNAL – for the price taken directly from linePrice (authoritative).

Calculation behaviour with external line price and line tax

When you use linePrice and lineTax in cart operations, the following rules apply:

  • If lineTax is provided, these values take priority over internally calculated totals for calculatedPrice and finalPrice. If neither is provided, then cart service calculates totals internally based on the unit price and quantity.

  • For partial cart item updates (with partial=true), any existing linePrice or lineTax values are preserved if they are not provided in the update payload.

  • For full cart item updates, any previously set linePrice or lineTax values are cleared if they are not included in the update payload.

  • If the item’s quantity is updated after an external linePrice was set, the cart recalculates it internally (calculated = INTERNAL) and ignores the previous external value. To restore external pricing, a new linePrice must be provided that matches the new quantity.

    If the linePrice is provided, the quantity of the provided linePrice values has to much the quantity of items in the cart. Otherwise, the additional items are calculated internally.

  • In Retrieving all products added to a cart or Retrieving a cart item, any externally provided linePrice and lineTax are returned unchanged.

    A quantity field is included on lineTax in responses, reflecting the quantity used when the external tax was calculated.

For order entries, the calculated = INTERNAL/EXTERNAL flag is also returned - it indicates how the pricing was derived.

How is price calculated

To ensure that both net and gross prices are available, along with clear details on how these values are derived, the Cart Service includes the calculatedPrice field.

At the item level, there's a calculatedPrice attribute, which contains detailed price calculations for a specific item. Additionally, a calculatedPrice is also available at the cart level, summarizing the price calculations for all items in the cart.

This calculation method provides a comprehensive breakdown of prices, including net values, gross values, tax details, fees, and discounts, both at the cart level and for individual line items.

Pricing glossary - calculated price on item level

Term
Definition

price

A unit price from priceMatch, it's multiplied by item quantity.

upliftValue

An additional amount authorized for payment to cover potential price adjustments during packing of weight-based products. There are two conditions to have this value for an item line:

  • The item has to be added to the cart with the "weightDependent":true attribute. It means that the quantity may vary during packaging, as some items, for example a case of bananas, cannot be divided to precisely match a given weight.

  • The tenant has to have the percentage uplift defined - authorizedAmountUplift, for example 0,1=10%. If the item price.netValue=12, the upliftValue.netValue=1,2 with the 10% uplift configured. If the upliftValue is not configured for an item, it's not returned in the response.

discountedPrice

The price of the line item is calculated as unit price × quantity, with any applied discounts. If no discounts are applied to a given line item, this attribute is not included in the response. Depending on the site configuration, the includesTax attribute can be true or false. The discount is applied to price.grossValue when includesTax=true or price.netValue when includesTax=false. Based on this, the corresponding netValue or grossValue is recalculated using the taxRate. The calculation method that was used is indicated in totalDiscount.calculationType, which can be either ApplyDiscountAfterTax or ApplyDiscountBeforeTax.

fees

A list of fees applied to the line item. If there are no fees on the line item, it's not returned in the response.

  • Types of fees:

    • PERCENT - The fee percentage of the line item price.netValue - unit price x quantity.

    • ABSOLUTE - The absolute amount assigned to the item line.

    • ABSOLUTE_MULTIPLY_ITEMQUANTITY - Monetary amount multiplied by the item quantity and assigned to the item line.

  • Fees origin:

    • INTERNAL - Defined in commerce engine

    • EXTERNAL - Specified when an item is added to the cart.

  • netValue - Monetary amount of the fee. Depends on the fee type:

    • ABSOLUTE - The value of the defined fee's feeAbsolute.amount attribute.

    • ABSOLUTE_MULTIPLY_ITEMQUANTITY - The value of the defined fee's feeAbsolute.amount attribute multiplied by the quantity of the line item.

    • PERCENT - The defined fee level percentage (feePercentage attribute) of the line item price.netValue.

  • grossValue - Value calculated based on the taxCode and the taxRate if taxable=true. For a fee that is taxable=true and has a correct taxCode, the taxRate defined for that taxCode is used to calculate the grossValue. If the fee is not taxable, the netValue is equal to grossValue.

  • taxRate - If a fee is defined with the attribute taxable=true, the tax rate is calculated based on the provided taxCode at the fee level. A taxable fee must have a defined taxCode.

  • taxCode - Tax code defined on the fee level, for example STANDARD. The value should match the available tax codes in the system configuration.

totalFee

Sum of all fees applied to the line item. It's calculated by summarizing fees[].discountedPrice if any discounts were applied to the fee, or fees[].price for a a not discounted fee.

totalDiscount

A summary of all discounts applied to the line, including discounts on both the line item's price and its fees. If there are no discounts applied on the line item, it's not returned in the response.

totalDiscount.calculationType

Indicates whether discounts were applied to net or gross values.

  • The discount is applied to either price.grossValue, when includesTax=true, or price.netValue, when includesTax=false. Based on this, the corresponding net or gross value is recalculated using the tax rate.

  • The calculation method used is indicated in totalDiscount.calculationType>, which can be either ApplyDiscountAfterTax or ApplyDiscountBeforeTax.

finalPrice

The final price is the sum of the discountedPrice or the original price, depending on whether any discounts were applied to the line item, and the totalFee, which includes all fees applied to the line item.

Pricing glossary - calculated price on cart level

Term
Definition

price

A sum of all line item prices without discounts.

upliftValue

It's the sum of all uplift values from item lines. At item level, it's an additional amount authorized for payment to cover potential price adjustments during packing of weight-based products. There are two conditions to have this value for an item line:

  • The item has to be added to the cart with the "weightDependent":true attribute. It means that the quantity may vary during packaging, as some items, for example a case of bananas, cannot be divided to precisely match a given weight.

  • The tenant has to have the percentage uplift defined - authorizedAmountUplift, for example 0,1=10%. If the item price.netValue=12, the upliftValue.netValue=1,2 with the 10% uplift configured. If the upliftValue is not configured for an item, it's not returned in the response.

discountedPrice

The sum of all line item prices after discounts. This attribute is included in the response if at least one line item has a discounted price. It represents the total of discounted prices for line items with discounts applied, or the regular prices for line items without discounts. Ultimately, it reflects the total cost of all line items after discounts.

fees

It's a sum of all the fees of the line items in the cart - sum of all items[].calculatedPrice.fees.price. The fees are WITHOUT discounts.

totalFee

Sum of all fees applied on the line items. It's a sum of items[].calculatedPrice.totalFee, WITH applied discounts.

shipping

The calculated shipping cost. It takes the sum of items[].calculatedPrice.price.grossValue for shipping estimation. It's shipping cost WITHOUT applied discounts.

totalShipping

The total shipping cost is calculated by summing items[].calculatedPrice.price.grossValue for shipping estimation. grossValue is used because, even for zero-tax items, it remains equal to netValue. It's a shipping cost WITH applied discounts.

totalDiscount

A summary of all discounts. It's the sum of all lines[].totalDiscount and shipping discounts. When discount is applied before tax the value equals price.netValue and price.grossValue for discount applied after tax.

finalPrice

The final price is the sum of items[].finalPrice, totalShipping.

finalPrice.taxAggregate - lines

A list of tax values grouped by taxCode and taxRate. It includes the sum of item[].calculatedPrice.discountedPrice or item[].calculatedPrice.price, item[].calculatedPrice.fees[].discountedPrice or item[].calculatedPrice.fees[].price, calculatedPrice.totalShipping and calculatedPrice.paymentFees. If any of these values have the same taxRate but different taxCode, they are listed separately. The aggregation also includes items that do not have a taxRate or taxCode defined.

See the sections below for shipping, payment fee, tax and discounts calculations.

How to calculate shipping cost at cart level

Shipping is calculated at two moments, depending on the stage at which it is performed.

  • On the cart, Cart Service calculates an estimate: the cheapest matching fee for this destination, or the fee for a delivery slot. The customer sees a preview amount. No method is selected.

  • At checkout, Checkout Service uses a quote: the list of methods and fees for a destination. The customer chooses a method and zone, and sees the amount that is charged.

Both answers come from Shipping Service configuration (zones, methods, and fees). The cart amount is a real estimate, not a placeholder. Cart Service does not send a method or zone, and it never calls POST /quote.

On the cart: estimated shipping

While the customer is still shopping, they have usually not chosen a delivery method and zone yet. Cart Service therefore calculates an estimate, not a final charge.

  • The shipment is always treated as coming from sites.homeBase.address.

  • The destination is the cart shipping address, or countryCode and zipCode if that is all that is available.

  • If no destination was provided, Cart Service fills one in this order:

    1. Legal entity address – If the cart is associated with a legal entity, the first location containing country, zipCode, and the required address type is used (origin: LEGAL_ENTITY).

    2. Customer address – If the cart has a logged-in customer, the default address matching the required type is used (origin: CUSTOMER).

    3. Site home base address – If none of the above are available, the site's home base address is used (origin: SITE).

The shipToAddress is determined in the following way:

  • cart address with origin REQUEST and type SHIPPING

  • cart countryCode and zipCode — kept for backward compatibility from when it was not possible to define addresses at the cart level

  • cart address with origin LEGAL_ENTITY, CUSTOMER, or SITE, and type SHIPPING

Cart Service then calls Shipping Service:

When no delivery window is set, Cart Service sends a request to the Calculating the minimum shipping cost endpoint.

The response is a single fee, not a list of methods. That amount appears on the cart as shipping:

The storefront does not call Shipping Service for the cart preview. Cart Service requests the estimate when the cart has a destination. Provide that destination as an address of type SHIPPING when you have one — the address uses country and zipCode. If you only have a country and postal code, set cart-level countryCode and zipCode instead. Do not assign a shipping method.

The storefront calls these public Cart APIs:

Optional: refine the estimate with a delivery slot

Use these steps when you want a slot-specific shipping estimate on the cart. The storefront retrieves available delivery windows, puts one on the cart, and then retrieves the cart to see the updated estimate. Setting a delivery window does not mean the customer selected a shipping method.

After you update the cart with a window and slot, Cart Service calls Calculating the shipping cost for a given slot. The storefront does not send that request.

1

Retrieve available delivery windows

Fetch available delivery windows for a cart by calling the Retrieving delivery windows by cart endpoint.

2

Update the cart with destination and delivery window

Pick the delivery window you want to use and update the cart by calling the Updating a cart endpoint.

3

Verify the shipping estimate

Verify the results by retrieving the cart. Call the Retrieving cart details by ID endpoint.

As a result, the cart response includes the shipping estimate:

Cart Service obtained that amount by sending a request like this to the Calculating the shipping cost for a given slot endpoint:

At checkout: final shipping quote

When the customer is ready to order, they choose a shipping method. The storefront calls Calculating the final shipping cost (POST /shipping/{tenant}/{site}/quote) to list methods and fees for the checkout address.

The response lists matching methods, grouped by zone:

The checkout request must map the selected method's zone.id, methods[].id, methods[].name, and methods[].fee.amount to zoneId, methodId, methodName, and amount. Include shippingTaxCode when the quote returns it. Checkout Service calls /quote again, keeps the matching method, and checks that the submitted amount is correct. If it is not, checkout fails.

Do not send the cart estimate as the checkout amount unless the customer selected that same cheapest method.

See Checkout Tutorial for the full contract and request example.

Cart API reference:

API Reference

Delivery and Shipping API reference:

API Reference

How to calculate a payment fee at cart level

At the cart level, only one additional fee is calculated, apart from the fees applied at the item level. The paymentFees is an additional, non-discountable amount that the customer must pay for using a given payment method.

The fee has a specific format, and there are two options for calculating it:

  • ABSOLUTE - the value of defined fee’s attribute feeAbsolute.amount, where the amount is treated as netValue.

  • PERCENT - the fee is calculated as a percentage of the total net value of all item lines' finalPrice.netValue, plus the cart’s calculatedPrice.totalShipping.netValue. The fee is specified by the feePercentage attribute.

If the fee is taxable and has a tax code, the gross value is calculated. Otherwise, the grossValue is equal to netValue.

How to determine a tax country at cart level

The tax country code is determined based on the following rules: First, we need to decide what type of the address should be used for tax determination. Based on site's setting taxDeterminationBasedOn:

  • SHIPPING_ADDRESS - use the address that is tagged with SHIPPING

  • BILLING_ADDRESS - use the address that is tagged with BILLING

  • Use an address of origin REQUEST and matching type

  • Use the country code that is set on the cart directly - backward compatibility.

  • Use an address of origin LEGAL_ENTITY and matching type

  • Use an address of origin CUSTOMER and matching type

  • Use an address of origin SITE and matching type

How to apply discounts at cart level

Discounts are known as coupons and, with the relevant settings that influence calculatedPrice, they can be applied to a cart.

Depending on the site configuration and the includesTax=true/false, the discount is applied to either the gross value - includesTax=true, or the net value - includesTax=false. Based on this setting, the corresponding netValue or grossValue is recalculated using the tax rate.

The information about which calculation method was used is available in the totalDiscount.calculationType=ApplyDiscountAfterTax/ApplyDiscountBeforeTax:

  • discountCalculationType:

    • SUBTOTAL - the discounts are applied on items[].calculatedPrice.price. The line item fees and shipping cost are NOT discounted.

    • TOTAL - the discounts are applied on items[].calculatedPrice.price, the line item fees and shipping cost.

  • discountType:

    • ABSOLUTE - a coupon that has a given type must have discountAbsolute attribute configured. It represents a monetary amount that should be discounted.

    Depending on the ApplyDiscountAfterTax/ApplyDiscountBeforeTax discount, the absolute amount is subtracted either from the grossValue or the netValue. The value of the discount on the cart level is divided across all the applicable cart prices, proportionally to the items[].calculatedPrice.price, items[].calculatedPrice.fees[].price and the calculated shipping cost. It's related to the difference between discountCalculationType:SUBTOTAL/TOTAL described above, to know which items are applicable.

    • PERCENT - it takes the value of discount’s discountPercentage attribute and calculates the percentage discount to the price.

    • FREE_SHIPPING - this type of a discount fully discounts the price of the calculatedPrice.totalShipping. It's applied before any other discount is applied.

  • categoryRestricted - the discount applies only to the line items that belong to a specific category. If the discountCalculationType=TOTAL, a fee of an item that fulfills the restriction is discounted. However, any other fees, or shipping are not part of the discounting.

  • segmentRestricted - the discount is applied only to the line items that belong to the given customer segment.

Since the system can be configured to allow more than one discount to a cart, it has a few implications:

  • The FREE_SHIPPING discount is applied on the shipping first.

  • The rest of the discounts are applied based on the order the discounts were applied to the cart.

  • Every PERCENT discount is calculated based on the original price, without applied discounts. Applying two coupons of 10% to 15.0 value results in 12.0 discounted price and two applied discounts of 1,5 value.

  • Every ABSOLUTE discount uses the not discounted values for the discount value spread. It means that if the given applicable item is already fully discounted, the remaining amount of the discount is spread proportionally on the discounts that still have some value left.

For some cases, you might need to calculate and charge additional fees, for example for packaging, freight, or any additional reasons. The fees calculated externally can be added directly to the customer's cart.

To achieve the communication between Commerce Engine and the fee management tool, you have to configure both systems accordingly. The steps required for such a case are described in the External Products, Pricing and Fees documentation. You need to generate a dedicated scope that serves as the authorization token for the API calls.

To add a custom fee to the cart, send the request to the endpoint. Provide the customer cart's ID in the cartId path parameter. The payload has to include the "itemType" : "EXTERNAL" parameter - see the Adding a product to a cart documentation.

How to apply separation of the same line items in the cart

When you add an item to the cart, it's stored as a single line. If you add the same item multiple times, it remains a single line item, but the quantity attribute is updated to reflect the total amount, for example when you add 5 items they are stored as item1: productA, qty:5.

If add the same item multiple times on separate lines in the cart, use the keepAsSeparateLineItem=true flag - it ensures each instance of the item appears as a distinct line item. This can be useful in a variety of scenarios, such as applying different discounts or fees to the same product, or handling separate delivery options.

A common use case is the Buy 2, Get 1 Free promotion. In this case, when a customer adds two of the same line items to the cart, the system can add a third instance as a separate line item marked as free.

Using the keepAsSeparateLineItem=true flag stores each addition of the product as an individual line, while the keepAsSeparateLineItem=false keeps them all in one.

By default, all items are grouped into a single line in the cart. This behavior is defined by keepAsSeparateLineItem=false. However, even if the keepAsSeparateLineItem flag is not explicitly included in the payload, the system assumes this default behavior. In other words, unless stated otherwise, keepAsSeparateLineItem=false is always applied.

Adding the keepAsSeparateLineItem":true flag to the payload example:

Usage examples

Adding multiple productA items with the keepAsSeparateLineItem=true flag

  • Adding the first productA item with keepAsSeparateLineItem=true results in:

  • Adding another productA item with keepAsSeparateLineItem=true results in:

Adding multiple productA items with the keepAsSeparateLineItem=false flag

  • Adding the first productA item with keepAsSeparateLineItem=false results in:

  • Adding another productA item with keepAsSeparateLineItem=false results in:

Adding multiple productA items with the keepAsSeparateLineItem=true and keepAsSeparateLineItem=false flags

  • Adding the first productA item with two different flags results in:

  • Adding another two productA items with different flags results in:

Products with external prices

You can add external prices for both custom products and products from the internal catalog. Line items for the same product can have different prices if they’re added separately with keepAsSeparateLineItem=true.

For example:

  • Adding the first productA item with priceX and keepAsSeparateLineItem=true results in

  • Adding another productA item to it, but with priceY and keepAsSeparateLineItem=true results in:

Products with standard prices

When using internal prices, the priceId is the same across all line items - if the product uses a standard price from the catalog, all lines for that item are expected to have the same price.

For example:

  • Adding the first productA item with priceX and keepAsSeparateLineItem=true results in:

  • Adding another productA item with different priceY and keepAsSeparateLineItem=true results in:

    • If cartItemValidationSkipExistingItemsValidationOnAddToCart=false, the validation occurs, and an error is thrown due to the price mismatch.

    • If cartItemValidationSkipExistingItemsValidationOnAddToCart=true, the validation does not occur, and the cart accepts the new line item.

Adding products with internal and external pricing

When you add the same product first as an internal one and then as an external, the items are split into separate line items even if keepAsSeparateLineItem=false, or if the flag is not present.

  • Adding productA item, with internal priceX and keepAsSeparateLineItem=false results in:

  • Adding productA item to it, with external priceY and keepAsSeparateLineItem=false results in:

A customer can have multiple open carts of different types. To implement save-for-later functionality (for example, wishlists) alongside a shopping cart, see the Wishlist Cart Tutorial.

Last updated

Was this helpful?