Checkout Functions
Extend Cartly checkout with rule-based functions and WASM modules. Control discounts, shipping rates, payment methods, and cart validation without touching core code.
Overview
Checkout Functions (v1.7) provide a rule-based extensibility engine that runs during the checkout flow. Every active function is executed in a 50 ms pipeline before the checkout response is returned to the storefront.
There are four function types:
| Type | What it controls |
|---|---|
discount_calculate | Apply percentage or fixed discounts to orders or line items |
shipping_filter_and_sort | Hide, rename, or reorder shipping rates |
payment_customization | Hide or reorder payment methods |
checkout_validate | Block checkout with a custom error message |
Each function runs in one of two modes: rule (JSON AST evaluated server-side) or wasm (WebAssembly binary sandboxed via wazero). Rule mode covers the majority of use cases without any code. WASM mode is for advanced logic that cannot be expressed as conditions and actions.
Quick Start
Create a function via the Admin UI at Marketing → Checkout Functions, or via the API:
const ADMIN_JWT = 'your_admin_jwt';
// Create a Discount Calculate function
const { function: fn } = await fetch('https://cartly.pro/admin/functions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${ADMIN_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'High-Value Order Discount',
function_type: 'discount_calculate',
mode: 'rule',
enabled: true,
rule_config: {
conditions: {
all: [
{ field: 'cart.subtotal_cents', operator: 'gt', value: 10000 },
],
},
actions: [
{ type: 'percentage_discount', value: 10, target: 'order' },
],
},
}),
}).then(r => r.json());
console.log(fn.id); // uuidOnce created, use the Test panel in the admin to simulate a cart and inspect the returned operations — without affecting live orders:
// Simulate a cart and test which operations the function returns
const { operations } = await fetch(`https://cartly.pro/admin/functions/${fn.id}/test`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${ADMIN_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
cart: {
subtotal_cents: 15000, // $150.00
item_count: 3,
items: [
{ product_id: 'uuid', variant_id: 'uuid', quantity: 2, price_cents: 5000 },
{ product_id: 'uuid', variant_id: 'uuid', quantity: 1, price_cents: 5000 },
],
customer: { tags: ['vip'], email: 'buyer@example.com' },
},
}),
}).then(r => r.json());
// operations: [{ type: 'percentage_discount', value: 10, target: 'order' }]Rule Engine
Rule-mode functions use a JSON AST to express conditions and actions. The evaluator supports 12+ operators and both all (AND) and any (OR) quantifiers that can be nested arbitrarily.
Available condition fields
| Field | Type | Description |
|---|---|---|
cart.subtotal_cents | int | Cart subtotal in cents before discounts |
cart.item_count | int | Total number of line items |
cart.total_weight_grams | int | Total weight of all items in grams |
cart.items[*].product_id | string | Product UUID — use with in operator |
cart.items[*].variant_tags | []string | Tags on any variant in the cart |
customer.tags | []string | Tags assigned to the customer |
customer.email | string | Customer email address |
shipping.country_code | string | Shipping destination country (ISO 3166-1 alpha-2) |
now.hour | int | Current UTC hour (0–23) |
now.day_of_week | int | Current UTC day (0=Sunday … 6=Saturday) |
Operators
eq, neq, gt, gte, lt,lte, contains, not_contains, in,not_in, starts_with, ends_with
Aggregates
Use SUM, COUNT, MIN, MAX, and AVG over array fields. Example: {"field": "SUM(cart.items[*].price_cents)", "operator": "gt", "value": 5000}
Full example
// Rule config structure (JSON AST)
{
"conditions": {
// Match ALL conditions:
"all": [
{ "field": "cart.subtotal_cents", "operator": "gt", "value": 10000 },
{ "field": "customer.tags", "operator": "in", "value": ["vip", "wholesale"] }
],
// OR: match ANY condition:
"any": [
{ "field": "cart.item_count", "operator": "gte", "value": 5 },
{ "field": "now.hour", "operator": "lt", "value": 9 }
]
},
"actions": [
{ "type": "percentage_discount", "value": 15, "target": "order" },
{ "type": "fixed_discount", "value": 500, "target": "line_item" },
{ "type": "hide_shipping_rate", "handle": "cash_on_delivery" },
{ "type": "rename_shipping_rate","handle": "standard", "new_title": "Free Shipping" },
{ "type": "hide_payment_method", "method": "cod" },
{ "type": "add_error", "message": "Minimum order is $50" }
]
}WASM Functions
When rule mode is insufficient, upload a WebAssembly binary compiled from any language (Go, Rust, AssemblyScript, etc.). The wazero sandbox executes it with a 50 ms timeout, no network access, and no filesystem access.
// 1. Create a function in WASM mode
const { function: fn } = await fetch('https://cartly.pro/admin/functions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${ADMIN_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Custom Tiered Discount',
function_type: 'discount_calculate',
mode: 'wasm',
enabled: false, // enable after uploading WASM binary
}),
}).then(r => r.json());
// 2. Upload your WASM binary (max 1 MB)
const wasmBinary = await fs.readFile('./function.wasm');
const formData = new FormData();
formData.append('file', new Blob([wasmBinary], { type: 'application/wasm' }), 'function.wasm');
await fetch(`https://cartly.pro/admin/functions/${fn.id}/upload-wasm`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${ADMIN_JWT}` },
body: formData,
});
// 3. Enable the function
await fetch(`https://cartly.pro/admin/functions/${fn.id}`, {
method: 'PUT',
headers: { 'Authorization': `Bearer ${ADMIN_JWT}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: true }),
});stdin / stdout protocol
// WASM functions communicate via stdin/stdout JSON.
// Cartly sends this input payload on stdin:
{
"function_type": "discount_calculate",
"cart": {
"subtotal_cents": 15000,
"item_count": 3,
"items": [
{ "product_id": "uuid", "variant_id": "uuid", "quantity": 2, "price_cents": 5000 }
],
"customer": { "tags": ["vip"], "email": "buyer@example.com" }
}
}
// Your WASM function reads stdin, computes, and writes to stdout:
{
"operations": [
{ "type": "percentage_discount", "value": 10, "target": "order" }
]
}
// Constraints:
// - Execution timeout: 50ms
// - Binary size limit: 1 MB
// - Magic bytes validated before execution (WASM: \0asm)
// - Sandboxed via wazero (no network, no filesystem)The executor validates magic bytes (\0asm) before execution and enforces a 1 MB binary size limit. WASM binaries are stored in S3 and cached in-memory with a 60 s TTL using sync.Map.
Checkout Branding
Merchants customise the checkout appearance at Online Store → Checkout Branding. Branding settings are injected into the checkout page as CSS custom properties.
// Get current checkout branding
const { branding } = await fetch('https://cartly.pro/admin/checkout/branding', {
headers: { 'Authorization': `Bearer ${ADMIN_JWT}` },
}).then(r => r.json());
// Update branding
await fetch('https://cartly.pro/admin/checkout/branding', {
method: 'PUT',
headers: {
'Authorization': `Bearer ${ADMIN_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
primary_color: '#6366f1', // indigo
background_color: '#ffffff',
text_color: '#111827',
error_color: '#ef4444',
button_style: 'pill', // pill | rounded | square
corner_radius: 8, // px
font_family: 'Inter',
font_size_base: 16, // px
custom_css: '.checkout-btn { letter-spacing: 0.05em; }',
}),
});
// Storefront reads branding at render time:
// GET /shops/:shopId/checkout/branding → injected as CSS variablesAvailable button_style values: pill, rounded, square.
Extension Points
Third-party apps can inject Remote UI components into 8 named extension slots in the checkout flow. Remote UI components are rendered server-side using a safe subset of 10 components.
| Extension Point | Location in checkout |
|---|---|
after_contact | Below the contact (email/phone) section |
after_shipping_address | Below the shipping address form |
after_shipping_methods | Below the shipping method selector |
after_payment_methods | Below the payment method selector |
before_order_summary | Above the order summary panel |
after_order_summary | Below the order summary panel |
before_footer | Above the checkout footer |
after_footer | Below the checkout footer |
Available Remote UI components
BlockStack, InlineStack, Text,Heading, TextField, Button,Banner, Divider, Image, Badge
// Register a checkout UI extension from your app
await fetch('https://cartly.pro/shops/:shopId/checkout/extensions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${APP_OAUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
extension_point: 'after_contact', // see table below
title: 'Loyalty Points Banner',
component_tree: {
type: 'BlockStack',
props: { spacing: 'base' },
children: [
{
type: 'Banner',
props: { status: 'info', title: 'You will earn 150 points on this order' },
},
],
},
}),
});Query active extensions for a slot viaGET /shops/:shopId/checkout/extensions?point=after_contact.
API Reference
| Method | Path | Description |
|---|---|---|
| GET | /admin/functions | List all checkout functions |
| POST | /admin/functions | Create a function |
| GET | /admin/functions/:id | Get function by ID |
| PUT | /admin/functions/:id | Update function (name, config, enabled) |
| DELETE | /admin/functions/:id | Delete a function |
| POST | /admin/functions/:id/test | Test function against a simulated cart |
| POST | /admin/functions/:id/upload-wasm | Upload WASM binary (multipart/form-data) |
| GET | /admin/checkout/branding | Get checkout branding |
| PUT | /admin/checkout/branding | Update checkout branding |
| GET | /shops/:shopId/checkout/branding | Storefront: get branding CSS variables |
| GET | /shops/:shopId/checkout/payment-methods | Storefront: get filtered payment methods |
| GET | /shops/:shopId/checkout/extensions | Storefront: get active extensions for a point |
| POST | /shops/:shopId/checkout/extensions | Register a checkout extension (OAuth app) |
All /admin/* endpoints require a valid admin JWT in theAuthorization: Bearer <token> header. App extension registration requires an OAuth token with thecheckout_extensions:write scope.