novinzodevelopers
Plugins

Functions

Synchronous plugin HTTP contracts, tenant identity, checkout failure behavior, and persistent D1 handler examples.

Functions are synchronous HTTP calls. Novinzo waits for the response and uses its JSON body. All function paths begin with /functions/ and accept POST requests. No Novinzo package is required to implement them.

FunctionPathPurposeTimeoutFailure behavior
VerifyPriceAdjustment/functions/verify-price-adjustmentReassess issued discounts and charge lines5 sCheckout fails
ResolveDeliveredKeys/functions/resolve-delivered-keysRead an order's delivered keys5 sKeys disappear after failure or timeout
CheckVariantStock/functions/check-variant-stockRead available plugin stock5 sCheckout fails closed
ImportMigratedReviews/functions/import-migrated-reviewsImport migrated store reviews1 minMigration step fails and retries
CreateHostedPayment/functions/create-hosted-paymentOpen a payment page for a buyer who chose the plugin's payment method20 sCheckout fails; no payment is recorded
CancelHostedPayment/functions/cancel-hosted-paymentClose a payment page the buyer gave up on20 sCancellation fails and the payment stays open
ReconcileHostedPayments/functions/reconcile-hosted-paymentsRe-check the store's pending payments with the provider, on a schedule1 minThe next scheduled pass asks again
ChargeSavedMethod/functions/charge-saved-methodCharge the method a subscriber saved, for a renewal20 sThe outcome is unknown; Novinzo asks again under the same key
RemoveSavedMethod/functions/remove-saved-methodForget a saved method no subscription needs20 sThe method stays saved
QuotePaymentSurcharges/functions/quote-payment-surchargesPrice what paying with a payment method adds to the total5 sCheckout and the storefront quote fail; the buyer can retry
AdmitCheckout/functions/admit-checkoutAdmit or refuse a checkout before the buyer pays5 sCheckout fails closed; the buyer can retry
ExtendOrderEmail/functions/extend-order-emailAdd sections and a blind copy to the order confirmation email5 sThe email goes without the plugin's additions
RenderOrderEmail/functions/render-order-emailWrite the whole order confirmation email sent from the store's own domain5 sNovinzo sends its own receipt from the store's domain
QuoteShipping/functions/quote-shippingSay whether the plugin ships a cart to the buyer, and price the shipping5 sCheckout fails; the buyer can retry
QuoteTax/functions/quote-taxPrice the tax on a cart, its shipping and its payment method's surcharges5 sCheckout fails; the buyer can retry
SyncSearchRecords/functions/sync-search-recordsHand over one page of the records the plugin makes searchable30 sThe page is asked again on the next pass, for about 4 hours
IssueKeys/functions/issue-keysIssue keys of a variant for a sale another plugin made20 sThe caller is told to ask again under the same sale reference

A call that outlasts its timeout counts as a failure. The hosted payment functions are called only for a plugin that runs a payment method with payments:provide, and the saved-method functions only for one that activated it with recurring: true.

Starting a checkout calls functions in steps, one step after another, and has 30 seconds in total. Each call is still held to its own timeout. A checkout that has not started after 30 seconds is refused with CheckoutError code INTERNAL_ERROR, and the shopper sees We can't start this checkout right now. Please try again shortly. Answer well inside your function's timeout so that the steps after yours keep their time.

Who gets called

Novinzo selects checkout and order functions from platform records:

  • Price adjustments select the plugin identified by their plugin/<code> actor.
  • Delivered keys select each plugin named in the order's variant delivery records.
  • Stock requests select each plugin named in the cart's variant delivery records.
  • Hosted payment functions select the plugin that runs the payment method of the payment.
  • Key issuing selects the plugin named in the variant's first delivery record.

These functions need no subscription. UpdatePlan records adjustment issuers. DeliverVariant records variant delivery ownership.

Hosted-payment functions go to the plugin that runs the payment's method. See Payments.

ImportMigratedReviews, QuotePaymentSurcharges, AdmitCheckout, ExtendOrderEmail, RenderOrderEmail, QuoteShipping, QuoteTax and SyncSearchRecords are different. Novinzo calls every installed plugin subscribed to import-migrated-reviews during store migration, every installed plugin subscribed to quote-payment-surcharges whenever checkout prices a payment method, every installed plugin subscribed to admit-checkout before a checkout opens its payment, every installed plugin subscribed to extend-order-email whenever it sends an order confirmation email, every installed plugin subscribed to quote-shipping or quote-tax when a buyer starts paying, and a plugin subscribed to sync-search-records when it is installed, and a store-private one after each of its deployments. It calls plugins subscribed to render-order-email that hold emails:customize only while the store's own sending domain is verified, one at a time, until one answers. A subscription uses the same catalog codes as webhooks. A store-private plugin subscribes to quote-payment-surcharges, admit-checkout, extend-order-email, render-order-email or sync-search-records by listing it under webhooks in its novinzo.plugin.json, and each deployment replaces its subscriptions. Novinzo registers first-party plugins' subscriptions through Registration. import-migrated-reviews, quote-shipping and quote-tax are only for first-party plugins. Novinzo makes sure that the plugin remains installed before each function call.

Request identity

Current function requests carry both x-novinzo-store-id and x-novinzo-plugin-invocation. The store header and signed token come from the same platform invocation. Use the trusted store header for local data queries. Reject a different payload.storeId when that field exists. ImportMigratedReviews, QuotePaymentSurcharges, AdmitCheckout, ExtendOrderEmail, RenderOrderEmail, QuoteShipping and QuoteTax have no store field in their payloads.

Forward the invocation token unchanged on platform calls. The signed token, not binding properties or a plugin-name header, establishes platform-call identity in every environment. Plugin authors do not receive signing secrets. Keep Workers private with workers_dev=false and preview_urls=false.

VerifyPriceAdjustment

Novinzo groups a cart's adjustment plan by issuing plugin during checkout initiation. A plugin whose plan entries are only buyer inputs is called too, with no items. It calls each issuer after creating the draft order and matching the plan's cart hash and store. The plan must still leave an amount to charge.

FieldJSON shapeMeaning
storeIdUUID stringCheckout store
action{ "_tag": "checkout", "orderId": "<uuid>" } or { "_tag": "cart-changed" }Reason for reassessment
itemsArray of { type, amount, adjustmentId, metadata, variantId? }This plugin's plan items
buyerInputsArray of { variantId, label, value }What the buyer gave this plugin's storefront block

type is discount or charge. amount is a signed integer encoded as a decimal string. adjustmentId is a string and metadata is an object. A charge line also names the variantId of the cart line it was added to. Refuse a charge line you no longer sell, such as a warranty withdrawn since the buyer chose it, as you would an expired discount. Novinzo sends checkout today. The contract reserves cart-changed, but no current flow calls it.

Return 200 {"ok":true} to accept. Return 400 {"_tag":"VerifyPriceAdjustmentError","messages":["This discount has expired"]} to refuse. Novinzo joins refusal messages with ". " and returns CheckoutError with code INVALID_CART. These messages reach the shopper. Without messages, the shopper sees The discounts or extras on this cart are no longer valid.

An unreachable Worker, unexpected status, malformed response, or removed installation fails checkout. Do not convert infrastructure failures into acceptance.

For limited-use discounts, claim the resource atomically during checkout. Key claims by store, order, and adjustment so repeated calls succeed without consuming another use. Confirm claims on CheckoutCompleted. Release unconfirmed claims on CheckoutCancelled. A checkout initiation that fails after asking issuers to verify rolls its order back, then announces CheckoutCancelled for that order. You can receive a cancellation for an order that never persisted; release any claim keyed by it, and treat an unknown order as already released. Decode the returned metadata against your own published adjustment format and compare it with current terms.

ResolveDeliveredKeys

Payload: { "storeId": "<uuid>", "orderId": "<uuid>" }. Novinzo calls once per plugin per order, even when the plugin delivers several order lines. The call serves seller order details and the shopper's paid order page.

Return all keys for this plugin's variants in the order:

[
  {
    "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
    "value": "ACME-7Q2K-91ZD",
    "status": "active"
  }
]

variantId is a UUID. value is a nonempty trimmed string. status is active, expired, exhausted, or revoked. A revoked key is one the seller withdrew; the buyer still sees it, marked as revoked. Novinzo matches keys to order lines by variant. Scope the lookup by both store and order. Never return another order's keys.

Novinzo waits five seconds. Timeouts, failures, malformed responses, and removed installations produce a warning and an order page without keys. The rest of the page remains available. Keep this function to an indexed lookup.

CheckVariantStock

Payload: { "storeId": "<uuid>", "variants": [{ "variantId": "<uuid>", "quantity": 3 }] }. The variants array contains at least one item. Every quantity is a positive integer. Each plugin receives only variants assigned to it.

Return only shortfalls:

[{ "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90", "requested": 3, "available": 1 }]

An empty array means no shortfall. requested is positive and available is a nonnegative integer. The response is a snapshot, not a reservation. Concurrent buyers can both pass a stock read. When your plugin owns stock, Novinzo also reserves against the count reported through the platform API.

FailureShopper result
Unreachable plugin or installation lookup failureWe can't confirm availability right now. Please try again shortly.
Removed installation, unknown plugin, or malformed answerVariants are refused as unavailable
Reported shortfallsNot enough stock: …

ImportMigratedReviews

Payload: { "reviews": [...] }, with at most 1,000 reviews per call. The tenant comes from the invocation's store header, not from the payload.

Review fieldJSON type
keyNonempty string, maximum 200 characters
productIdUUID string
productNameString
productVariantIdUUID string or null
variantNameString or null
customerEmailString or null
ratingInteger
message, replyString or null
repliedAtDate string or null
automaticBoolean
createdAtDate string

All fields are required. Novinzo only sends reviews for products the store still has, including archived products, and names them as the store does. productVariantId and variantName are null when the migration did not import the variant or the store has since deleted it. Do not read the product back from a storefront endpoint: storefront reads omit archived products. The plugin decides whether source ratings and text fit its own review rules. Novinzo supplies customer email only when the installation has a grant that permits email access. Otherwise it supplies null.

Return one outcome for every input key:

[
  { "_tag": "Imported", "key": "source-review-1", "id": "review-42", "notes": [] },
  { "_tag": "Skipped", "key": "source-review-2", "reason": "Rating is outside the supported range" }
]

Persist imported keys by tenant. A repeated import returns the same identifier instead of creating a second review. Record transformation details in notes and intentional exclusions in reason. A missing outcome fails the migration step.

Return 503 {"_tag":"MigratedReviewsUnavailable","message":"Review storage is unavailable"} for temporary failures. Transport failures and malformed answers also fail the step. The migration retries unanswered work with the same keys. Never report a storage outage as an intentional skip.

QuotePaymentSurcharges

A surcharge is what paying with a particular payment method adds to the buyer's total, such as a card fee. Novinzo asks for it when the buyer starts paying, when they switch payment method, and when the storefront shows each method's surcharge before the buyer picks one.

Payload: { "amount": { "amountMinorUnits": "1999", "currency": "USD" }, "connections": ["<uuid>"] }. amount is what the buyer owes for the cart once its discounts apply. connections holds at least one of the store's payment connection ids: the chosen one at checkout, every active one for the storefront's quote. The tenant comes from the invocation's store header.

Return one surcharge for each connection you charge extra for, and leave out the rest:

[
  {
    "connectionId": "5b0e7c1a-2f4d-4e8b-9a63-1d7c0f2e8b54",
    "adjustmentId": "c3f1a9d2-6b4e-4f07-8a15-2e9d7c6b0f31",
    "amountInMinorUnits": "60",
    "description": "Card fee (3%)"
  }
]

amountInMinorUnits is a positive integer encoded as a string, in the payload's currency. adjustmentId is your own UUID for the charge, such as your rule's id; the order records it. description is 1 to 100 characters, and the buyer reads it beside the amount. An empty array charges nothing.

Novinzo ignores a connection it did not ask about. The order records each surcharge as a price adjustment of type surcharge, beside the plan's discounts and charge lines. A price adjustment plan never carries a surcharge. The amount you are asked to price includes the plan's charge lines.

A refund returns the refunded goods' share of the order's surcharges, rounded half up and counted against everything refunded so far, so refunding every good returns the whole surcharge. Novinzo works this out from the recorded adjustments and does not call your plugin.

Novinzo asks again each time it prices a method and keeps no answer, so a rule the seller changes applies to the next checkout. An unreachable Worker, timeout, unexpected status, malformed answer, or one connection answered twice refuses the checkout with CheckoutError code INTERNAL_ERROR, rather than charge an amount the buyer was not quoted. The shopper sees We can't confirm the price of this payment method right now. Please try again shortly. The storefront's quote fails the same way. A plugin uninstalled after Novinzo read its subscription charges nothing.

AdmitCheckout

Novinzo asks every installed plugin subscribed to admit-checkout whether a checkout may go ahead, once it knows what the buyer pays and before it opens the payment. It asks when the buyer starts paying and again when they switch payment method, so a refusal for one method cannot be bypassed by switching to it afterwards. Use it to block buyers by email, address or network, enforce a minimum or maximum order total, turn off a payment method for some products, cap what a method takes in a day, or close the store for maintenance.

Payload:

{
  "email": "buyer@example.com",
  "ip": "203.0.113.7",
  "network": {
    "asn": 3243,
    "asOrganization": "MEO",
    "country": "PT",
    "region": "Lisbon",
    "regionCode": "11",
    "city": "Lisbon",
    "postalCode": "1100-148",
    "latitude": "38.71670",
    "longitude": "-9.13330",
    "timezone": "Europe/Lisbon",
    "colo": "LIS",
    "tlsVersion": "TLSv1.3",
    "tlsCipher": "AEAD-AES128-GCM-SHA256",
    "httpProtocol": "HTTP/2",
    "acceptLanguage": "pt-PT,pt;q=0.9",
    "userAgent": "Mozilla/5.0 …",
    "botScore": 87,
    "ja3Hash": null,
    "ja4": null
  },
  "device": null,
  "orderId": "9e2d7b14-5c3a-4b6f-8d01-7a9c2e4f6b85",
  "signedInCustomerId": null,
  "lines": [
    {
      "productId": "7c2e9d14-3b5a-4f81-9c06-2d4e8a1b7f35",
      "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "quantity": 2,
      "unitPrice": { "amountMinorUnits": "1000", "currency": "USD" }
    }
  ],
  "buyerInputs": [
    {
      "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "label": "Discord username",
      "value": "buyer#0001"
    }
  ],
  "amount": { "amountMinorUnits": "1860", "currency": "USD" },
  "amountInUsd": { "amountMinorUnits": "1860", "currency": "USD" },
  "connection": { "id": "5b0e7c1a-2f4d-4e8b-9a63-1d7c0f2e8b54", "provider": "stripe" }
}
FieldMeaning
emailThe address the buyer checks out with. Null unless the store granted customers:email, customers:read, customers:list, orders:read or orders:list.
ipThe buyer's address as Cloudflare reported it, or null when unknown. Null unless the store granted orders:read.
networkWhat Cloudflare reported about the buyer's network and client: asn, asOrganization, country, region, regionCode, city, postalCode, latitude, longitude, timezone, colo, tlsVersion, tlsCipher, httpProtocol, acceptLanguage, userAgent, botScore, ja3Hash and ja4. Each field is null when the edge did not report it. Core reads it off the request that reached the platform, whether it came through the storefront or straight to the API, so a caller cannot leave it out. The whole object is null when what was reported does not fit these fields, and unless the store granted orders:read.
deviceWhat the buyer's browser reported about itself and the visit: deviceId (a random id the browser keeps for the store), timezone, languages, screenWidth, screenHeight, hardwareConcurrency, deviceMemory, maxTouchPoints, webdriver, pagesViewed, secondsSinceFirstVisit, secondsOnCheckout and emailPasted. Only the storefront's checkout form sends it, and only through the storefront is it trusted, so it is null for any other caller, when the browser sent none, and unless the store granted orders:read. The browser can be scripted, so treat every field as a hint.
orderIdThe order checkout opened for this attempt, still unpaid. Its later webhooks, such as PaymentAttempted and PaymentDisputed, name it, so a plugin can tie what it decided to what became of the order. When admission refuses the checkout, or checkout fails afterwards, the order is rolled back and the id names no order.
signedInCustomerIdThe store customer the buyer is signed in as, or null for a guest. It can name another customer than email does. Read the customer with CustomerById. Null unless the store granted customers:email, customers:read, customers:list, orders:read or orders:list.
linesAt least one line, each with its product, variant, quantity and unit price before charge lines, discounts and surcharges.
buyerInputsWhat the buyer gave your own storefront block for the cart's lines, as { variantId, label, value }: the buyer inputs your plugin put on the plan with UpdatePlan, never another plugin's. An empty array when a checkout starts and the buyer gave you nothing, so refuse here a checkout that lacks an answer you require. The field is left out when there is nothing to judge, and you should admit: from a core that predates it; for a checkout that takes no plan, such as a prepared checkout; and when the buyer switches payment method, since what they gave was judged when the checkout started and a switch cannot change it. So an answer you require only of some payment methods is not asked for on a switch to one of them.
amountWhat the buyer pays: the cart once its charge lines, discounts, shipping and tax and the chosen payment method's surcharges apply. Tax inside the prices adds nothing.
amountInUsdamount in US dollars at a recent exchange rate, so one bound holds for orders in any currency. An estimate, never what is charged. Null when the order's currency could not be converted, and left out by a core that predates it.
connectionThe store's payment method the buyer pays with: its id and the kind of provider behind it, such as stripe, crypto or plugin. New kinds can appear; do not refuse one you do not know.

The tenant comes from the invocation's store header.

Answer { "admit": true } to let the checkout go ahead, or refuse it with a message the buyer reads:

{ "admit": false, "message": "Orders from this region are not accepted." }

message is trimmed, then 1 to 200 characters. Write it for the buyer; it is shown as you wrote it.

Every subscribed plugin must admit the checkout. A refusal stops it with CheckoutError code CHECKOUT_REFUSED and your message. A refused start rolls the draft order back and leaves no payment, and adjustment issuers are not asked to claim. A refused switch leaves the buyer on the method they had. An unreachable Worker, timeout, unexpected status or out-of-contract answer refuses the checkout too: Novinzo fails the checkout call with CheckoutError code INTERNAL_ERROR and the message We can't confirm this checkout right now. Please try again shortly. The storefront may stop waiting for that call before your 5 s run out, and then shows the buyer its own error instead of this message. When one plugin refuses and another fails, the buyer sees the refusal. A plugin uninstalled after Novinzo read its subscription is not asked.

Novinzo asks again on every attempt and keeps no answer. The checkout is not yet paid when you are asked, and it may still be abandoned or fail at the payment provider. You are not asked again when the buyer retries a card inside the checkout. Instead, at a store any plugin subscribes to admit-checkout for, Novinzo stops an order taking cards once 5 were declined for it. A card entered on the storefront is then refused with CheckoutError code CHECKOUT_REFUSED and the message Too many cards were declined for this order. Please choose another payment method., and a Stripe payment is cancelled after the decline that reached the limit. The checkout stays open, and the buyer can switch it to any method but Stripe. Count what a checkout takes, such as a method's daily volume, on CheckoutCompleted, not here. Answer quickly: the buyer waits on your answer.

ExtendOrderEmail

Novinzo sends the buyer an order confirmation email once an order is paid. ExtendOrderEmail lets a plugin add to it, for delivery instructions, a review request or warranty notes, and ask for a blind copy, for a review platform's automatic feedback service. The email stays Novinzo's: a plugin cannot change its subject, sender, recipient or Novinzo's own content, and supplies no markup. A store-private plugin is the seller's own code, so it can only ask for a blind copy: Novinzo drops its sections. Changing what the email says needs a store's own sending domain: once it is verified, a plugin writes the whole email through RenderOrderEmail.

Payload:

{
  "orderId": "8f0c2d4e-1a3b-4c5d-9e6f-7a8b9c0d1e2f",
  "customerEmail": null,
  "lines": [
    {
      "productId": "2c4e6a8b-0d1f-4a3b-8c5d-7e9f1a2b3c4d",
      "productVariantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "productName": "Pro Tools",
      "variantName": "Lifetime",
      "quantity": 2
    }
  ]
}

customerEmail is the address the email goes to when the store granted your plugin customers:email, customers:read, customers:list, orders:read or orders:list, and null otherwise. variantName is null for a variant without a name of its own. The tenant comes from the invocation's store header.

Answer with the sections to add, which can be none, and an optional blind-copy address:

{
  "sections": [
    {
      "heading": "Tell us how it went",
      "paragraphs": ["Your review helps other buyers choose."],
      "action": { "label": "Leave a review", "url": "https://reviews.example.com/r/8f0c2d4e" }
    }
  ],
  "bcc": "acme+feedback@invite.reviews.example"
}
FieldRule
sectionsRequired, at most 2 sections.
headingRequired, 1 through 150 characters.
paragraphsRequired, 1 through 5 paragraphs of at most 2000 characters each.
actionOptional link: label of at most 60 characters and an absolute https: url without credentials.
bccOptional single email address, without a display name. Honoured only when the store granted your plugin orders:read.

Every text field is plain text, the same as Emails: Novinzo strips control characters, trims it and escapes it, in the HTML and the plain-text body alike. Novinzo shows each section in a box under the order and its link, headed Added by <your plugin's name>, an app <store> uses, and shows action as a link, so the email's own button stays the only one. Sections come in the order of the plugins' names. An email shows at most 4 sections and has at most 2 blind copies, from all plugins together; past those, a later plugin's sections and address are left out.

A blind copy is the buyer's email exactly as sent: delivered license keys and a link that opens the buyer's order page, downloads included, for 7 days. Novinzo honours bcc only for a plugin granted orders:read, which reveals as much; it drops the bcc of a plugin without it, and keeps its sections. Novinzo sends each copy as a message of its own to that address, and only once the buyer's email was accepted, so a copy never goes out when the buyer's address cannot receive mail. A copy that fails is logged and not sent again. Ask a seller for orders:read only when they want the copy, and tell them who receives it.

The email never waits for your plugin. An unreachable Worker, a timeout, an unexpected status, or an answer out of contract, such as a third section or an http: link, leaves out everything your plugin answered, and the email goes without it. A plugin uninstalled after Novinzo read its subscription adds nothing.

Novinzo asks again each time it tries to send the email. When a send fails and is retried, your plugin is asked again, and its copy is sent only after the retry reaches the buyer. The mail provider takes no idempotency key: in the rare case where a send succeeded but was not recorded, the buyer and the blind copy both receive the email twice. Answer the same way for the same order.

When a plugin writes the whole email through RenderOrderEmail, the sections stay out of it: they belong to Novinzo's receipt, which is sent only when no plugin writes the email. The blind copy is then of the plugin's email.

RenderOrderEmail

RenderOrderEmail lets a plugin write the whole order confirmation email, markup included, for an email theme or a custom delivery template. Novinzo sends what it answers in place of its own receipt.

A store's email must not harm the platform's sending reputation, so a plugin can replace the email only once the store sends from a domain of its own. A plugin granted emails:customize registers the store's domain with SendingDomainRegister, shows the seller the DNS records it answers, and calls SendingDomainVerify once they are published. While the domain's DKIM and Return-Path are both verified:

  • every order confirmation of the store goes from "<store name>" <orders@<domain>>, whoever writes it;
  • Novinzo asks the store's plugins subscribed to render-order-email and granted emails:customize, one at a time in the order of their names, and sends the first answer in contract. It does not ask the rest.

Until then, no plugin is asked, and Novinzo sends its own receipt from its own sender. The same holds once the domain stops being verified: Novinzo checks its records again daily, and a domain it could not check for 7 days counts as unverified (see Sending domains).

Payload:

{
  "orderId": "8f0c2d4e-1a3b-4c5d-9e6f-7a8b9c0d1e2f",
  "storeName": "Acme Keys",
  "customerEmail": null,
  "itemCount": 2,
  "currency": "USD",
  "total": "$10.00",
  "orderUrl": "https://acme.example.com/orders/8f0c2d4e-1a3b-4c5d-9e6f-7a8b9c0d1e2f?access=…",
  "lines": [
    {
      "productId": "2c4e6a8b-0d1f-4a3b-8c5d-7e9f1a2b3c4d",
      "productVariantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "productName": "Pro Tools",
      "variantName": "Lifetime",
      "quantity": 2,
      "delivery": { "_tag": "Keys", "keys": [{ "value": "AAAA-BBBB", "status": "active" }] }
    }
  ]
}

The payload is what Novinzo's own receipt shows. delivery is one of { "_tag": "Keys", "keys": [...] } (each key active, expired, exhausted or revoked), { "_tag": "Download", "url": ... } (the order page, which signs a fresh file link), { "_tag": "Pending" } (not ready yet; it appears on the order page) or { "_tag": "None" }. orderUrl opens the order without signing in, and total and orderUrl are null when Novinzo's receipt leaves them out. customerEmail follows the same rule as in ExtendOrderEmail. The tenant comes from the invocation's store header.

Answer with the whole email:

{
  "subject": "Your Pro Tools are here",
  "htmlBody": "<!doctype html><html>…</html>",
  "textBody": "Thanks for your order…"
}
FieldRule
subjectRequired plain text, 1 through 150 characters once control characters are stripped.
htmlBodyRequired, 1 through 200000 characters. Sent as you write it.
textBodyRequired, 1 through 50000 characters. Sent as you write it.

The email carries the delivered keys and the order link, so include them: the buyer has no other copy of the receipt. The recipient is always the buyer, and the sender always the store's verified domain.

The email never waits for your plugin. An unreachable Worker, a timeout, an unexpected status or an answer out of contract, such as an empty subject, skips your plugin; when no plugin answers, Novinzo sends its own receipt, still from the store's domain. As with ExtendOrderEmail, Novinzo asks again on each send attempt.

Shipping and tax

Novinzo does not pick a shipping or tax plugin for a store. When a buyer starts paying for a cart or a prepared checkout, it asks every installed plugin subscribed to quote-shipping for shipping, then every one subscribed to quote-tax for tax on the cart, that shipping and the payment method's surcharges. The order records the answers as price adjustments of type shipping, tax and included_tax, beside the plan's discounts and charge lines, and the buyer pays exactly what was quoted. Switching payment method keeps the shipping and asks quote-tax again, since the new method's surcharge changes what is taxed. A cart that discounts bring to nothing is refused before either is asked, and a subscription renewal charges its price without asking them.

Both functions take the cart's lines, each with variantId, quantity, unitPrice and requiresShipping, and its amount: what the buyer owes for the goods, their prices less the cart's discounts plus the charge lines plugins added. unitPrice is the variant's price before charge lines, in the currency of amount. A line requiresShipping when its variant's delivery sends it to the buyer's address. The payment method's surcharge is priced on the goods alone, without shipping or tax. The tenant comes from the invocation's store header.

A quoted line has the same shape in both answers:

FieldRule
adjustmentIdYour own UUID for what you charged, such as your rate's id. The order records it.
amountInMinorUnitsA positive integer encoded as a string, in the currency of amount, at most Number.MAX_SAFE_INTEGER.
description1 to 100 characters. The buyer reads it beside the amount, such as Shipping to Portugal (mainland).

An unreachable Worker, timeout, unexpected status or malformed answer refuses the checkout with CheckoutError code INTERNAL_ERROR, rather than charge an amount the buyer was not shown. So does a failure to read the store's subscriptions. A plugin uninstalled after Novinzo read its subscription is not asked.

QuoteShipping

Novinzo calls QuoteShipping only for a cart with at least one line that requiresShipping.

Payload:

{
  "lines": [
    {
      "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "quantity": 2,
      "unitPrice": { "amountMinorUnits": "1000", "currency": "EUR" },
      "requiresShipping": true
    }
  ],
  "amount": { "amountMinorUnits": "2000", "currency": "EUR" },
  "destination": { "country": "PT", "postalCode": "1100-148" }
}

destination is the shipping address the buyer entered: country is an ISO 3166-1 alpha-2 code and postalCode is 1 to 20 characters, or null.

Answer whether you ship the order there and, when you do, the shipping you charge:

{
  "ships": true,
  "lines": [
    {
      "adjustmentId": "a4d2c8e1-5b3f-4e7a-9c16-0f8b2d7e4a93",
      "amountInMinorUnits": "590",
      "description": "Shipping to Portugal (mainland)"
    }
  ]
}

"ships": true with no lines is free shipping. Answer { "ships": false, "lines": [] } for a destination you do not ship to; Novinzo ignores the lines of a plugin that does not ship.

One plugin ships an order. When more than one answers ships: true, checkout is refused with INTERNAL_ERROR rather than charge the buyer twice. The buyer sees We can't confirm shipping for this order right now. Please try again shortly. for this and every failure above.

When no plugin ships to the destination, including at a store with no shipping plugin, checkout is refused with CheckoutError code DESTINATION_NOT_SHIPPED and the message This store isn't shipping to you yet. A checkout of such a cart without a shipping address is refused with code SHIPPING_ADDRESS_REQUIRED before any plugin is asked.

QuoteTax

Novinzo calls QuoteTax on every cart or prepared checkout once shipping and the payment method's surcharges are priced, and again when the buyer switches a started checkout to another payment method.

Payload:

{
  "lines": [
    {
      "variantId": "0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90",
      "quantity": 2,
      "unitPrice": { "amountMinorUnits": "1000", "currency": "EUR" },
      "requiresShipping": true
    }
  ],
  "amount": { "amountMinorUnits": "2000", "currency": "EUR" },
  "shipping": { "amountMinorUnits": "590", "currency": "EUR" },
  "surcharges": { "amountMinorUnits": "180", "currency": "EUR" },
  "destination": { "country": "PT", "postalCode": "1100-148" }
}

shipping is the total the cart was quoted for shipping, zero when it ships nothing. surcharges is what the payment method the buyer pays with adds, zero when it adds nothing. It is part of what the buyer pays for the goods, so tax it with them. A request without surcharges comes from a Novinzo that predates it; treat it as zero. destination is the shipping address for a cart that ships, otherwise the billing country and postal code the payment form gave, or null when neither is known. A billing postal code that does not fit 1 to 20 characters is sent as null.

Answer the tax lines, each a quoted line with included:

[
  {
    "adjustmentId": "e7b1f3a9-2c5d-4b8e-a6f0-3d9c1e7b5a24",
    "amountInMinorUnits": "484",
    "description": "IVA 23%",
    "included": true
  }
]

included: false adds the tax to what the buyer pays, as type tax. included: true records tax already inside the prices, as type included_tax, and adds nothing. An empty array charges no tax, as at a store without a tax plugin.

One plugin taxes an order. When more than one answers with lines, or the tax inside the prices is more than the buyer pays for the cart, its shipping and its surcharges, checkout is refused with INTERNAL_ERROR. The buyer sees We can't work out the tax on this order right now. Please try again shortly. for this and every failure above.

SyncSearchRecords

The dashboard's search finds what your plugin writes to it. Write a record whenever it changes; this function hands over the records written before that, page by page.

Payload: { "generation": "<uuid>", "cursor": null }. cursor is null for the first page, then whatever your previous answer named. The tenant comes from the invocation's store header.

For each page:

  1. Read up to 500 records from cursor.
  2. Write them with POST /api/search/records/sync under the payload's generation, with done: true if it is your last page.
  3. Answer { "nextCursor": "<where the next page starts>" }, or { "nextCursor": null } after the last page.
{ "nextCursor": "coupon:6b1f…" }

The cursor is yours and opaque to Novinzo, up to 1000 characters; a record id or a sort key works. Write the page before answering: Novinzo asks for the next page as soon as you answer. A page can be asked for again after a failure, so the same generation and cursor must write the same records.

Novinzo asks for pages for about a minute at a time and continues on the next pass of its delivery loop, a few minutes later, so a large store takes several passes. A failure retries from the last page you answered: answer SearchRecordsPageUnavailable (503) when you cannot read or write a page now. Any failure on the same page, whatever its cause (a 404 from a Worker not deployed yet, a 503, another status or a timeout), is retried on each pass for about four hours, so a sync owed before your new Worker is deployed is not lost; then Novinzo stops asking, and the records are owed again only when the plugin is next installed. A plugin uninstalled meanwhile is asked nothing more, and a malformed answer ends the sync.

IssueKeys

Another plugin sold your keys outside the store's checkout: there is no order, and the buyer is not a customer of the store. That plugin holds the store's keys:issue grant and called VariantKeysIssue; Novinzo passes the call to the plugin that delivers the variant.

Payload: { "storeId": "<uuid>", "variantId": "<uuid>", "quantity": 3, "saleRef": "line-81:0", "issuedForPluginCode": "resellers" }. quantity is 1 through 100. saleRef is the selling plugin's name for the sale, up to 128 characters.

Answer the keys of the sale's units, in order:

{ "keys": ["AAAAA-BBBBB-CCCCC-DDDDD"] }

Issue the keys as you would for a purchase and take them out of your stock, then report the new stock with SetVariantStock.

The call must be idempotent on issuedForPluginCode and saleRef together. The selling plugin asks again whenever it did not hear your answer, and a second answer must hold the same keys, never new ones. Record the sale and its keys in one write.

When you have fewer keys than quantity, answer the ones you have. They are sold: the selling plugin hands them to its buyer and fails the rest of its sale. A later call under the same saleRef answers them again, with any more you can issue by then.

Answer 404 VariantNotEnabledError for a variant you issue no keys for. Any other failure, or no answer within 20 seconds, tells the selling plugin to ask again under the same saleRef.

Example handlers

This standalone Worker implements the three checkout and order functions above using D1. It reads persistent stock and issued keys, and reassesses unlimited fixed discounts. It does not allocate keys, reserve stock, issue adjustment plans, or implement review import. Those workflows belong to your plugin's write handlers and platform integration.

Start with the quickstart configuration. Install a public JSON parser:

npm install zod@4

Add this migration to your standalone project's migrations directory:

migrations/0002_functions.sql
CREATE TABLE stock (
  store_id TEXT NOT NULL,
  variant_id TEXT NOT NULL,
  available INTEGER NOT NULL CHECK (available >= 0),
  PRIMARY KEY (store_id, variant_id)
);
CREATE TABLE delivered_keys (
  store_id TEXT NOT NULL,
  order_id TEXT NOT NULL,
  variant_id TEXT NOT NULL,
  value TEXT NOT NULL CHECK (length(trim(value)) > 0 AND value = trim(value)),
  status TEXT NOT NULL CHECK (status IN ('active', 'expired', 'exhausted', 'revoked')),
  PRIMARY KEY (store_id, order_id, variant_id, value)
);
CREATE TABLE adjustments (
  store_id TEXT NOT NULL,
  adjustment_id TEXT NOT NULL,
  amount TEXT NOT NULL,
  revision TEXT NOT NULL,
  enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),
  PRIMARY KEY (store_id, adjustment_id)
);

Save this complete alternative Worker as src/functions.js and set Wrangler's main to that file. Use it separately from the purchase Worker, or combine their routers in your application.

src/functions.js
import { z } from "zod";
const id = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
const quantity = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
const stockPayload = z.object({
  storeId: id,
  variants: z
    .array(
      z.object({
        variantId: id,
        quantity,
      }),
    )
    .min(1),
});
const keysPayload = z.object({ storeId: id, orderId: id });
const adjustmentPayload = z.object({
  storeId: id,
  action: z.discriminatedUnion("_tag", [
    z.object({ _tag: z.literal("checkout"), orderId: id }),
    z.object({ _tag: z.literal("cart-changed") }),
  ]),
  items: z.array(
    z.object({
      type: z.enum(["discount", "charge"]).default("discount"),
      amount: z.string().regex(/^-?\d+$/),
      adjustmentId: z.string(),
      metadata: z.record(z.string(), z.unknown()),
      variantId: id.optional(),
    }),
  ),
  buyerInputs: z
    .array(z.object({ variantId: id, label: z.string(), value: z.string() }))
    .default([]),
});
const schemas = {
  "/functions/check-variant-stock": stockPayload,
  "/functions/resolve-delivered-keys": keysPayload,
  "/functions/verify-price-adjustment": adjustmentPayload,
};
const fail = (status, tag) => Response.json({ _tag: tag }, { status });

export default {
  async fetch(request, env) {
    const path = new URL(request.url).pathname;
    const schema = schemas[path];
    if (request.method !== "POST" || !schema) return fail(404, "NotFound");
    if (!request.headers.get("x-novinzo-plugin-invocation")) return fail(401, "MissingInvocation");
    const storeId = request.headers.get("x-novinzo-store-id");
    if (!id.safeParse(storeId).success) return fail(400, "MissingStoreIdError");
    if (request.headers.get("content-type")?.split(";")[0].trim() !== "application/json") {
      return fail(415, "UnsupportedMediaType");
    }
    let decoded;
    try {
      decoded = schema.safeParse(await request.json());
    } catch {
      return fail(400, "InvalidPayload");
    }
    if (!decoded.success) return fail(400, "InvalidPayload");
    const payload = decoded.data;
    if (payload.storeId !== storeId) return fail(403, "StoreMismatch");
    try {
      if (path === "/functions/check-variant-stock") {
        const shortfalls = [];
        for (const { variantId, quantity } of payload.variants) {
          const row = await env.DB.prepare(
            "SELECT available FROM stock WHERE store_id = ? AND variant_id = ?",
          )
            .bind(storeId, variantId)
            .first();
          const available = row === null ? 0 : row.available;
          if (available < quantity) shortfalls.push({ variantId, requested: quantity, available });
        }
        return Response.json(shortfalls);
      }
      if (path === "/functions/resolve-delivered-keys") {
        const { results } = await env.DB.prepare(
          `SELECT variant_id AS variantId, value, status
          FROM delivered_keys WHERE store_id = ? AND order_id = ? ORDER BY variant_id, value`,
        )
          .bind(storeId, payload.orderId)
          .all();
        return Response.json(results);
      }
      const messages = [];
      for (const item of payload.items) {
        const row = await env.DB.prepare(
          `SELECT amount, revision, enabled FROM adjustments
          WHERE store_id = ? AND adjustment_id = ?`,
        )
          .bind(storeId, item.adjustmentId)
          .first();
        if (
          row === null ||
          row.enabled !== 1 ||
          row.revision !== item.metadata.revision ||
          BigInt(row.amount) !== BigInt(item.amount)
        ) {
          messages.push("This discount is no longer available");
        }
      }
      return messages.length > 0
        ? Response.json({ _tag: "VerifyPriceAdjustmentError", messages }, { status: 400 })
        : Response.json({ ok: true });
    } catch {
      return fail(500, "UnexpectedError");
    }
  },
};

The discount format uses metadata.revision and a fixed integer amount. Persist those terms when issuing the corresponding plan. Change the revision whenever those terms change. These discounts have unlimited uses, so reassessment consumes nothing and repeated checkout calls remain safe. Do not use this handler for limited-use resources without adding atomic claims and outcome processing.

For a local fixture, insert stock through the public CLI:

npm run db:local
npx wrangler d1 execute DB --local --command "INSERT INTO stock (store_id,variant_id,available) VALUES ('7d5c4a7e-1f0b-4c35-9a52-1b2f0e8d9c41','0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90',1) ON CONFLICT (store_id,variant_id) DO UPDATE SET available=excluded.available"
npm run dev

Send a stock request in another terminal:

curl -i http://localhost:8787/functions/check-variant-stock \
  -H 'content-type: application/json' \
  -H 'x-novinzo-store-id: 7d5c4a7e-1f0b-4c35-9a52-1b2f0e8d9c41' \
  -H 'x-novinzo-plugin-invocation: local-fixture-only' \
  -d '{"storeId":"7d5c4a7e-1f0b-4c35-9a52-1b2f0e8d9c41","variants":[{"variantId":"0b8f6c3e-2a71-4d9e-8f05-6c4b3a2d1e90","quantity":3}]}'

The response reports requested:3 and available:1. The fake fixture token is unusable against live core. Header presence is not signature authentication. This exercise tests the handler and local storage, not Novinzo installation, checkout, or dispatch. See Testing plugins for real staging acceptance.

On this page