k.commerce.cart
Shopping cart management.
| Execution Context | Prerequisites | Typical 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 methods | Create/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
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 / Property | Description | Returns |
|---|---|---|
currentId | Read-only property returning the cart ID bound to the current session, or null if unbound | string | null |
create(options?) | Create a cart and bind it to the current request session | string |
get(cartId) | Retrieve basic cart data | Cart | null |
getDetail(cartId, options?) | Retrieve computed cart totals including discounts, shipping, tax, and points | CartDetail | 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 cart | void |
updateContact(cartId, email) | Update contact email (automatically binds customerId when matched) | void |
updateDiscountCodes(cartId, discountCodes) | Replace coupon codes applied to the cart | void |
updateShipping(cartId, shippingId) | Set the physical shipping method | void |
updateDigitalShipping(cartId, shippingId) | Set the digital delivery method | void |
updateAdditional(cartId, options) | Update points redemption toggle, insurance amount, and extension button | void |
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
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
options | CartOptions | No | Optional creation parameters |
options.extensionButton | { text: string, url: string } | No | Extension button shown in the Commerce backend |
options.insuranceAmount | number | No | Insurance amount |
Returns: string. Newly created cart ID.
k.api.post(() => {
const cartId = k.commerce.cart.create({
extensionButton: { text: 'Test', url: '/test' },
insuranceAmount: 100
})
return { cartId }
})get()
Get basic shopping cart information.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
Returns: Cart | null. Returns null when the cart does not exist.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
options | GetCartOptions | No | Optional currency and destination overrides |
options.currency | string | No | Currency code |
options.country | string | No | Country (English country name or ISO country code, e.g. "China" or "CN", used for tax lookup) |
options.province | string | No | Province / state (English name, e.g. "Guangdong"; takes precedence over city for tax region matching) |
options.city | string | No | City (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.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
variantId | string | Yes | Product variant ID |
quantity | number | Yes | Quantity |
options | CartLineOptions | No | Optional line configuration |
options.note | string | No | Line note |
options.groupName | string | No | Bundle product group name (lines with the same groupName form a bundle) |
options.isMain | boolean | No | Whether this item is the main product in a bundle |
options.extensionButton | { text: string, url: string } | No | Extension button |
Returns: void.
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 (
groupNameis non-null andisMainistrue) removes all lines sharing thatgroupName. cartIdmust 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
variantId | string | Yes | Product variant ID |
groupName | string | No | Bundled product group name |
Returns: void.
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).
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
options | CartAdditionalOptions | Yes | Fields to update |
options.redeemPoints | boolean | No | Whether to use points |
options.extensionButton | { text: string, url: string } | No | Extension button |
options.insuranceAmount | number | No | Insurance amount |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
email | string | Yes | Contact email |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
shippingId | string | Yes | Digital shipping method ID |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
discountCodes | string[] | Yes | Array of coupon codes |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
cartId | string | Yes | Cart ID |
shippingId | string | Yes | Shipping method ID |
Returns: void.
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
| Property | Description | Type |
|---|---|---|
id | Cart ID | string |
traceId | Session trace ID | string |
customerId | Customer ID | string |
contact | Contact email | string |
country | Country | string |
discountCodes | Coupon codes | string[] |
note | Note | string |
lines | Raw shopping cart lines | CartLine[] |
shippingId | Shipping method ID | string |
digitalShippingId | Digital shipping method ID | string |
insuranceAmount | Insurance amount | number |
extensionButton | Extension button | { text: string, url: string } | null |
redeemPoints | Whether points are redeemed | boolean |
createdAt | Creation time | string |
updatedAt | Update time | string |
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).
| Property | Description | Type |
|---|---|---|
variantId | Product variant ID | string |
quantity | Product quantity (clamped to 1 if < 1) | number |
groupName | Bundle product group name | string |
isMain | Whether it is the main product in a bundle | boolean |
note | Note | string |
extensionButton | Extension button | { text: string, url: string } | null |
CartDetail Property
| Property | Description | Type |
|---|---|---|
id | Cart ID | string |
contact | Contact email | string |
country | Country | string |
currency | Currency information | { code: string, symbol: string, rate: number } |
discountCodes | Applied coupon codes | string[] |
activeDiscountCodes | Active coupon codes | string[] |
note | Note | string |
discountAllocations | Applied discount allocations (includes both automatic and coupon-code discounts) | DiscountAllocation[] |
shippingAllocations | Shipping allocations | ShippingAllocation[] |
shippingAmount | Shipping amount | number |
insuranceAmount | Insurance amount | number |
subtotalAmount | Subtotal amount | number |
totalAmount | Total amount | number |
taxAmount | Tax amount | number |
totalQuantity | Total quantity | number |
redeemPoints | Redeemed points | number |
pointsDeductionAmount | Points deduction amount | number |
earnPoints | Earned points | number |
shipping | Delivery method | Shipping | null |
lines | Cart detail items | CartItem[] |
CartItem Properties
Maps to CartDetailLine in the TypeScript definitions (used exclusively in CartDetail.lines).
| Property | Description | Type |
|---|---|---|
variantId | Product variant ID | string |
productId | Product ID | string |
title | Product title | string |
options | Product variant options | { name: string, value: string }[] |
sku | Product SKU | string |
image | Product image | string |
originalPrice | Original product price | number |
price | Product price | number |
discountAllocations | Applied discount allocations (includes both automatic and coupon-code discounts) | DiscountAllocation[] |
quantity | Product quantity | number |
totalQuantity | Total item quantity | number |
amount | Product subtotal amount | number |
taxAmount | Product tax amount | number |
inventory | Product inventory | number |
groupName | Product group name | string |
isMain | Whether it is the main product in a bundle | boolean |
note | Product note | string |
ShippingAllocation Property
| Property | Description | Type |
|---|---|---|
cost | Delivery cost | number |
title | Shipping method title | string |
isAdditional | Whether this is an additional shipping fee | boolean |
TypeScript Definitions
Show full TypeScript definitions
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;
}Related Docs
- k.commerce - E-commerce module overview
- product - Product management
- category - Category management
- order - Order management
- shipping - Shipping management