Skip to content

k.commerce.order ​

Order management.

Execution ContextPrerequisitesTypical Use
KScript API (k.api.get / k.api.post), server-side <script env="server">Cart-based creation requires lines added via k.commerce.cart; direct creation requires explicit linesQuery and filter orders, create orders at checkout, record payments, fulfill whole or split shipments, and update addresses or tracking info

k.commerce.order provides full order lifecycle operations: paginated order lookup, order creation from a cart or CreateOrderInit payload, payment marking, full or line-level fulfillment, address/shipping/extension updates, cancellation, reopening, and deletion.

Quick Start ​

js
k.api.get(() => {
    const result = k.commerce.order.list({
        paid: false,
        canceled: false,
        pageIndex: 1,
        pageSize: 10
    })
    return { count: result.count, items: result.list }
})

Quick Reference ​

Method / PropertyDescriptionReturns
list(query?)Query paginated orders (runtime returns OrderResult)OrderResult
get(orderId)Get full order details by IDOrderDetail | null
create(cartId, options)Create an order from an existing shopping cartOrderDetail
create(init)Create a standalone order directly from CreateOrderInitOrderDetail
pay(orderId, method)Mark the order as paid with the given payment methodvoid
delivery(orderId, shippingCarrier, trackingNumber)Mark the full order as shipped with carrier and tracking numbervoid
delivery(orderId, lineIds)Mark specific order line IDs as shipped (partial fulfillment)void
updateShippingInfo(orderId, orderLineId, options)Update shipping details or digital items for an order linevoid
updateAddress(orderId, address)Update the order shipping addressvoid
updateExtensionField(id, property, value)Update an existing key in order.extensionFieldsvoid
cancel(orderId, reason)Cancel an order with a reasonvoid
reopen(orderId)Reopen a canceled ordervoid
delete(id)Permanently delete an ordervoid

list() ​

Get a paginated list of orders.

Note: At runtime k.commerce.order.list() returns an OrderResult pagination object ({ list, count, pageIndex, pageSize }), whereas the IDE type definition currently declares OrderDetail[].

ParameterTypeRequiredDescription
queryOrderQueryNoFilter and pagination options
query.customerIdstringNoCustomer ID
query.paidbooleanNoWhether paid
query.deliveredbooleanNoWhether delivered
query.canceledbooleanNoWhether canceled
query.startDateDateNoStart date
query.endDateDateNoEnd date
query.pageIndexnumberNoPage number, default 1
query.pageSizenumberNoItems per page, default 30

Returns: OrderResult. Contains list (OrderDetail[]), count, pageIndex, and pageSize.

js
k.api.get(() => {
    const result = k.commerce.order.list({
        startDate: new Date('2025-01-01'),
        endDate: new Date('2025-12-31'),
        paid: false,
        delivered: false,
        canceled: false,
        pageIndex: 1,
        pageSize: 10
    })
    return result
})

get() ​

Get details for a specific order.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID

Returns: OrderDetail | null.

js
k.api.get(() => {
    const order = k.commerce.order.get('order-id')
    return { id: order.id, totalAmount: order.totalAmount }
})

create() ​

Create an order from an existing cart, or create a standalone order directly with CreateOrderInit.

Parameters (create(cartId, options)):

ParameterTypeRequiredDescription
cartIdstringYesCart ID
optionsCreateOrderOptionsYesOrder creation options
options.addressAddressYesShipping address
options.currencystringNoOrder currency code
options.extensionFieldsKeyValue[]NoExtension fields
options.notestringNoOrder note
options.scheduledDeliveryTimeDateNoScheduled delivery time

Parameters (create(init)):

ParameterTypeRequiredDescription
initCreateOrderInitYesDirect order payload
init.linesCreateOrderLineInit[]YesOrder line items
init.addressAddressNoShipping address
init.currencystringNoCurrency code
init.shippingAmountnumberNoShipping amount
init.customerIdstringNoExisting customer ID (customer email, name, and phone on the order are loaded solely from this matched customer record)
init.emailstringNoCustomer email (currently ignored by OrderService.Create; populated only from the customer matched by customerId)
init.firstNamestringNoCustomer first name (currently ignored; populated only from customerId)
init.lastNamestringNoCustomer last name (currently ignored; populated only from customerId)
init.phonestringNoCustomer phone (currently ignored; populated only from customerId)
init.sourcestringNoOrder source
init.notestringNoOrder note
init.extensionButtonExtensionButtonNoExtension button ({ text, url })
init.extensionFieldsKeyValue[]NoExtension fields

Returns: OrderDetail.

js
k.api.post(() => {
    // Overload 1: Create an order from a cart
    const cartId = k.commerce.cart.create()
    const product = k.commerce.product.create({
        title: 'Order Test Product',
        description: 'Test',
        price: 99.9,
        active: true,
        seoName: 'order-test-' + Date.now(),
        featuredImage: ''
    })
    k.commerce.product.createVariant(product.id, {
        sku: 'ORD-SKU-' + Date.now(),
        price: 99.9,
        inventory: 100,
        barcode: '',
        active: true,
        selectedOptions: []
    })
    const refreshed = k.commerce.product.get(product.id)
    k.commerce.cart.addOrUpdateLine(cartId, refreshed.variants[0].id, 1)

    const order = k.commerce.order.create(cartId, {
        address: {
            country: 'China',
            province: 'Fujian',
            city: 'Xiamen',
            address1: 'address1',
            address2: '',
            zip: '361000',
            firstName: 'firstName',
            lastName: 'lastName',
            phone: '13800138000',
            isDefault: true
        },
        currency: 'USD',
        note: 'test order',
        extensionFields: []
    })
    return { orderId: order.id, totalAmount: order.totalAmount }
})

Note: When creating an order via create(init), customer contact fields (email, firstName, lastName, phone) on the order are populated solely from the customer record matched by init.customerId; top-level email, firstName, lastName, and phone on init are currently ignored by OrderService.Create.

js
k.api.post(() => {
    // Overload 2: Create a standalone order directly via CreateOrderInit
    const customer = k.commerce.customer.getByEmail('buyer@example.com')
    const order = k.commerce.order.create({
        customerId: customer ? customer.id : '',
        currency: 'USD',
        shippingAmount: 10,
        source: 'api',
        note: 'Direct order',
        address: {
            country: 'China',
            province: 'Fujian',
            city: 'Xiamen',
            address1: 'address1',
            address2: '',
            zip: '361000',
            firstName: 'Ada',
            lastName: 'Lovelace',
            phone: '13800138000',
            isDefault: true
        },
        lines: [
            {
                title: 'Custom Service',
                price: 50,
                quantity: 2,
                image: '',
                extensionButton: { text: '', url: '' }
            }
        ],
        extensionButton: { text: '', url: '' },
        extensionFields: [{ key: 'channel', value: 'web' }]
    })
    return { orderId: order.id, totalAmount: order.totalAmount }
})

cancel() ​

Cancel an order.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
reasonstringYesReason for cancellation

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.cancel(orderId, 'cancel reason')
    const order = k.commerce.order.get(orderId)
    return { id: order.id, canceled: order.canceled, cancelReason: order.cancelReason }
})

delete() ​

Delete an order.

ParameterTypeRequiredDescription
idstringYesOrder ID

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.delete(orderId)
    return { deleted: k.commerce.order.get(orderId) === null }
})

pay() ​

Mark an order as paid.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
methodstringYesPayment method

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.pay(orderId, 'alipay')
    const order = k.commerce.order.get(orderId)
    return { id: order.id, paid: order.paid, paymentMethod: order.paymentMethod }
})

delivery() ​

Mark the full order as shipped with carrier/tracking details, or mark specific order lines as shipped.

Parameters (delivery(orderId, shippingCarrier, trackingNumber)):

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
shippingCarrierstringYesShipping carrier name or code (e.g. 'SF Express' or shipping.name)
trackingNumberstringYesTracking number

Parameters (delivery(orderId, lineIds)):

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
lineIdsstring[]YesOrder line IDs to mark as shipped

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    const shipping = k.commerce.shipping.list()[0]
    const carrier = shipping ? (shipping.code || shipping.name) : 'SF Express'
    k.commerce.order.delivery(orderId, carrier, 'SF123456789')
    const order = k.commerce.order.get(orderId)
    return {
        id: order.id,
        delivered: order.delivered,
        trackingNumber: order.lines[0] ? order.lines[0].trackingNumber : null
    }
})
js
k.api.post(() => {
    const orderId = 'order-id'
    const order = k.commerce.order.get(orderId)
    const lineIds = order.lines.map(l => l.id)
    k.commerce.order.delivery(orderId, lineIds)
    const updated = k.commerce.order.get(orderId)
    return { id: updated.id, delivered: updated.delivered, partialDelivered: updated.partialDelivered }
})

reopen() ​

Reopen a canceled order.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.reopen(orderId)
    const order = k.commerce.order.get(orderId)
    return { id: order.id, canceled: order.canceled }
})

updateAddress() ​

Update the order shipping address.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
addressAddressYesShipping address

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.updateAddress(orderId, {
        country: 'China',
        province: 'Fujian',
        city: 'Xiamen',
        address1: 'address1',
        address2: '',
        zip: '361000',
        firstName: 'firstName',
        lastName: 'lastName',
        phone: '13800138000',
        isDefault: true
    })
    const order = k.commerce.order.get(orderId)
    return { id: order.id, shippingAddress: order.shippingAddress }
})

updateShippingInfo() ​

Update shipping details for an individual order line.

ParameterTypeRequiredDescription
orderIdstringYesOrder ID
orderLineIdstringYesOrder item ID
optionsDeliveryOptionsYesShipping options
options.shippingCarrierstringNoShipping carrier name or code (e.g. 'SF Express' or shipping.name)
options.trackingNumberstringNoTracking number
options.digitalItemsDigitalOrderItem[]NoDigital product items

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    const order = k.commerce.order.get(orderId)
    const lineId = order.lines[0].id
    const shipping = k.commerce.shipping.list()[0]
    const carrier = shipping ? (shipping.code || shipping.name) : 'SF Express'

    k.commerce.order.updateShippingInfo(orderId, lineId, {
        shippingCarrier: carrier,
        trackingNumber: 'SF123456789'
    })
    const updated = k.commerce.order.get(orderId)
    return { id: updated.id, lineTracking: updated.lines[0].trackingNumber }
})

updateExtensionField() ​

Update the value of an existing key in order.extensionFields. Only entries whose key already exists on the order are updated.

ParameterTypeRequiredDescription
idstringYesOrder ID
propertystringYesExtension field key
valuestringYesUpdated field value

Returns: void.

js
k.api.post(() => {
    const orderId = 'order-id'
    k.commerce.order.updateExtensionField(orderId, 'channel', 'mobile')
    const updated = k.commerce.order.get(orderId)
    return { id: updated.id, extensionFields: updated.extensionFields }
})

Structures ​

OrderResult Properties ​

PropertyDescriptionType
listOrder detail listOrderDetail[]
countTotal countnumber
pageIndexCurrent page indexnumber
pageSizePage sizenumber

OrderDetail Property ​

Note: At runtime OrderDetail and OrderLine are converted via Helpers.ToKscriptModel, so all date/time properties are serialized date string values rather than JS Date objects.

PropertyDescriptionType
idOrder IDstring
customerCustomer informationCustomer
pointsDeductionAmountPoints deduction amountnumber
earnPointsPoints earnednumber
redeemPointsPoints redeemednumber
totalAmountTotal order amountnumber
taxAmountTax amountnumber
originalAmountOriginal amountnumber
shippingAmountShipping amountnumber
insuranceAmountInsurance amountnumber | null
subtotalAmountSubtotal amountnumber
originalSubtotalAmountOriginal subtotal amountnumber
totalQuantityTotal quantitynumber
currencyCurrency codestring
paidWhether paidboolean
paidAtPayment timestring | null
paymentMethodPayment methodstring
deliveredWhether deliveredboolean
partialDeliveredWhether partially deliveredboolean
trackingNumberTracking number (unassigned in OrderDetail constructor, always null; read from order.lines[].trackingNumber)string | null
shippingCarrierShipping carrier (unassigned in OrderDetail constructor, always null; read from order.lines[].shippingCarrier)string | null
shippingAtShipping timestring | null
scheduledDeliveryTimeEstimated delivery timestring | null
canceledWhether canceledboolean
cancelReasonReason for cancellationstring
cancelAtCancellation timestring | null
createdAtCreation timestring
updatedAtUpdate timestring
shippingAddressShipping addressAddress
noteOrder notestring
linesOrder itemsOrderLine[]
ipClient IP addressstring
countryCountrystring
sourceOrder sourcestring
clientInfoClient informationClientInfo
extensionButtonExtension button{ text: string, url: string }
discountAllocationsAutomatic discount allocationsDiscountAllocation[]
shippingAllocationsShipping allocationsShippingAllocation[]
extensionFieldsExtension fieldsKeyValue[]

CreateOrderLineInit Property ​

PropertyDescriptionType
titleProduct titlestring
priceUnit pricenumber
quantityQuantitynumber
imageProduct image URLstring
extensionButtonExtension button{ text: string, url: string }

Customer attribute ​

PropertyDescriptionType
idCustomer IDstring
emailCustomer emailstring
firstNameCustomer first namestring
lastNameCustomer last namestring
phoneCustomer phone numberstring

Address property ​

PropertyDescriptionType
idAddress IDstring
isDefaultWhether default addressboolean
countryCountrystring
provinceProvince / statestring
cityCitystring
address1Address line 1string
address2Address line 2string
firstNameRecipient first namestring
lastNameRecipient last namestring
phonePhone numberstring
zipPostal codestring

OrderLine Property ​

PropertyDescriptionType
idOrder line IDstring
totalAmountLine total amountnumber
taxAmountLine tax amountnumber
originalAmountLine original amountnumber
quantityLine quantitynumber
totalQuantityTotal quantity of items orderednumber
priceLine unit pricenumber
originalPriceOriginal line unit pricenumber
titleOrder item titlestring
imageOrder item image URLstring
productIdProduct IDstring
variantIdVariant IDstring
skuProduct SKUstring
orderIdOrder IDstring
optionsProduct options{ name: string, value: string }[]
discountAllocationsAutomatic discount allocationsDiscountAllocation[]
groupNameBundle group namestring
isMainWhether main bundle productboolean
noteOrder line notestring
extensionButtonExtension button{ text: string, url: string }
trackingNumberTracking numberstring
shippingCarrierShipping carrierstring
shippingAtShipping timestring | null
deliveredWhether deliveredboolean
digitalItemsDigital product itemsDigitalOrderItem[]
autoDeliveryWhether delivered automaticallyboolean
isDigitalWhether digital productboolean
maxDownloadCountMaximum download countnumber | null
maxDownloadDayMaximum download daysnumber | null
errorMessageError messagestring

ClientInfo Property ​

PropertyDescriptionType
platformPlatformstring
oSOperating systemstring
deviceDevicestring
applicationApplication informationApplicationInfo

ApplicationInfo Property ​

PropertyDescriptionType
isWebBrowserWhether web browserboolean
nameApplication namestring
versionApplication versionstring

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KOrder {
  create(cartId: string, options: KScript.Commerce.Models.CreateOrderOptions): Kooboo.Sites.Commerce.ViewModels.OrderDetail;
  create(init: KScript.Commerce.Models.CreateOrderInit): Kooboo.Sites.Commerce.ViewModels.OrderDetail;
  get(orderId: string): Kooboo.Sites.Commerce.ViewModels.OrderDetail;
  pay(orderId: string, method: string): void;
  delivery(orderId: string, shippingCarrier: string, trackingNumber: string): void;
  delivery(orderId: string, lineIds: string[]): void;
  updateShippingInfo(orderId: string, orderLineId: string, options: Kooboo.Sites.Commerce.ViewModels.DeliveryOptions): void;
  cancel(orderId: string, reason: string): void;
  reopen(orderId: string): void;
  updateAddress(orderId: string, address: Kooboo.Sites.Commerce.Entities.Address): void;
  list(query?: KScript.Commerce.Models.OrderQuery): Kooboo.Sites.Commerce.ViewModels.OrderDetail[];
  delete(id: string): void;
  updateExtensionField(id: string, property: string, value: string): void;
}

interface OrderQuery extends CustomerOrderQuery {
  customerId: string;
  paid?: boolean;
  delivered?: boolean;
  canceled?: boolean;
  startDate?: Date;
  endDate?: Date;
  pageIndex: number;
  pageSize: number;
}

interface OrderResult {
  list: Kooboo.Sites.Commerce.ViewModels.OrderDetail[];
  count: number;
  pageIndex: number;
  pageSize: number;
}

interface CreateOrderOptions {
  scheduledDeliveryTime?: Date;
  note: string;
  address: Kooboo.Sites.Commerce.Entities.Address;
  extensionFields: KScript.KeyValue[];
  currency: string;
}

interface CreateOrderInit {
  note: string;
  source: string;
  address: Kooboo.Sites.Commerce.Entities.Address;
  shippingAmount: number;
  customerId: string;
  email: string;
  firstName: string;
  lastName: string;
  phone: string;
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
  extensionFields: KScript.KeyValue[];
  lines: CreateOrderLineInit[];
  currency: string;
}

interface CreateOrderLineInit {
  image: string;
  price: number;
  quantity: number;
  title: string;
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
}

interface DeliveryOptions {
  shippingCarrier: string;
  trackingNumber: string;
  digitalItems: Kooboo.Sites.Commerce.Entities.DigitalOrderItem[];
}

interface OrderDetail {
  id: string;
  customer: CustomerInfo;
  pointsDeductionAmount: number;
  earnPoints: number;
  redeemPoints: number;
  totalAmount: number;
  taxAmount: number;
  originalAmount: number;
  shippingAmount: number;
  insuranceAmount?: number;
  subtotalAmount: number;
  originalSubtotalAmount: number;
  totalQuantity: number;
  currency: string;
  paid: boolean;
  paidAt?: string; // string | null at runtime via ToKscriptModel
  paymentMethod: string;
  delivered: boolean;
  partialDelivered: boolean;
  trackingNumber: string | null; // unassigned (null) at runtime; read from lines[].trackingNumber
  shippingCarrier: string | null; // unassigned (null) at runtime; read from lines[].shippingCarrier
  shippingAt?: string;
  scheduledDeliveryTime?: string;
  canceled: boolean;
  cancelReason: string;
  cancelAt?: string;
  createdAt: string;
  updatedAt: string;
  shippingAddress: Kooboo.Sites.Commerce.Entities.Address;
  note: string;
  lines: Kooboo.Sites.Commerce.Entities.OrderLine[];
  ip: string;
  country: string;
  source: string;
  clientInfo: Kooboo.Lib.Utilities.UAParser.ClientInfo;
  extensionButton: Kooboo.Sites.Commerce.Entities.ExtensionButton;
  discountAllocations: Kooboo.Sites.Commerce.Calculate.DiscountAllocation[];
  shippingAllocations: Kooboo.Sites.Commerce.Calculate.ShippingAllocation[];
  extensionFields: KScript.KeyValue[];
}