Skip to content
Cartly Developers

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:

TypeWhat it controls
discount_calculateApply percentage or fixed discounts to orders or line items
shipping_filter_and_sortHide, rename, or reorder shipping rates
payment_customizationHide or reorder payment methods
checkout_validateBlock 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:

javascript
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); // uuid

Once created, use the Test panel in the admin to simulate a cart and inspect the returned operations — without affecting live orders:

javascript
// 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

FieldTypeDescription
cart.subtotal_centsintCart subtotal in cents before discounts
cart.item_countintTotal number of line items
cart.total_weight_gramsintTotal weight of all items in grams
cart.items[*].product_idstringProduct UUID — use with in operator
cart.items[*].variant_tags[]stringTags on any variant in the cart
customer.tags[]stringTags assigned to the customer
customer.emailstringCustomer email address
shipping.country_codestringShipping destination country (ISO 3166-1 alpha-2)
now.hourintCurrent UTC hour (0–23)
now.day_of_weekintCurrent 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

json
// 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.

javascript
// 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

json
// 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.

javascript
// 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 variables

Available 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 PointLocation in checkout
after_contactBelow the contact (email/phone) section
after_shipping_addressBelow the shipping address form
after_shipping_methodsBelow the shipping method selector
after_payment_methodsBelow the payment method selector
before_order_summaryAbove the order summary panel
after_order_summaryBelow the order summary panel
before_footerAbove the checkout footer
after_footerBelow the checkout footer

Available Remote UI components

BlockStack, InlineStack, Text,Heading, TextField, Button,Banner, Divider, Image, Badge

javascript
// 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

MethodPathDescription
GET/admin/functionsList all checkout functions
POST/admin/functionsCreate a function
GET/admin/functions/:idGet function by ID
PUT/admin/functions/:idUpdate function (name, config, enabled)
DELETE/admin/functions/:idDelete a function
POST/admin/functions/:id/testTest function against a simulated cart
POST/admin/functions/:id/upload-wasmUpload WASM binary (multipart/form-data)
GET/admin/checkout/brandingGet checkout branding
PUT/admin/checkout/brandingUpdate checkout branding
GET/shops/:shopId/checkout/brandingStorefront: get branding CSS variables
GET/shops/:shopId/checkout/payment-methodsStorefront: get filtered payment methods
GET/shops/:shopId/checkout/extensionsStorefront: get active extensions for a point
POST/shops/:shopId/checkout/extensionsRegister 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.