novinzodevelopers
Plugins

Reading dashboard data

Call permission-gated backend RPCs through a service binding with the current invocation token.

Core for plugins covers products, orders, customers, email, price adjustments, product deliveries and storefront cache changes. Backend RPC adds permission-gated operations over NDJSON.

NDJSON is newline-delimited JSON. Each message ends with a newline.

The permission model

Coordinate requested permissions with Novinzo during registration, or declare them in a store-private plugin's novinzo.plugin.json. The seller grants permissions for each installation.

PermissionAccess
orders:readFull order details and completed-order attribution.
orders:listPage through the store's orders through c4p.
orders:annotateAdd notes to the store's orders' timelines through c4p.
checkout:writePrepare unpaid checkouts and publish owned checkout-session events.
customers:emailReveal customer email through the order-viewer c4p endpoint.
customers:readRead one of the store's customers by id or by email through c4p.
customers:listPage through the store's customers through c4p.
emails:sendSend transactional email in the store's name through c4p.
products:readList the store's live variants through c4p.
products:writeCreate and publish the plugin's own products through c4p.
payments:provideRun a hosted payment method for the store and report how its payments ended.
sales:writeReport sales made outside the checkout as store revenue through c4p, and the order lines it took in as credit for them.
analytics:readThe store's revenue, order counts, products sold and conversion over time, as the overview charts them, and a product's sales by variant.
emails:customizeSet up the store's own sending domain, and write the order confirmation email sent from it once it is verified.
storefront:injectAdd HTML to the store's storefront pages through c4p, and admit the origins it names to their CSP.
deliveries:writeReport the parts sent for the order lines the plugin delivers and ships.
replacements:writeHold, confirm, release and report sent replacement units for the order lines the plugin delivers and ships.
returns:writePut units of the order lines the plugin delivers and ships back in stock once they come back.
refunds:writeRefund units of the order lines the plugin delivers, through the provider that took the payment.
prices:adjustSign the discounts and charges the plugin puts on a buyer's cart through c4p.
products:deliverDeliver any variant of the store and own its stock through c4p.
payments:readList the payment methods the store has connected and enabled through c4p.
keys:issueTake license keys of a variant another plugin delivers, for a sale the plugin makes outside the store's checkout.
push:sendTell the store's team about one of its paid orders on their phones, at most once per order.

Core-for-plugins does not require prices:adjust or products:deliver yet. Declare them anyway, so the plugin keeps working once it does.

The backend admits plugins only to explicitly permission-gated RPCs:

RPCRequired permissionResult
OrderDetailsorders:readFull order details, including email, IP address, payment details and delivered keys.
PreparedCheckoutCreatecheckout:writeAn unpaid checkout URL on the store's domain.
WebhookEventPublishcheckout:writePublishes an event type owned by the calling plugin.
PluginPaymentMethodActivatepayments:provideOffers the plugin's payment method at the store's checkout.
PluginPaymentMethodDeactivatepayments:provideWithdraws the plugin's payment method from checkout.
PluginPaymentReportpayments:provideReports how a payment the plugin took ended.
GetAnalyticsanalytics:readThe store's sales measures over a date range, totals and grouped rows only.
GetVariantInsightsanalytics:readA product's sales by variant, how often its buyers buy again and what they buy next.
SendingDomainRegisteremails:customizeRegisters the store's own sending domain and answers the DNS records that verify it.
SendingDomainGetemails:customizeThe store's sending domain, its records and whether each is verified.
SendingDomainVerifyemails:customizeHas the mail provider check the records now.
SendingDomainRemoveemails:customizeRemoves the store's sending domain; order emails go from Novinzo's sender again.
OrderLineDeliveryReportdeliveries:writeReports a part sent on a line the plugin delivers and ships, with the label and link the buyer reads.
OrderLineReplacementHoldreplacements:writeHolds units of a variant the plugin ships as a replacement owed on a delivered line, until the hold expires.
OrderLineReplacementConfirmreplacements:writeCommits the held units to the buyer: they leave stock and no longer expire.
OrderLineReplacementReleasereplacements:writeGives up a replacement not yet sent and puts its units back on sale.
OrderLineReplacementShippedreplacements:writeRecords the replacement sent, with the label and link the buyer reads.
OrderLineRestockreturns:writePuts returned units of a line the plugin delivers and ships back in stock, never more than were reported delivered.
OrderLineRefundrefunds:writeRefunds units of a line the plugin delivers. Core sets the amount.
VariantKeysIssuekeys:issueHands over keys of a variant another plugin delivers, for a sale the plugin made outside the checkout.
SellerOrderPushSendpush:sendTells the store's team about one of its paid orders on their phones. A second call for the same order sends nothing.

Other backend RPCs remain seller-only. orders:read grants the entire OrderDetails response, not selected fields.

Sellers grant permissions at installation or through SetPluginPermissions. A grant not requested by the plugin fails with UnrequestedPluginPermissionError.

How the backend admits a plugin

Send x-novinzo-plugin-invocation with every call. The signed token identifies the plugin and store in every environment.

The backend applies these rules:

  1. Invalid or expired invocation tokens fail with PluginInvocationRejected.
  2. The invocation store determines scope. Binding props and x-store-id do not replace it.
  3. A current installation and the RPC's required seller grant are required.

A missing invocation token follows seller authentication instead. Reject it locally before sending a plugin call.

Installation lookup failures, withdrawn grants and unsupported RPCs all return PermissionDenied. This hides store existence and fails closed.

The backend reads the installation on every call. Uninstalling or withdrawing a grant affects the next call.

Add the binding

A store-private plugin has no BACKEND binding. It sends the same requests to https://dashboard.novinzo.com/api/rpc with fetch, and skips this step.

For any other plugin, coordinate backend binding access and environment names with Novinzo. There is no public self-service provisioning API.

Replace the service placeholder with the name Novinzo supplies. The binding name stays BACKEND in every environment:

wrangler.jsonc
{
  "name": "acme-plugin",
  "main": "src/index.js",
  "compatibility_date": "2026-10-01",
  "workers_dev": false,
  "preview_urls": false,
  "services": [{ "binding": "BACKEND", "service": "<supplied by Novinzo>" }],
}

Production deployment is coordinated with Novinzo. See Deployment.

Call an RPC

Use env.BACKEND.fetch with https://backend.internal/rpc. The hostname is a placeholder handled by the binding.

Send content-type: application/ndjson, an empty envelope headers array and the invocation in the HTTP header. Do not send x-storefront-request.

Expected outcomes arrive as HTTP 200 with an Exit frame. Success uses exit.value; failure uses exit.cause.

This complete Worker provides optional customer-email enrichment for an admin request. It consumes only the email field, not the full order schema.

src/index.js
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);

async function customerEmail(backend, invocation, orderId) {
  const response = await backend.fetch("https://backend.internal/rpc", {
    method: "POST",
    headers: {
      "content-type": "application/ndjson",
      accept: "application/ndjson",
      "x-novinzo-plugin-invocation": invocation,
    },
    body:
      JSON.stringify({
        _tag: "Request",
        id: "0",
        tag: "OrderDetails",
        payload: { orderId },
        headers: [],
      }) + "\n",
  });
  if (!response.ok) throw new Error("RPC HTTP failure");
  const text = await response.text();
  if (!text.endsWith("\n")) throw new Error("Incomplete RPC response");
  const lines = text.split("\n").filter((line) => line.trim() !== "");
  if (lines.length !== 1) throw new Error("Unexpected unary RPC framing");
  const frame = JSON.parse(lines[0]);
  if (!record(frame) || frame._tag !== "Exit" || frame.requestId !== "0" || !record(frame.exit)) {
    throw new Error("Invalid RPC frame");
  }
  const exit = frame.exit;
  if (exit._tag === "Success") {
    if (
      !record(exit.value) ||
      exit.value.orderId !== orderId ||
      typeof exit.value.customerEmail !== "string"
    ) {
      throw new Error("Invalid order response");
    }
    return exit.value.customerEmail;
  }
  if (exit._tag !== "Failure" || !Array.isArray(exit.cause) || exit.cause.length === 0) {
    throw new Error("Invalid RPC outcome");
  }
  const permissionOnly = exit.cause.every(
    (entry) =>
      record(entry) &&
      entry._tag === "Fail" &&
      record(entry.error) &&
      entry.error._tag === "PermissionDenied" &&
      typeof entry.error.message === "string",
  );
  if (permissionOnly) return null;
  // Other typed failures, defects and interruptions are not permission degradation.
  throw new Error("Order RPC failed");
}

export default {
  async fetch(request, env) {
    if (new URL(request.url).pathname !== "/admin/optional-customer-email") {
      return new Response("Not found", { status: 404 });
    }
    if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
    const invocation = request.headers.get("x-novinzo-plugin-invocation");
    if (!invocation) return new Response("Missing invocation", { status: 401 });
    let payload;
    try {
      payload = await request.json();
    } catch {
      return new Response("Invalid JSON", { status: 400 });
    }
    if (!record(payload) || typeof payload.orderId !== "string" || !uuid.test(payload.orderId)) {
      return new Response("Invalid orderId", { status: 400 });
    }
    try {
      const email = await customerEmail(env.BACKEND, invocation, payload.orderId);
      return Response.json({ customerEmail: email });
    } catch {
      return new Response("Order lookup unavailable", { status: 502 });
    }
  },
};

Only a failure containing exclusively PermissionDenied becomes null. Mixed causes, malformed frames and protocol-level Defect frames fail the request.

Prepared checkouts

PreparedCheckoutCreate accepts items, attributes, successUrl, cancelUrl and optional visitorId and expiresInMinutes. Use the reference for exact payload schemas.

The lifetime defaults to 1440 minutes and accepts integers from 30 through 1440. Return URLs use HTTPS.

visitorId is a UUID naming the buyer as the visitor of your own site. The order carries it instead of the visitor id of the pay page, so affiliate credit follows the arrival recorded for that visitor.

Success returns preparedCheckoutId, url, expiresAt, priced items and subtotal. The buyer pays on the store's domain, where prices are evaluated again.

Preparing a checkout does not take payment or create an order. Refused lines return PreparedCheckoutLinesRefusedError; unavailable plugin stock confirmation returns PreparedCheckoutStockUnconfirmedError.

Analytics

GetAnalytics runs the query behind the overview's charts, for the store in the invocation. Send one or more measures (revenue, ordersCount, completedOrdersCount, productsSold, avgOrderValue, checkoutSessions, conversionRate), up to three dimensions (date, paymentMethod, paymentMethodName, paymentMethodIconUrl, productId, productName, variantId, channel), one dateRanges entry plus an optional comparison range, and a timeBucket for date. Use the reference for filters, ordering and limits.

totals holds one value per measure across the range, and rows one per group. Money arrives as { amountMinorUnits, currency } in the store's currency; counts and percentages arrive as numbers. Days and weeks follow the store's time zone.

The response holds aggregates only. To show one order, request orders:read and call OrderDetails.

Publishing checkout events

WebhookEventPublish requires ownership of the event type in addition to checkout:write. A grant alone does not authorize arbitrary event types.

The payload contains type, dedupKey and data. Supported types are CheckoutSessionCompleted and CheckoutSessionExpired.

Event data contains sessionId, status, orderId, items, totals and string-valued metadata. Completion uses status completed and an order UUID.

Expiry uses status expired and null orderId. Data encodes to at most 32768 characters. Deduplication keys contain 1 through 200 characters.

Publishing the same store, type and key again succeeds without sending another event. Wrong event ownership returns WebhookEventNotOwnedError.

Sending domains

A store's order confirmation email goes from Novinzo's own sending domain, whose reputation every store shares, so Novinzo writes it. A store that sends from a domain of its own, which it proved it controls, may have a plugin write the email instead through RenderOrderEmail. An email-theme plugin granted emails:customize sets that domain up:

  1. SendingDomainRegister with { "domain": "shop.example.com" } registers it with Novinzo's mail provider and answers its status: dkim is a TXT record and returnPath a CNAME record, each a host and value to publish, with verified for each and for the whole domain.
  2. Show the seller both records to publish at their DNS host.
  3. SendingDomainVerify has the mail provider check them now and answers the new status. DNS changes can take a while to appear, so let the seller retry.

Once both records are verified, every order confirmation of the store goes from orders@<domain>, named after the store, whether or not a plugin writes it. SendingDomainGet answers the status without asking the mail provider, or null. SendingDomainRemove deletes the domain from the mail provider and the store: the email goes from Novinzo's sender, in Novinzo's words, again.

Novinzo has the mail provider check every domain's records again about once a day, and saves what it finds as SendingDomainVerify does. A domain whose records were taken down stops counting as verified, and one the mail provider no longer has is removed from the store. A domain no check has read for 7 days counts as unverified until one does. While a domain is not verified, the store's order emails go from Novinzo's sender, in Novinzo's words.

A store has one sending domain, and a domain belongs to one store. Registering the store's own domain again answers it as it stands. Registration refuses Novinzo's own domains and the domains under or above them with SendingDomainPlatformDomainError, another store's domain with SendingDomainTakenError (unless that store registered it over 72 hours ago and neither record was ever verified: then the registration takes it over with new records for the new store to publish, and the records the earlier store was given verify nothing any more), a second domain with SendingDomainAlreadySetError, and one the mail provider will not send from, such as a public mailbox provider's, with SendingDomainRefusedError. SendingDomainsUnavailableError means the mail provider could not be reached; nothing was registered, so try again. The store's owner can call these RPCs too; its other team members can only read the status.

Handle PermissionDenied

PermissionDenied means access was refused. It does not distinguish a withheld grant from a failed authorization lookup.

Apply these rules:

  • Degrade optional enrichment only when omission preserves correctness and authorization.
  • Keep required workflows closed. Display the required grant to sellers instead of pretending the operation succeeded.
  • Do not retry automatically. A later call reads the current installation and grants again.

Never degrade credential authentication, stock enforcement or required checkout writes into successful behavior.

FailureMeaning
PluginInvocationRejectedInvalid or expired token. Invocation tokens last 15 minutes.
InvalidRequestThe RPC payload failed decoding.
OrderNotFound, OrderDatabaseError, InternalServerErrorThe operation's own failures.
Die, Interrupt, protocol DefectServer defect, interruption or protocol failure.
Non-success HTTP, network or JSON failureTransport failure, not a seller grant decision.

Next steps

On this page