Skip to content

k.payment

Third-party payment integration.

Overview

k.payment provides capabilities such as payment request creation, payment status query, and payment request record reading. Before using it, you need to enable and configure the corresponding payment method in the site CMS Service Integrations -> Payment.

charge() will be written to the site's built-in PaymentRequest; if Commerce order is passed in, the built-in callback will update the order after the payment is successful. Don’t default to building your own set of parallel pay tables.

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 hosting 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 currency; each provider also has supportedCurrency. The intersection of the two should be taken before initiating payment. WeChat/Alipay usually only CNY.

getRequest()

Get the payment request record based on requestId.

ts
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
    }
})

Parameters

ParameterTypeRequiredDescription
requestIdstringYesPayment request ID returned by charge()

Return: PaymentRequest

Common Properties

Each payment method object contains the following basic 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

General process

ts
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', phone: '13800138000' } as any
    })

    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}`)
    return k.response.renderView(charge.nextAction.renderHtml)
})

Payment callback example

returnUrl is the jump address after payment is completed. You can carry the order ID in the address, and then use the saved requestId to query the real payment status.

ts
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)
    }

    const requestId = getRequestIdByOrderId(orderId)
    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?.paid) {
        return k.response.redirect(`/order/${orderId}`)
    }

    return k.response.redirect('/payment-failed')
})

ChargeResponse

propertytypeillustrate
paidbooleanHas it been paid?
requestIdanyPayment request ID, used when querying the status later.
paymentMethodReferenceIdstringThird-party payment side reference ID
nextActionNextActionNext action

NextAction

propertytypeillustrate
typestringAction type, such as jump, render HTML, QR code, etc.
redirectUrlstringTarget address when redirection is required
renderHtmlstringThe HTML that needs to be rendered to the page
responseDatastringOriginal response data returned by a third party, often used in QR codes or client SDK parameters

PaymentStatusResponse

propertytypeillustrate
hasResultbooleanAre there any query results?
paidbooleanWhether the payment was successful
failedbooleanWhether payment failed
statusPaymentStatusPayment status
messagestringstatus message

PaymentStatus can be: NotAvailable, Authorized, Pending, Paid, Cancelled, Rejected.

PaymentRequest

propertytypeillustrate
IDanyPayment request ID
descriptionstringPayment description
totalAmountnumberAmount
currencystringcurrency
orderstringAssociated Commerce order ID
paymentMethodstringPayment method
paidbooleanHas it been paid?
failedbooleanwhether failed
callbackCodeNamestringThe name of the callback code executed after payment is completed
referenceIdstringThird Party Reference ID
returnUrlstringPayment completion jump address
cancelUrlstringCancel payment redirect address
additionalRecord<string, any>Payment method additional data
cardCardCard information
creationDateDatecreation time
lastModifiedDatelast modified time
namestringPayment name