Skip to content

k.payment ​

Third-party payment integration.

Execution ContextPrerequisitesTypical Use
KScript API (k.api.get / k.api.post), server-side <script env="server">Enable and configure the target gateway in CMS Service Integrations -> PaymentCreate payment charges, render or redirect checkout flows, poll status, and update orders

charge() writes to the site's built-in PaymentRequest store; when a Commerce order ID is supplied, the built-in callback updates the order automatically after payment succeeds—avoid creating parallel payment tables by default.

Quick Start ​

js
k.api.get(() => {
    const requestId = k.request.queryString.get("requestId")
    if (!requestId) {
        return { error: "missing requestId" }
    }
    const request = k.payment.getRequest(requestId)
    return { id: request?.id, paid: request?.paid, failed: request?.failed }
})

Quick Reference ​

Method / PropertyDescriptionReturns
getRequest(requestId)Fetch a PaymentRequest record by requestIdPaymentRequest
<provider>.charge(params)Initiate a payment request and get requestId + nextActionChargeResponse
<provider>.checkStatus(requestId)Check payment status and trigger order/callback updates on paid/failed (paypalForm throws; moneyBoxs only reads local PaymentRequest.Paid with status always "NotAvailable" and failed always false)PaymentStatusResponse
<provider>.setting / context / supportedCurrencyInspect gateway settings, current request context, and supported currenciesSettings / string[]

Callback Handling

Payment callbacks are handled automatically by Kooboo's built-in /_api/paymentcallback/{PaymentMethod}_{Method} endpoint (such as AlipayForm_UpdateOrder, AlipayForm_Notify, or StripeCheckout_UpdateOrder), which invokes PaymentManager.CallBack(...) to update PaymentRequest, execute callbackCodeName, and mark any linked Commerce order as paid. <provider>.updateOrder(context) is an internal callback handler—do not invoke it directly from KScript to update orders. To confirm payment status in KScript, use <provider>.checkStatus(requestId) (which invokes PaymentManager.CallBack when paid or failed) or k.payment.getRequest(requestId).

Choosing a Payment Method ​

User goalRecommended APInextAction form
WeChat scan code / PC QR codek.payment.wechatrenderHtml
WeChat mobile browser H5k.payment.weChatH5redirectUrl -> see WeChat H5 Flow
WeChat built-in browserk.payment.wechatJsApiresponseData (requires openId)
Alipay web checkoutk.payment.alipayFormrenderHtml
Alipay H5k.payment.alipayH5renderHtml
PayPal Checkoutk.payment.paypalCheckoutredirect / renderHtml
Stripe hosted pagek.payment.stripeCheckoutredirect / renderHtml
Stripe on-site card paymentk.payment.stripepaid or 3DS redirectUrl

Payment Method Pages ​

DocAPI
Alipayk.payment.alipayApp, k.payment.alipayForm, k.payment.alipayH5
WeChat Payk.payment.wechat, k.payment.wechatApp, k.payment.weChatH5, k.payment.wechatJsApi
PayPalk.payment.paypalCheckout, k.payment.paypalForm
Stripek.payment.stripeCheckout, k.payment.stripe
Squarek.payment.square
Pay.NLk.payment.paynlCheckout
TwoCheckoutk.payment.twoCheckout
MoneyBoxsk.payment.moneyBoxs

Multi-Currency Note ​

k.commerce.currency.list() returns the site's configured currencies; each provider also exposes supportedCurrency. Use their intersection before initiating payment. WeChat Pay and Alipay typically support CNY only.

getRequest() ​

Get the payment request record based on requestId.

ParameterTypeRequiredDescription
requestIdstringYesPayment request ID returned by charge()

Returns: PaymentRequest

js
k.api.get(() => {
    const request = k.payment.getRequest("request-id")
    return {
        id: request.id,
        paid: request.paid,
        failed: request.failed,
        paymentMethod: request.paymentMethod,
        order: request.order
    }
})

General Process ​

Create Payment and Persist requestId ​

js
k.api.get(() => {
    const product = k.commerce.product.get("test-product")
    const cartId = k.commerce.cart.create()

    k.commerce.cart.addOrUpdateLine(cartId, product.variants[0].id, 1)
    k.commerce.cart.updateContact(cartId, "customer@example.com")

    const order = k.commerce.order.create(cartId, {
        address: {
            firstName: "Test",
            lastName: "User",
            country: "CN",
            province: "Fujian",
            city: "Xiamen",
            address1: "Street 1",
            address2: "",
            zip: "361000",
            phone: "13800138000",
            isDefault: true
        }
    })

    const charge = k.payment.alipayForm.charge({
        name: product.title,
        description: "Order payment",
        totalAmount: order.totalAmount,
        currency: "CNY",
        order: order.id,
        returnUrl: `/__paymentCallback?orderId=${order.id}`,
        callbackCodeName: "PaymentCallback"
    })

    k.logger.information("Payment.Info", `requestId: ${charge.requestId}, orderId: ${order.id}`)

    // Save the requestId so the payment callback can look it up by order
    k.DB.keyValue.set(`payment:${order.id}`, charge.requestId)

    k.response.setHeader("Content-Type", "text/html; charset=utf-8")
    k.response.write(charge.nextAction.renderHtml)
})

Payment Callback Example ​

returnUrl is the redirect URL after payment completes. Include the order ID in the URL, then retrieve the requestId saved during charge creation to query the real payment status.

js
k.api.get(() => {
    const orderId = k.request.queryString.get("orderId")
    if (!orderId) {
        k.response.json({ code: -1, msg: "order ID is not found" })
        return k.api.httpCode(400)
    }

    // Read back the requestId saved when the payment was created
    const saved = k.DB.keyValue.get(`payment:${orderId}`)
    const requestId = saved ? saved.toString() : null
    if (!requestId) {
        k.response.json({ code: -1, msg: "payment request ID is not found" })
        return k.api.httpCode(400)
    }

    const status = k.payment.alipayForm.checkStatus(requestId)
    if (status && status.paid) {
        k.response.redirect(`/order/${orderId}`)
        return
    }

    k.response.redirect("/payment-failed")
})

Common Properties & Data Structures ​

Common Provider Properties ​

PropertyTypeDescription
namestringInternal payment method name
displayNamestringDisplay name
iconstringIcon URL or inline content
iconTypestringIcon type
supportedCurrencystring[]Supported currencies
contextobjectCurrent payment context
settingobjectSite configuration for this payment method

ChargeResponse ​

PropertyTypeDescription
paidbooleanWhether payment has succeeded
requestIdanyPayment request ID used for subsequent status queries
paymentMethodReferenceIdstringThird-party payment reference ID
nextActionNextActionNext action to execute

NextAction ​

PropertyTypeDescription
typestringAction type, such as redirect, render HTML, QR code, etc.
redirectUrlstringTarget URL when redirection is required
renderHtmlstringHTML markup to render to the browser
responseDatastringRaw provider payload, commonly used for QR codes or client SDKs

PaymentStatusResponse ​

PropertyTypeDescription
hasResultbooleanWhether query results are available
paidbooleanWhether the payment succeeded
failedbooleanWhether the payment failed
statusPaymentStatusPayment status
payloadRecord<string, any>Raw payload returned by the provider
messagestringStatus message

PaymentStatus values: NotAvailable, Authorized, Pending, Paid, Cancelled, Rejected.

PaymentRequest ​

PropertyTypeDescription
idanyPayment request ID
descriptionstringPayment description
totalAmountnumberAmount
currencystringCurrency
countrystringCountry code
orderIdanyAssociated Commerce order GUID
orderstringAssociated Commerce order ID
userIpstringClient IP address initiating the payment
paymentMethodstringPayment method
paidbooleanWhether paid
failedbooleanWhether failed
codestringPayment request code
callbackCodeNamestringCallback code name executed after payment completes
referenceIdstringThird-party reference ID
referenceIdHashanyHash of the third-party reference ID
returnUrlstringPayment completion redirect URL
cancelUrlstringCancel payment redirect URL
additionalRecord<string, any>Payment method additional data
cardCardCard information
onlinebooleanWhether this is an online payment request
creationDateDateCreation time
lastModifiedDateLast modified time
namestringPayment name

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface kPay {
    stripeCheckout: StripeCheckout;
    stripe: StripePaymentIntent;
    paypalCheckout: PaypalCheckout;
    paypalForm: PaypalForm;
    wechat: WeChatNative;
    wechatApp: WeChatApp;
    wechatJsApi: WeChatJsApi;
    weChatH5: WeChatH5;
    alipayForm: AlipayForm;
    alipayApp: AlipayApp;
    alipayH5: AlipayH5;
    twoCheckout: TwoCheckout;
    paynlCheckout: PaynlCheckout;
    square: SquareCheckout;
    moneyBoxs: MoneyBoxs;
    getRequest(requestId: string): PaymentRequest;
}

interface ChargeParams {
    totalAmount: number;
    name: string;
    description: string;
    currency: string;
    order: string;
    callbackCodeName: string;
}

interface ChargeResponse {
    paid: boolean;
    requestId: any;
    paymentMethodReferenceId: string;
    nextAction: NextAction;
}

interface NextAction {
    type: string;
    responseData: string;
    renderHtml: string;
    redirectUrl: string;
}

type PaymentStatus = "NotAvailable" | "Authorized" | "Pending" | "Paid" | "Cancelled" | "Rejected";

interface PaymentStatusResponse {
    hasResult: boolean;
    paid: boolean;
    failed: boolean;
    status: PaymentStatus;
    payload: Record<string, any>;
    message: string;
}

interface PaymentCallback {
    id: any;
    requestId: any;
    responseMessage: string;
    rawData: string;
    requestUrl: string;
    postData: string;
    request: Record<string, any>;
    paid: boolean;
    cancelled: boolean;
    rejected: boolean;
    pending: boolean;
    status: PaymentStatus;
    creationDate: Date;
    lastModified: Date;
    name: string;
}

interface PaymentRequest {
    id: any;
    description: string;
    totalAmount: number;
    currency: string;
    country: string;
    orderId: any;
    order: string;
    userIp: string;
    paymentMethod: string;
    paid: boolean;
    failed: boolean;
    code: string;
    callbackCodeName: string;
    referenceId: string;
    referenceIdHash: any;
    returnUrl: string;
    cancelUrl: string;
    additional: any;
    card: any;
    online: boolean;
    version: number;
    constType: number;
    creationDate: Date;
    lastModified: Date;
    lastModifyTick: number;
    name: string;
}