Custom Stores

Example Server

A complete custom store server in two files: a checkout endpoint that creates checkouts for Superwall paywalls, and a webhook handler that reports purchases, renewals, cancellations and refunds.

This is a complete custom store integration in two files, with no dependencies:

  • server.ts is the same for every billing system. It verifies Superwall's checkout requests and sends events to Superwall.
  • billing.ts is the only file that knows your billing system. The version here talks to an imaginary provider called Acme Billing. You replace its two functions with calls to yours.

Do the quickstart first, so you have a store, a product and an API key.

What the server does

RouteCalled byWhat it does
POST /superwall/checkoutSuperwall, when a user taps a productCreates a checkout in your billing system and answers with its URL.
POST /billing/webhooksYour billing system, on every subscription changeTurns the webhook into an event and sends it to Superwall.

server.ts

server.ts
// A custom store server. Node 22.18 or later runs it as is: `node server.ts`
import { createHmac, timingSafeEqual } from "node:crypto"
import { createServer } from "node:http"
import { createCheckout, readBillingWebhook } from "./billing.ts"

const env = (name: string): string => {
  const value = process.env[name]
  if (!value) throw new Error(`Set ${name}`)
  return value
}

const SUPERWALL_API_KEY = env("SUPERWALL_API_KEY") // scope: custom_store_events:write
const CUSTOM_STORE_ID = env("SUPERWALL_CUSTOM_STORE_ID")
const CHECKOUT_SECRET = env("SUPERWALL_CHECKOUT_SECRET") // whsec_..., shown once
const SUPERWALL_API = process.env.SUPERWALL_API_URL ?? "https://api.superwall.com"

type Reply = { status: number; body: unknown }

// 1. Checkout endpoint: Superwall asks for a checkout URL when a user taps a product.

/** True when Superwall signed this request (Standard Webhooks) in the last five minutes. */
function isFromSuperwall(body: string, headers: Headers): boolean {
  const id = headers.get("webhook-id")
  const timestamp = headers.get("webhook-timestamp")
  const signatures = headers.get("webhook-signature")
  if (!id || !timestamp || !signatures) return false
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 5 * 60) return false

  const key = Buffer.from(CHECKOUT_SECRET.slice("whsec_".length), "base64")
  const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest()
  // During a secret rotation the header lists one signature per secret. Any may match.
  return signatures.split(" ").some((entry) => {
    const [version, value] = entry.split(",", 2)
    const candidate = Buffer.from(value ?? "", "base64")
    return (
      version === "v1" && candidate.length === expected.length && timingSafeEqual(candidate, expected)
    )
  })
}

async function handleCheckout(body: string, headers: Headers): Promise<Reply> {
  if (!isFromSuperwall(body, headers)) return { status: 401, body: { error: "invalid signature" } }
  const request = JSON.parse(body)

  const url = await createCheckout({
    productId: request.product_id,
    successUrl: request.success_url,
    cancelUrl: request.cancel_url,
    // Your billing system must hand these two back on every webhook for this subscription.
    metadata: {
      superwall_app_user_id: request.app_user_id,
      superwall_custom_transaction_id: request.custom_transaction_id,
    },
  })
  if (!url) return { status: 404, body: { error: `unknown product ${request.product_id}` } }
  return { status: 200, body: { url } }
}

// 2. Billing webhook: your billing system reports a change, and you report it to Superwall.

async function handleBillingWebhook(body: string, headers: Headers): Promise<Reply> {
  const result = readBillingWebhook(body, headers)
  if (result === "invalid_signature") return { status: 401, body: { error: "invalid signature" } }
  // Nothing Superwall needs to know about. Answer 2xx so it isn't sent again.
  if (result === "ignored") return { status: 200, body: { ignored: true } }

  const response = await fetch(`${SUPERWALL_API}/v2/custom-stores/${CUSTOM_STORE_ID}/events`, {
    method: "POST",
    headers: { authorization: `Bearer ${SUPERWALL_API_KEY}`, "content-type": "application/json" },
    body: JSON.stringify({ events: [result] }),
    signal: AbortSignal.timeout(20_000),
  })

  if (!response.ok) {
    // Nothing was recorded. Fail the delivery so your billing system sends it again:
    // the event_id makes the retry safe.
    console.error(`${result.event_id}: Superwall answered ${response.status}`)
    return { status: 502, body: { error: "not recorded, send again" } }
  }

  const [outcome] = (await response.json()).results
  if (outcome.status === "rejected") {
    // The event itself is wrong (unknown product, missing price, ...). A retry can't fix it.
    console.error(`${result.event_id}: rejected ${outcome.error.code}: ${outcome.error.message}`)
  }
  return { status: 200, body: outcome }
}

// 3. The HTTP server.

createServer(async (request, response) => {
  const chunks: Buffer[] = []
  for await (const chunk of request) chunks.push(chunk)
  // Keep the body byte for byte: both signatures are computed over it.
  const body = Buffer.concat(chunks).toString("utf8")
  const headers = new Headers(request.headers as Record<string, string>)

  let reply: Reply = { status: 404, body: { error: "not found" } }
  try {
    if (request.method === "POST" && request.url === "/superwall/checkout") {
      reply = await handleCheckout(body, headers)
    } else if (request.method === "POST" && request.url === "/billing/webhooks") {
      reply = await handleBillingWebhook(body, headers)
    }
  } catch (error) {
    console.error(error)
    reply = { status: 502, body: { error: "failed" } }
  }
  response.writeHead(reply.status, { "content-type": "application/json" })
  response.end(JSON.stringify(reply.body))
}).listen(Number(process.env.PORT ?? 8787))

billing.ts

Acme Billing stands for your billing system. It has a "create checkout" API that accepts metadata, and it signs its webhooks. Almost every billing system has both.

billing.ts
// The only file that knows your billing system. This one talks to an imaginary
// provider, "Acme Billing". Replace both functions with your provider's API.
import { createHmac, timingSafeEqual } from "node:crypto"

const ACME_API_KEY = process.env.ACME_API_KEY ?? ""
const ACME_WEBHOOK_SECRET = process.env.ACME_WEBHOOK_SECRET ?? ""
const ACME_API = process.env.ACME_API_URL ?? "https://api.acme-billing.example"
// Test keys report sandbox events, so a test purchase never counts as real revenue.
const ENVIRONMENT = ACME_API_KEY.startsWith("test_") ? "sandbox" : "production"

// Your billing system's plan for each Superwall product identifier.
const PLANS: Record<string, string> = {
  pro_monthly: "plan_monthly_999",
  pro_yearly: "plan_yearly_7999",
}
const PRODUCTS = Object.fromEntries(Object.entries(PLANS).map(([product, plan]) => [plan, product]))

/** Creates a hosted checkout and returns its URL, or undefined for a product you don't sell. */
export async function createCheckout(input: {
  productId: string
  successUrl: string
  cancelUrl: string
  metadata: Record<string, string>
}): Promise<string | undefined> {
  const plan = PLANS[input.productId]
  if (!plan) return undefined

  const response = await fetch(`${ACME_API}/checkouts`, {
    method: "POST",
    headers: { authorization: `Bearer ${ACME_API_KEY}`, "content-type": "application/json" },
    body: JSON.stringify({
      plan,
      success_url: input.successUrl,
      cancel_url: input.cancelUrl,
      // Stored on the subscription, so every later webhook carries it.
      metadata: input.metadata,
    }),
    signal: AbortSignal.timeout(8_000), // Superwall waits ten seconds for your answer.
  })
  if (!response.ok) throw new Error(`Acme refused the checkout: ${response.status}`)
  return (await response.json()).url
}

/** The Superwall event type for each Acme webhook. Anything else is ignored. */
const EVENT_TYPES: Record<string, string> = {
  "subscription.started": "initial_purchase",
  "subscription.renewed": "renewal",
  "subscription.cancel_scheduled": "cancellation",
  "subscription.cancel_removed": "uncancellation",
  "subscription.payment_failed": "billing_issue",
  "subscription.ended": "expiration",
  "payment.refunded": "refund",
}
const PRICED = new Set(["initial_purchase", "renewal", "refund"])

/** Verifies a webhook and turns it into a custom store event. */
export function readBillingWebhook(body: string, headers: Headers) {
  const expected = createHmac("sha256", ACME_WEBHOOK_SECRET).update(body).digest()
  const given = Buffer.from(headers.get("acme-signature") ?? "", "hex")
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    return "invalid_signature" as const
  }

  const webhook = JSON.parse(body)
  const type = EVENT_TYPES[webhook.type]
  const subscription = webhook.subscription
  const appUserId = subscription?.metadata?.superwall_app_user_id
  const productId = PRODUCTS[subscription?.plan]
  // Not a change Superwall tracks, or a subscription that wasn't sold through Superwall.
  if (!type || !appUserId || !productId) return "ignored" as const

  const ended = type === "expiration" || type === "refund"
  return {
    event_id: `acme_${webhook.id}`, // the same on every retry of this webhook
    type,
    app_user_id: appUserId,
    product_id: productId,
    subscription_id: subscription.id, // the same for the subscription's whole life
    transaction_id: subscription.latest_invoice_id, // changes every billing period
    custom_transaction_id: subscription.metadata.superwall_custom_transaction_id,
    environment: ENVIRONMENT,
    occurred_at: webhook.created_at, // when it happened, not when you forward it
    purchased_at: subscription.current_period_start,
    expires_at: ended ? null : subscription.current_period_end,
    period_type: subscription.in_trial ? "trial" : "normal",
    // Major units as a string, before tax: 999 cents is "9.99". "0" during a free trial.
    ...(PRICED.has(type) && {
      price: {
        amount: (webhook.amount_cents / 100).toFixed(2),
        currency: webhook.currency,
      },
    }),
  }
}

One webhook, start to finish

Acme sends this when a subscription renews:

{
  "id": "evt_01J9Y6Q3W0V7",
  "type": "subscription.renewed",
  "created_at": "2026-12-01T09:15:02Z",
  "amount_cents": 999,
  "currency": "USD",
  "subscription": {
    "id": "sub_4f1c",
    "plan": "plan_monthly_999",
    "latest_invoice_id": "inv_9a77",
    "current_period_start": "2026-12-01T09:15:00Z",
    "current_period_end": "2027-01-01T09:15:00Z",
    "in_trial": false,
    "metadata": {
      "superwall_app_user_id": "user_8812",
      "superwall_custom_transaction_id": "9f2c1d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f"
    }
  }
}

readBillingWebhook turns it into this event, and server.ts sends it:

{
  "event_id": "acme_evt_01J9Y6Q3W0V7",
  "type": "renewal",
  "app_user_id": "user_8812",
  "product_id": "pro_monthly",
  "subscription_id": "sub_4f1c",
  "transaction_id": "inv_9a77",
  "custom_transaction_id": "9f2c1d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f",
  "environment": "production",
  "occurred_at": "2026-12-01T09:15:02Z",
  "purchased_at": "2026-12-01T09:15:00Z",
  "expires_at": "2027-01-01T09:15:00Z",
  "period_type": "normal",
  "price": { "amount": "9.99", "currency": "USD" }
}

Adapt it to your billing system

You change two things in billing.ts.

Create the checkout

Call your billing system's "create checkout" API with:

PassFrom the requestWhy
The plan or price to sellproduct_id, through your own mappingThe paywall names a Superwall product.
Metadataapp_user_id and custom_transaction_idYour webhooks must carry both back. Put them where your billing system copies them to the subscription, so renewals carry them too.
The success URLsuccess_urlSends the customer back to the app after paying.
The cancel or back URLcancel_urlSends the customer back when they leave without paying.

Use app_user_id exactly as Superwall sent it. Don't replace it with your own user ID: the entitlement goes to the user that the events name.

Map the webhooks

Find the webhook your billing system sends for each change, and build the event:

When this happensSendPriceAccess
A subscription starts, including a free trialinitial_purchaseWhat was paid, "0" for a free trialGranted until expires_at
A new period is paidrenewalWhat was paidExtended to expires_at
The customer turns off auto-renewcancellationNoneContinues until expires_at
The customer turns auto-renew back onuncancellationNoneUnchanged
A renewal payment fails and is being retriedbilling_issueNoneContinues until expires_at
The subscription endsexpirationNoneEnds
The current period is refunded in fullrefundThe refunded amountEnds for good
A one-time purchasenon_renewing_purchaseWhat was paidGranted until expires_at, or for life with null

Three fields decide whether your integration is correct:

  • event_id must be the same when your billing system retries a webhook. Derive it from the webhook's own ID. Superwall never applies the same event_id twice, so retries are safe.
  • subscription_id must stay the same for the subscription's whole life. Superwall uses it to know that a renewal belongs to an earlier purchase.
  • occurred_at must be when the change happened in your billing system, never when you forwarded it. Superwall orders events by it, so a late webhook can't undo a newer one.

The events reference has every field and rule.

Billing systems with a guide

  • Paddle: follow the Paddle guide. It uses superwall/custom-store-paddle, a tested server for Paddle Billing.
  • Polar: create the checkout with POST /v1/checkouts/ and put the two values in metadata. Polar copies checkout metadata to the order and the subscription. Map order.paid to initial_purchase or renewal by its billing_reason, subscription.canceled to cancellation, subscription.uncanceled to uncancellation, subscription.past_due to billing_issue, subscription.revoked to expiration, and a full order.refunded to refund.

Run it

SUPERWALL_API_KEY=... \
SUPERWALL_CUSTOM_STORE_ID=4821 \
SUPERWALL_CHECKOUT_SECRET=whsec_... \
ACME_API_KEY=test_... \
ACME_WEBHOOK_SECRET=... \
node server.ts

It listens on port 8787. Superwall and your billing system both need to reach it over https://, so while you test, put it behind a tunnel such as cloudflared tunnel --url http://localhost:8787.

  1. 1

    Point Superwall at the checkout endpoint

    Open the custom store in the dashboard. In its Checkout section, click Set up checkout and enter https://<your server>/superwall/checkout. Superwall shows the signing secret (whsec_...) once. It's SUPERWALL_CHECKOUT_SECRET.

  2. 2

    Point your billing system at the webhook handler

    In your billing system, add https://<your server>/billing/webhooks as a webhook endpoint, subscribed to the subscription and refund events you mapped.

  3. 3

    Buy the product

    Add the product to a paywall, open it in your app as a test user, and pay with your billing system's test card. The server reports an initial_purchase, the paywall closes, and the user has the entitlement.

Before you go live

  • A refund ends the subscription for good. Superwall never restores a refunded subscription_id. Cancel the subscription in your billing system when you report a refund, so the customer isn't billed again. Partial refunds aren't supported, so don't report them.
  • Fail the webhook when Superwall didn't record the event. The example answers 502 on any error from Superwall, and your billing system sends the webhook again. Answer 2xx only for an event that was accepted, rejected or ignored.
  • Watch for rejected events. A rejection means the event is wrong, such as an unknown product_id. It won't fix itself, so alert on that log line.
  • Keep sandbox and production apart. Send environment: "sandbox" for test-mode purchases. The store's first production event starts its revenue reporting.
  • Limit the request body size. The example reads the whole body before it checks the signature. In production, refuse bodies over a few hundred kilobytes.
  • Report each subscription from one place. Don't send events for purchases that the App Store, Google Play, Stripe or RevenueCat integration already reports, or their revenue counts twice.

How is this guide?

On this page