Skip to content

k.commerce.cart ​

Shopping cart management.

Execution ContextPrerequisitesTypical Use
KScript API (k.api.get / k.api.post), server-side <script env="server">Products and variants must exist; configure discount or shipping rules in Commerce backend before applying codes or shipping methodsCreate/reuse session carts, add/remove line items, bind contact info, apply discount codes/shipping, and compute checkout totals

k.commerce.cart provides full lifecycle operations for shopping carts, including session binding, item management, customer contact association, coupons, shipping selection, and detailed total calculation with taxes, discounts, and points.

Quick Start ​

js
k.api.post(() => {
    const cartId = k.commerce.cart.currentId || k.commerce.cart.create()
    const product = k.commerce.product.list()[0]
    const detail = k.commerce.product.get(product.id)
    const variantId = detail.variants[0].id

    k.commerce.cart.addOrUpdateLine(cartId, variantId, 1, {
        note: 'Quick add'
    })
    const summary = k.commerce.cart.getDetail(cartId)
    return { cartId, totalQuantity: summary.totalQuantity, totalAmount: summary.totalAmount }
})

Quick Reference ​

Method / PropertyDescriptionReturns
currentIdRead-only property returning the cart ID bound to the current session, or null if unboundstring | null
create(options?)Create a cart and bind it to the current request sessionstring
get(cartId)Retrieve basic cart dataCart | null
getDetail(cartId, options?)Retrieve computed cart totals including discounts, shipping, tax, and pointsCartDetail | null
addOrUpdateLine(cartId, variantId, quantity, options?)Add or update a cart line item (supports bundled product groups)void
removeLine(cartId, variantId, groupName?)Remove a variant line item from the cartvoid
updateContact(cartId, email)Update contact email (automatically binds customerId when matched)void
updateDiscountCodes(cartId, discountCodes)Replace coupon codes applied to the cartvoid
updateShipping(cartId, shippingId)Set the physical shipping methodvoid
updateDigitalShipping(cartId, shippingId)Set the digital delivery methodvoid
updateAdditional(cartId, options)Update points redemption toggle, insurance amount, and extension buttonvoid

Cart Existence Requirement

All mutating cart methods (addOrUpdateLine, removeLine, updateAdditional, updateContact, updateDigitalShipping, updateDiscountCodes, updateShipping) require an existing cartId; passing null or a non-existent cartId throws a runtime exception.

currentId ​

Read-only property that returns the shopping cart ID associated with the current request session, or null if no cart has been created or bound in the session yet (calling create() populates this session state). No parameters.

Type: string | null

js
k.api.get(() => {
    const cartId = k.commerce.cart.currentId
    return { currentId: cartId }
})

create() ​

Create a shopping cart and bind it to the current request session.

ParameterTypeRequiredDescription
optionsCartOptionsNoOptional creation parameters
options.extensionButton{ text: string, url: string }NoExtension button shown in the Commerce backend
options.insuranceAmountnumberNoInsurance amount

Returns: string. Newly created cart ID.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create({
        extensionButton: { text: 'Test', url: '/test' },
        insuranceAmount: 100
    })
    return { cartId }
})

get() ​

Get basic shopping cart information.

ParameterTypeRequiredDescription
cartIdstringYesCart ID

Returns: Cart | null. Returns null when the cart does not exist.

js
k.api.get(() => {
    const cartId = k.commerce.cart.currentId
    return k.commerce.cart.get(cartId)
})

getDetail() ​

Get computed shopping cart details including discounts, shipping costs, taxes, and point deductions.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
optionsGetCartOptionsNoOptional currency and destination overrides
options.currencystringNoCurrency code
options.countrystringNoCountry (English country name or ISO country code, e.g. "China" or "CN", used for tax lookup)
options.provincestringNoProvince / state (English name, e.g. "Guangdong"; takes precedence over city for tax region matching)
options.citystringNoCity (English name, e.g. "Guangzhou"; used for tax region matching when province is omitted)

Returns: CartDetail | null. Returns null when the cart does not exist.

js
k.api.get(() => {
    const cartId = k.commerce.cart.currentId
    return k.commerce.cart.getDetail(cartId, {
        currency: 'USD',
        country: 'China',
        province: 'Guangdong',
        city: 'Guangzhou'
    })
})

addOrUpdateLine() ​

Add or update a shopping cart line item.

Quantity Rules

quantity is truncated to an integer and clamped to a minimum of 1 (passing values < 1 stores 1). To delete a line item, call removeLine(). Throwing occurs if cartId does not exist.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
variantIdstringYesProduct variant ID
quantitynumberYesQuantity
optionsCartLineOptionsNoOptional line configuration
options.notestringNoLine note
options.groupNamestringNoBundle product group name (lines with the same groupName form a bundle)
options.isMainbooleanNoWhether this item is the main product in a bundle
options.extensionButton{ text: string, url: string }NoExtension button

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    const product = k.commerce.product.list()[0]
    const detail = k.commerce.product.get(product.id)
    const variantId = detail.variants[0].id

    k.commerce.cart.addOrUpdateLine(cartId, variantId, 2, {
        note: 'test line',
        groupName: 'Bundle Group 1',
        isMain: true
    })
    const cart = k.commerce.cart.getDetail(cartId)
    return { cartId, lineCount: cart.lines.length, totalAmount: cart.totalAmount }
})

removeLine() ​

Remove a product variant line from the shopping cart.

Bundle Removal & Null Handling

  • Removing the main item of a bundle (groupName is non-null and isMain is true) removes all lines sharing that groupName.
  • cartId must refer to an existing cart (otherwise a runtime exception is thrown); if the matching variant line does not exist, the call is a no-op.
ParameterTypeRequiredDescription
cartIdstringYesCart ID
variantIdstringYesProduct variant ID
groupNamestringNoBundled product group name

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.currentId
    if (!cartId) {
        return { error: 'Cart not found' }
    }
    const product = k.commerce.product.list()[0]
    const detail = k.commerce.product.get(product.id)
    const variantId = detail.variants[0].id

    k.commerce.cart.removeLine(cartId, variantId)
    const cart = k.commerce.cart.get(cartId)
    return { cartId, lineCount: cart.lines.length }
})

updateAdditional() ​

Update cart additional fields (points redemption, extension button, and insurance amount).

ParameterTypeRequiredDescription
cartIdstringYesCart ID
optionsCartAdditionalOptionsYesFields to update
options.redeemPointsbooleanNoWhether to use points
options.extensionButton{ text: string, url: string }NoExtension button
options.insuranceAmountnumberNoInsurance amount

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    k.commerce.cart.updateAdditional(cartId, {
        redeemPoints: true,
        extensionButton: { text: 'Test', url: '/test' },
        insuranceAmount: 100
    })
    const cart = k.commerce.cart.get(cartId)
    return { cartId, redeemPoints: cart.redeemPoints, insuranceAmount: cart.insuranceAmount }
})

updateContact() ​

Update the shopping cart customer contact email.

Note

If a customer record exists for email, customerId is bound automatically; otherwise only contact is stored.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
emailstringYesContact email

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    k.commerce.cart.updateContact(cartId, 'test@test.com')
    const cart = k.commerce.cart.get(cartId)
    return { cartId, contact: cart.contact, customerId: cart.customerId }
})

updateDigitalShipping() ​

Update the digital delivery method for the cart.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
shippingIdstringYesDigital shipping method ID

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    const digitalShipping = k.commerce.shipping.digitalList()[0]
    k.commerce.cart.updateDigitalShipping(cartId, digitalShipping.id)
    const cart = k.commerce.cart.get(cartId)
    return { cartId, digitalShippingId: cart.digitalShippingId }
})

updateDiscountCodes() ​

Update coupon codes applied to the shopping cart.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
discountCodesstring[]YesArray of coupon codes

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    const discount = k.commerce.discount.list()[0]
    k.commerce.cart.updateDiscountCodes(cartId, [discount.code])
    const cart = k.commerce.cart.get(cartId)
    return { cartId, discountCodes: cart.discountCodes }
})

updateShipping() ​

Update the physical shipping method for the shopping cart.

ParameterTypeRequiredDescription
cartIdstringYesCart ID
shippingIdstringYesShipping method ID

Returns: void.

js
k.api.post(() => {
    const cartId = k.commerce.cart.create()
    const shipping = k.commerce.shipping.list({ cartId })[0]
    k.commerce.cart.updateShipping(cartId, shipping.id)
    const cart = k.commerce.cart.get(cartId)
    return { cartId, shippingId: cart.shippingId }
})

Structures ​

Cart Properties ​

PropertyDescriptionType
idCart IDstring
traceIdSession trace IDstring
customerIdCustomer IDstring
contactContact emailstring
countryCountrystring
discountCodesCoupon codesstring[]
noteNotestring
linesRaw shopping cart linesCartLine[]
shippingIdShipping method IDstring
digitalShippingIdDigital shipping method IDstring
insuranceAmountInsurance amountnumber
extensionButtonExtension button{ text: string, url: string } | null
redeemPointsWhether points are redeemedboolean
createdAtCreation timestring
updatedAtUpdate timestring

CartLine Properties ​

Raw line structure stored in Cart.lines. Computed line items with title, price, sku, amount, and taxAmount are only returned on CartDetail.lines (CartItem).

PropertyDescriptionType
variantIdProduct variant IDstring
quantityProduct quantity (clamped to 1 if < 1)number
groupNameBundle product group namestring
isMainWhether it is the main product in a bundleboolean
noteNotestring
extensionButtonExtension button{ text: string, url: string } | null

CartDetail Property ​

PropertyDescriptionType
idCart IDstring
contactContact emailstring
countryCountrystring
currencyCurrency information{ code: string, symbol: string, rate: number }
discountCodesApplied coupon codesstring[]
activeDiscountCodesActive coupon codesstring[]
noteNotestring
discountAllocationsApplied discount allocations (includes both automatic and coupon-code discounts)DiscountAllocation[]
shippingAllocationsShipping allocationsShippingAllocation[]
shippingAmountShipping amountnumber
insuranceAmountInsurance amountnumber
subtotalAmountSubtotal amountnumber
totalAmountTotal amountnumber
taxAmountTax amountnumber
totalQuantityTotal quantitynumber
redeemPointsRedeemed pointsnumber
pointsDeductionAmountPoints deduction amountnumber
earnPointsEarned pointsnumber
shippingDelivery methodShipping | null
linesCart detail itemsCartItem[]

CartItem Properties ​

Maps to CartDetailLine in the TypeScript definitions (used exclusively in CartDetail.lines).

PropertyDescriptionType
variantIdProduct variant IDstring
productIdProduct IDstring
titleProduct titlestring
optionsProduct variant options{ name: string, value: string }[]
skuProduct SKUstring
imageProduct imagestring
originalPriceOriginal product pricenumber
priceProduct pricenumber
discountAllocationsApplied discount allocations (includes both automatic and coupon-code discounts)DiscountAllocation[]
quantityProduct quantitynumber
totalQuantityTotal item quantitynumber
amountProduct subtotal amountnumber
taxAmountProduct tax amountnumber
inventoryProduct inventorynumber
groupNameProduct group namestring
isMainWhether it is the main product in a bundleboolean
noteProduct notestring

ShippingAllocation Property ​

PropertyDescriptionType
costDelivery costnumber
titleShipping method titlestring
isAdditionalWhether this is an additional shipping feeboolean

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KCart {
  currentId: string;
  create(options?: CartOptions): string;
  get(cartId: string): Cart;
  getDetail(cartId: string, options?: GetCartOptions): CartDetail;
  addOrUpdateLine(cartId: string, variantId: string, quantity: number, options?: CartLineOptions): void;
  removeLine(cartId: string, variantId: string, groupName?: string): void;
  updateContact(cartId: string, email: string): void;
  updateDiscountCodes(cartId: string, discountCodes: string[]): void;
  updateShipping(cartId: string, shippingId: string): void;
  updateDigitalShipping(cartId: string, shippingId: string): void;
  updateAdditional(cartId: string, options: CartAdditionalOptions): void;
}

interface CartOptions {
  /** Display a extension button on Kooboo commerce backend page. */
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
  insuranceAmount?: number;
}

interface GetCartOptions {
  currency: string;
  country: string;
  province: string;
  city: string;
}

interface CartDetail {
  id: string;
  contact: string;
  country: string;
  currency: Kooboo.Sites.Commerce.Entities.Currency;
  discountCodes: string[];
  activeDiscountCodes: string[];
  note: string;
  discountAllocations: Kooboo.Sites.Commerce.Calculate.DiscountAllocation[];
  shippingAllocations: Kooboo.Sites.Commerce.Calculate.ShippingAllocation[];
  shippingAmount: number;
  insuranceAmount: number;
  subtotalAmount: number;
  totalAmount: number;
  taxAmount: number;
  totalQuantity: number;
  redeemPoints: number;
  pointsDeductionAmount: number;
  earnPoints: number;
  shipping: Kooboo.Sites.Commerce.Entities.Shipping;
  lines: CartDetailLine[];
}

interface CartDetailLine {
  variantId: string;
  productId: string;
  title: string;
  options: Kooboo.Sites.Commerce.Entities.ProductVariantOption[];
  sku: string;
  image: string;
  originalPrice: number;
  price: number;
  discountAllocations: Kooboo.Sites.Commerce.Calculate.DiscountAllocation[];
  quantity: number;
  totalQuantity: number;
  amount: number;
  taxAmount: number;
  inventory: number;
  groupName: string;
  isMain: boolean;
  note: string;
}

interface CartLineOptions {
  /** Cart line with same group name value will become a bundle product. */
  groupName: string;
  /** Main product or not on a bundle product. */
  isMain: boolean;
  note: string;
  /** Display a extension button on Kooboo commerce backend page. */
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
}

interface CartAdditionalOptions {
  /** Display a extension button on Kooboo commerce backend page. */
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
  insuranceAmount?: number;
  redeemPoints?: boolean;
}

interface CartLine {
  variantId: string;
  quantity: number;
  groupName: string;
  isMain: boolean;
  note: string;
  extensionButton: ExtensionButton;
}

interface Cart extends Kooboo.Sites.Commerce.Entity {
  traceId: string;
  customerId: string;
  contact: string;
  country: string;
  discountCodes: string[];
  note: string;
  lines: CartLine[];
  extensionButton: ExtensionButton;
  shippingId: string;
  digitalShippingId: string;
  insuranceAmount: number;
  redeemPoints: boolean;
  id: string;
  createdAt: Date;
  updatedAt: Date;
  clone(): any;
  getGuid(): any;
}

interface ShippingAllocation {
  cost: number;
  title: string;
  isAdditional: boolean;
  applyRate(rate: number): ShippingAllocation;
}