Skip to content

k.commerce.customer ​

Customer management.

Execution ContextPrerequisitesTypical Use
KScript API (k.api.get / k.api.post), server-side <script env="server">E-commerce module enabled; configure discounts first before calling addDiscount()Customer registration/auth (login/logout), third-party OAuth binding, address book updates, order history, and coupon assignment

k.commerce.customer manages customer accounts across registration, session authentication, password management, OAuth linking, saved shipping addresses, order history pagination, and customer-assigned discounts.

Quick Start ​

js
k.api.post(() => {
    const email = 'buyer@example.com'
    let customer = k.commerce.customer.getByEmail(email)
    if (!customer) {
        customer = k.commerce.customer.create({
            email,
            firstName: 'Ada',
            lastName: 'Lovelace',
            password: 'strong-password-123'
        })
    }
    const loggedIn = k.commerce.customer.login(email, 'strong-password-123')
    return { customerId: loggedIn ? loggedIn.id : null, currentId: k.commerce.customer.currentId }
})

Quick Reference ​

Method / PropertyDescriptionReturns
currentIdRead-only property returning the logged-in customer ID in the current context, or empty/null when anonymousstring | null
create(model)Create a customer (throws if a provided email or phone already exists)Customer
get(id)Fetch customer details by customer IDCustomer | null
getByEmail(email)Fetch customer details by email addressCustomer | null
getByPhone(phone)Fetch customer details by phone numberCustomer | null
login(email, password)Authenticate customer with email/password and set sessionCustomer | null
logout()Log out the currently authenticated customer sessionvoid
setPassword(id, password)Set or reset a customer passwordvoid
setOAuth(id, openId, type)Bind a third-party OAuth identifier to a customervoid
getByOAuth(openId, type)Look up a customer by OAuth identifier and provider typeCustomer | null
oAuthList(id)List OAuth bindings for a customer (runtime returns PascalCase keys)CustomerOAuthModel[]
orders(customerId, query?)List paginated orders placed by a customerOrderResult | null
updateInfo(id, info)Update customer email, name, phone, and tagsvoid
updateAddresses(id, addresses)Replace the customer saved address listvoid
addDiscount(id, discountId)Assign a discount to the customervoid
getDiscounts(id, options?)Get customer discounts, optionally evaluating canUse against a cartIdCustomerDiscountItem[]
remove(id)Delete a customer recordvoid

currentId ​

Read-only property that returns the ID of the currently logged-in customer in the request context, or null / empty string when no customer is signed in. No parameters.

Type: string | null

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

create() ​

Create a customer.

Uniqueness Validation

Neither email nor phone is required, but providing a non-empty email or phone that already belongs to an existing customer throws an exception.

ParameterTypeRequiredDescription
modelCreateCustomerYesCustomer payload
model.emailstringNoEmail (optional; throws if non-empty and already used by another customer)
model.firstNamestringNoFirst name
model.lastNamestringNoLast name
model.passwordstringNoPassword
model.phonestringNoPhone number (optional; throws if non-empty and already used by another customer)

Returns: Customer.

js
k.api.post(() => {
    const customer = k.commerce.customer.create({
        email: 'test@example.com',
        firstName: 'Test',
        lastName: 'User',
        password: '123456',
        phone: '15291101010'
    })
    return { id: customer.id, email: customer.email }
})

get() ​

Get a customer by customer ID.

ParameterTypeRequiredDescription
idstringYesCustomer ID

Returns: Customer | null.

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

getByEmail() ​

Get a customer by email address.

ParameterTypeRequiredDescription
emailstringYesCustomer email

Returns: Customer | null.

js
k.api.get(() => {
    const customer = k.commerce.customer.getByEmail('test@example.com')
    return { id: customer.id, email: customer.email }
})

getByPhone() ​

Get a customer by mobile phone number.

ParameterTypeRequiredDescription
phonestringYesPhone number

Returns: Customer | null.

js
k.api.get(() => {
    const customer = k.commerce.customer.getByPhone('15291101010')
    return { id: customer.id, phone: customer.phone }
})

login() ​

Authenticate a customer with email and password.

ParameterTypeRequiredDescription
emailstringYesCustomer email
passwordstringYesPassword

Returns: Customer | null. Returns the Customer object when login succeeds, or null when login fails.

js
k.api.post(() => {
    const result = k.commerce.customer.login('test@example.com', '123456')
    if (!result) {
        return { error: 'email or password is incorrect' }
    }
    return { id: result.id, email: result.email }
})

logout() ​

Log out the current customer session. No parameters.

Session Timing & Side Effects

logout() deletes the kb_commerce cookie on the response without clearing the in-memory customerId (or cartId) fields for the current request:

  • Checking k.commerce.customer.currentId immediately after logout() within the same request still returns the old ID; the logged-out state takes effect on subsequent requests.
  • Deleting the kb_commerce cookie also clears the persisted shopping cart binding (k.commerce.cart.currentId becomes null on subsequent requests).

Returns: void.

js
k.api.post(() => {
    k.commerce.customer.logout()
    return { loggedOut: true }
})

setPassword() ​

Set or update a customer password.

ParameterTypeRequiredDescription
idstringYesCustomer ID
passwordstringYesNew password

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    k.commerce.customer.setPassword(customerId, 'new-password')
    const customer = k.commerce.customer.get(customerId)
    return { id: customer.id, updatedAt: customer.updatedAt }
})

setOAuth() ​

Bind third-party OAuth information to a customer.

ParameterTypeRequiredDescription
idstringYesCustomer ID
openIdstringYesThird-party platform openId
typestringYesThird-party platform type (such as Apple)

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    k.commerce.customer.setOAuth(customerId, 'open-id-123', 'Apple')
    return { items: k.commerce.customer.oAuthList(customerId) }
})

getByOAuth() ​

Get a customer by OAuth credentials.

ParameterTypeRequiredDescription
openIdstringYesThird-party platform openId
typestringYesThird-party platform type

Returns: Customer | null.

js
k.api.get(() => {
    const customer = k.commerce.customer.getByOAuth('open-id-123', 'Apple')
    return { id: customer.id, email: customer.email }
})

oAuthList() ​

Get the list of OAuth bindings attached to a customer.

ParameterTypeRequiredDescription
idstringYesCustomer ID

Returns: CustomerOAuthModel[].

js
k.api.get(() => {
    const list = k.commerce.customer.oAuthList('customer-id')
    return { count: list.length, items: list }
})

orders() ​

Get the paginated order list for a customer.

ParameterTypeRequiredDescription
customerIdstringYesCustomer ID
queryCustomerOrderQueryNoQuery filters
query.pageIndexnumberNoPage number, default 1
query.pageSizenumberNoItems per page, default 30
query.paidbooleanNoWhether paid
query.deliveredbooleanNoWhether delivered
query.canceledbooleanNoWhether canceled
query.startDateDateNoStart date
query.endDateDateNoEnd date

Returns: OrderResult | null. Contains list (OrderDetail[]), count, pageIndex, and pageSize, or null when customerId does not exist.

js
k.api.get(() => {
    const orders = k.commerce.customer.orders('customer-id', {
        pageIndex: 1,
        pageSize: 10,
        paid: true,
        delivered: true,
        canceled: false
    })
    if (!orders) {
        return { count: 0, orders: [] }
    }
    return { count: orders.count, orders: orders.list }
})

updateInfo() ​

Update customer profile information.

Uniqueness Validation

Providing a non-empty info.email or info.phone that is already used by another customer throws an exception.

ParameterTypeRequiredDescription
idstringYesCustomer ID
infoUpdateCustomerYesFields to update
info.emailstringNoEmail
info.firstNamestringNoFirst name
info.lastNamestringNoLast name
info.phonestringNoPhone number
info.tagsstring[]NoTags

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    k.commerce.customer.updateInfo(customerId, {
        firstName: 'Updated',
        lastName: 'Name',
        phone: '13900139000',
        tags: ['vip', 'active']
    })
    const updated = k.commerce.customer.get(customerId)
    return { id: updated.id, firstName: updated.firstName, tags: updated.tags }
})

updateAddresses() ​

Update the customer address list.

Note

  • This operation overwrites the entire address list: the array passed in becomes the customer's final saved addresses.
  • Use English geographic names for country, province, and city (or ISO country code for tax lookup) so saved addresses match k.commerce.address.addressDetail() and checkout tax calculation.
ParameterTypeRequiredDescription
idstringYesCustomer ID
addressesAddressModel[]YesAddress list

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    k.commerce.customer.updateAddresses(customerId, [{
        country: 'China',
        province: 'Fujian',
        city: 'Xiamen',
        address1: 'address1',
        address2: 'address2',
        zip: '361000',
        firstName: 'firstName',
        lastName: 'lastName',
        phone: '13800138000',
        isDefault: true
    }])
    const updated = k.commerce.customer.get(customerId)
    return { id: updated.id, addresses: updated.addresses }
})

addDiscount() ​

Assign a discount to a customer.

ParameterTypeRequiredDescription
idstringYesCustomer ID
discountIdstringYesDiscount ID

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    const discount = k.commerce.discount.list()[0]
    k.commerce.customer.addDiscount(customerId, discount.id)
    return { discounts: k.commerce.customer.getDiscounts(customerId) }
})

getDiscounts() ​

Get discounts assigned to a customer, optionally evaluating applicability against a cart.

ParameterTypeRequiredDescription
idstringYesCustomer ID
optionsGetDiscountOptionsNoOptional filter parameters
options.cartIdstringNoCart ID used to evaluate whether each discount canUse applies

Returns: CustomerDiscountItem[].

js
k.api.get(() => {
    const discounts = k.commerce.customer.getDiscounts('customer-id', {
        cartId: 'cart-id'
    })
    return { count: discounts.length, items: discounts }
})

remove() ​

Delete a customer.

ParameterTypeRequiredDescription
idstringYesCustomer ID

Returns: void.

js
k.api.post(() => {
    const customerId = 'customer-id'
    k.commerce.customer.remove(customerId)
    return { removed: k.commerce.customer.get(customerId) === null }
})

Structures ​

Customer attribute ​

PropertyDescriptionType
idCustomer IDstring
emailCustomer emailstring
firstNameFirst namestring
lastNameLast namestring
phoneCustomer phone numberstring
passwordPassword hash (strip before returning customer objects from public APIs)string
lastPlaceOrderDateLast order timestring | null
addressesAddress listAddressModel[]
tagsTag liststring[]
createdAtCreation timestring
updatedAtUpdate timestring

AddressModel 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

CustomerOAuthModel Properties ​

Runtime Note: At runtime oAuthList() returns PascalCase keys (CustomerId, OpenId, Type, CreatedAt), while IDE IntelliSense declares camelCase (customerId, openId, type, createdAt).

PropertyDescriptionType
CustomerIdCustomer IDstring
OpenIdThird-party platform openIdstring
TypeThird-party platform typestring
CreatedAtCreation timestring

OrderResult Properties ​

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

CustomerDiscountItem Properties ​

Inherits Discount properties plus customer availability flags:

PropertyDescriptionType
idDiscount IDstring
titleDiscount titlestring
codeCoupon codestring
typeDiscount typestring
methodDiscount methodstring
valueDiscount valuenumber
isPercentWhether the value is a percentageboolean
canUseWhether the customer can use this discount (evaluated with cartId when provided)boolean
usedWhether the customer has already used this discountboolean
startDateStart datestring
endDateEnd datestring
conditionDiscount condition definitionCondition
codeUsageLimitCoupon code usage limitnumber | null
priorityDiscount prioritynumber
isExclusionWhether exclusive with other discountsboolean
createdAtCreation timestring
updatedAtUpdate timestring

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KCustomer {
  currentId: string;
  get(id: string): Kooboo.Sites.Commerce.Entities.Customer;
  getByEmail(email: string): Kooboo.Sites.Commerce.Entities.Customer;
  getByPhone(phone: string): Kooboo.Sites.Commerce.Entities.Customer;
  getByOAuth(openId: string, type: string): Kooboo.Sites.Commerce.Entities.Customer;
  setOAuth(id: string, openId: string, type: string): void;
  oAuthList(id: string): Kooboo.Sites.Commerce.DataStorage.CustomerOAuthModel[];
  create(model: KScript.Commerce.Models.CreateCustomer): Kooboo.Sites.Commerce.Entities.Customer;
  setPassword(id: string, password: string): void;
  login(email: string, password: string): Kooboo.Sites.Commerce.Entities.Customer;
  logout(): void;
  remove(id: string): void;
  orders(customerId: string, query?: KScript.Commerce.Models.CustomerOrderQuery): KScript.Commerce.Models.OrderResult;
  updateAddresses(id: string, addresses: Kooboo.Sites.Commerce.Entities.Address[]): void;
  updateInfo(id: string, info: KScript.Commerce.Models.UpdateCustomer): void;
  addDiscount(id: string, discountId: string): void;
  getDiscounts(id: string, options?: GetDiscountOptions): CustomerDiscountItem[];
}

interface CreateCustomer {
  email: string;
  firstName: string;
  lastName: string;
  phone: string;
  password: string;
}

interface UpdateCustomer {
  email: string;
  phone: string;
  firstName: string;
  lastName: string;
  tags: string[];
}

interface CustomerOrderQuery extends Kooboo.Sites.Commerce.ViewModels.PagingQuery {
  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 GetDiscountOptions {
  cartId: string;
}

interface Customer extends Kooboo.Sites.Commerce.Entity {
  email: string;
  firstName: string;
  lastName: string;
  phone: string;
  password: string;
  lastPlaceOrderDate?: Date;
  addresses: Address[];
  tags: string[];
  id: string;
  createdAt: Date;
  updatedAt: Date;
  clone(): any;
  getGuid(): any;
}

interface CustomerOAuthModel {
  customerId: string;
  openId: string;
  type: string;
  createdAt: Date;
}

interface CustomerDiscountItem extends Kooboo.Sites.Commerce.Entities.Discount {
  canUse: boolean;
  used: boolean;
  title: string;
  startDate: Date;
  endDate: Date;
  condition: Kooboo.Sites.Commerce.Condition.Define;
  method: Kooboo.Sites.Commerce.DiscountMethod;
  code: string;
  codeUsageLimit?: number;
  type: Kooboo.Sites.Commerce.DiscountType;
  value: number;
  isPercent: boolean;
  priority: number;
  isExclusion: boolean;
  id: string;
  createdAt: Date;
  updatedAt: Date;
  clone(): any;
  getGuid(): any;
}