k.payment
Third-party payment integration.
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
KScript API (k.api.get / k.api.post), server-side <script env="server"> | Enable and configure the target gateway in CMS Service Integrations -> Payment | Create 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
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 / Property | Description | Returns |
|---|---|---|
getRequest(requestId) | Fetch a PaymentRequest record by requestId | PaymentRequest |
<provider>.charge(params) | Initiate a payment request and get requestId + nextAction | ChargeResponse |
<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 / supportedCurrency | Inspect gateway settings, current request context, and supported currencies | Settings / 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 goal | Recommended API | nextAction form |
|---|---|---|
| WeChat scan code / PC QR code | k.payment.wechat | renderHtml |
| WeChat mobile browser H5 | k.payment.weChatH5 | redirectUrl -> see WeChat H5 Flow |
| WeChat built-in browser | k.payment.wechatJsApi | responseData (requires openId) |
| Alipay web checkout | k.payment.alipayForm | renderHtml |
| Alipay H5 | k.payment.alipayH5 | renderHtml |
| PayPal Checkout | k.payment.paypalCheckout | redirect / renderHtml |
| Stripe hosted page | k.payment.stripeCheckout | redirect / renderHtml |
| Stripe on-site card payment | k.payment.stripe | paid or 3DS redirectUrl |
Payment Method Pages
| Doc | API |
|---|---|
| Alipay | k.payment.alipayApp, k.payment.alipayForm, k.payment.alipayH5 |
| WeChat Pay | k.payment.wechat, k.payment.wechatApp, k.payment.weChatH5, k.payment.wechatJsApi |
| PayPal | k.payment.paypalCheckout, k.payment.paypalForm |
| Stripe | k.payment.stripeCheckout, k.payment.stripe |
| Square | k.payment.square |
| Pay.NL | k.payment.paynlCheckout |
| TwoCheckout | k.payment.twoCheckout |
| MoneyBoxs | k.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.
| Parameter | Type | Required | Description |
|---|---|---|---|
requestId | string | Yes | Payment request ID returned by charge() |
Returns: PaymentRequest
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
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.
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
| Property | Type | Description |
|---|---|---|
name | string | Internal payment method name |
displayName | string | Display name |
icon | string | Icon URL or inline content |
iconType | string | Icon type |
supportedCurrency | string[] | Supported currencies |
context | object | Current payment context |
setting | object | Site configuration for this payment method |
ChargeResponse
| Property | Type | Description |
|---|---|---|
paid | boolean | Whether payment has succeeded |
requestId | any | Payment request ID used for subsequent status queries |
paymentMethodReferenceId | string | Third-party payment reference ID |
nextAction | NextAction | Next action to execute |
NextAction
| Property | Type | Description |
|---|---|---|
type | string | Action type, such as redirect, render HTML, QR code, etc. |
redirectUrl | string | Target URL when redirection is required |
renderHtml | string | HTML markup to render to the browser |
responseData | string | Raw provider payload, commonly used for QR codes or client SDKs |
PaymentStatusResponse
| Property | Type | Description |
|---|---|---|
hasResult | boolean | Whether query results are available |
paid | boolean | Whether the payment succeeded |
failed | boolean | Whether the payment failed |
status | PaymentStatus | Payment status |
payload | Record<string, any> | Raw payload returned by the provider |
message | string | Status message |
PaymentStatus values: NotAvailable, Authorized, Pending, Paid, Cancelled, Rejected.
PaymentRequest
| Property | Type | Description |
|---|---|---|
id | any | Payment request ID |
description | string | Payment description |
totalAmount | number | Amount |
currency | string | Currency |
country | string | Country code |
orderId | any | Associated Commerce order GUID |
order | string | Associated Commerce order ID |
userIp | string | Client IP address initiating the payment |
paymentMethod | string | Payment method |
paid | boolean | Whether paid |
failed | boolean | Whether failed |
code | string | Payment request code |
callbackCodeName | string | Callback code name executed after payment completes |
referenceId | string | Third-party reference ID |
referenceIdHash | any | Hash of the third-party reference ID |
returnUrl | string | Payment completion redirect URL |
cancelUrl | string | Cancel payment redirect URL |
additional | Record<string, any> | Payment method additional data |
card | Card | Card information |
online | boolean | Whether this is an online payment request |
creationDate | Date | Creation time |
lastModified | Date | Last modified time |
name | string | Payment name |
TypeScript Definitions
Show full TypeScript definitions
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;
}