k.commerce.customer
Customer management.
| Execution Context | Prerequisites | Typical 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
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 / Property | Description | Returns |
|---|---|---|
currentId | Read-only property returning the logged-in customer ID in the current context, or empty/null when anonymous | string | null |
create(model) | Create a customer (throws if a provided email or phone already exists) | Customer |
get(id) | Fetch customer details by customer ID | Customer | null |
getByEmail(email) | Fetch customer details by email address | Customer | null |
getByPhone(phone) | Fetch customer details by phone number | Customer | null |
login(email, password) | Authenticate customer with email/password and set session | Customer | null |
logout() | Log out the currently authenticated customer session | void |
setPassword(id, password) | Set or reset a customer password | void |
setOAuth(id, openId, type) | Bind a third-party OAuth identifier to a customer | void |
getByOAuth(openId, type) | Look up a customer by OAuth identifier and provider type | Customer | null |
oAuthList(id) | List OAuth bindings for a customer (runtime returns PascalCase keys) | CustomerOAuthModel[] |
orders(customerId, query?) | List paginated orders placed by a customer | OrderResult | null |
updateInfo(id, info) | Update customer email, name, phone, and tags | void |
updateAddresses(id, addresses) | Replace the customer saved address list | void |
addDiscount(id, discountId) | Assign a discount to the customer | void |
getDiscounts(id, options?) | Get customer discounts, optionally evaluating canUse against a cartId | CustomerDiscountItem[] |
remove(id) | Delete a customer record | void |
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
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | CreateCustomer | Yes | Customer payload |
model.email | string | No | Email (optional; throws if non-empty and already used by another customer) |
model.firstName | string | No | First name |
model.lastName | string | No | Last name |
model.password | string | No | Password |
model.phone | string | No | Phone number (optional; throws if non-empty and already used by another customer) |
Returns: Customer.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
Returns: Customer | null.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
email | string | Yes | Customer email |
Returns: Customer | null.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
phone | string | Yes | Phone number |
Returns: Customer | null.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
email | string | Yes | Customer email |
password | string | Yes | Password |
Returns: Customer | null. Returns the Customer object when login succeeds, or null when login fails.
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.currentIdimmediately afterlogout()within the same request still returns the old ID; the logged-out state takes effect on subsequent requests. - Deleting the
kb_commercecookie also clears the persisted shopping cart binding (k.commerce.cart.currentIdbecomesnullon subsequent requests).
Returns: void.
k.api.post(() => {
k.commerce.customer.logout()
return { loggedOut: true }
})setPassword()
Set or update a customer password.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
password | string | Yes | New password |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
openId | string | Yes | Third-party platform openId |
type | string | Yes | Third-party platform type (such as Apple) |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
openId | string | Yes | Third-party platform openId |
type | string | Yes | Third-party platform type |
Returns: Customer | null.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
Returns: CustomerOAuthModel[].
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
customerId | string | Yes | Customer ID |
query | CustomerOrderQuery | No | Query filters |
query.pageIndex | number | No | Page number, default 1 |
query.pageSize | number | No | Items per page, default 30 |
query.paid | boolean | No | Whether paid |
query.delivered | boolean | No | Whether delivered |
query.canceled | boolean | No | Whether canceled |
query.startDate | Date | No | Start date |
query.endDate | Date | No | End date |
Returns: OrderResult | null. Contains list (OrderDetail[]), count, pageIndex, and pageSize, or null when customerId does not exist.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
info | UpdateCustomer | Yes | Fields to update |
info.email | string | No | |
info.firstName | string | No | First name |
info.lastName | string | No | Last name |
info.phone | string | No | Phone number |
info.tags | string[] | No | Tags |
Returns: void.
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, andcity(or ISO country code for tax lookup) so saved addresses matchk.commerce.address.addressDetail()and checkout tax calculation.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
addresses | AddressModel[] | Yes | Address list |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
discountId | string | Yes | Discount ID |
Returns: void.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
options | GetDiscountOptions | No | Optional filter parameters |
options.cartId | string | No | Cart ID used to evaluate whether each discount canUse applies |
Returns: CustomerDiscountItem[].
k.api.get(() => {
const discounts = k.commerce.customer.getDiscounts('customer-id', {
cartId: 'cart-id'
})
return { count: discounts.length, items: discounts }
})remove()
Delete a customer.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Customer ID |
Returns: void.
k.api.post(() => {
const customerId = 'customer-id'
k.commerce.customer.remove(customerId)
return { removed: k.commerce.customer.get(customerId) === null }
})Structures
Customer attribute
| Property | Description | Type |
|---|---|---|
id | Customer ID | string |
email | Customer email | string |
firstName | First name | string |
lastName | Last name | string |
phone | Customer phone number | string |
password | Password hash (strip before returning customer objects from public APIs) | string |
lastPlaceOrderDate | Last order time | string | null |
addresses | Address list | AddressModel[] |
tags | Tag list | string[] |
createdAt | Creation time | string |
updatedAt | Update time | string |
AddressModel Property
| Property | Description | Type |
|---|---|---|
id | Address ID | string |
isDefault | Whether default address | boolean |
country | Country | string |
province | Province / state | string |
city | City | string |
address1 | Address line 1 | string |
address2 | Address line 2 | string |
firstName | Recipient first name | string |
lastName | Recipient last name | string |
phone | Phone number | string |
zip | Postal code | string |
CustomerOAuthModel Properties
Runtime Note: At runtime
oAuthList()returns PascalCase keys (CustomerId,OpenId,Type,CreatedAt), while IDE IntelliSense declares camelCase (customerId,openId,type,createdAt).
| Property | Description | Type |
|---|---|---|
CustomerId | Customer ID | string |
OpenId | Third-party platform openId | string |
Type | Third-party platform type | string |
CreatedAt | Creation time | string |
OrderResult Properties
| Property | Description | Type |
|---|---|---|
list | Order detail list | OrderDetail[] |
count | Total count | number |
pageIndex | Current page index | number |
pageSize | Page size | number |
CustomerDiscountItem Properties
Inherits Discount properties plus customer availability flags:
| Property | Description | Type |
|---|---|---|
id | Discount ID | string |
title | Discount title | string |
code | Coupon code | string |
type | Discount type | string |
method | Discount method | string |
value | Discount value | number |
isPercent | Whether the value is a percentage | boolean |
canUse | Whether the customer can use this discount (evaluated with cartId when provided) | boolean |
used | Whether the customer has already used this discount | boolean |
startDate | Start date | string |
endDate | End date | string |
condition | Discount condition definition | Condition |
codeUsageLimit | Coupon code usage limit | number | null |
priority | Discount priority | number |
isExclusion | Whether exclusive with other discounts | boolean |
createdAt | Creation time | string |
updatedAt | Update time | string |
TypeScript Definitions
Show full TypeScript definitions
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;
}Related Docs
- k.commerce - E-commerce module overview
- order - Order management
- cart - Shopping cart
- loyalty - Loyalty & points