Your database
Keep transactions, subscriptions and entitlements in your own Convex, Supabase, Neon, Turso or Cloudflare D1 database, or any backend through a signed endpoint.
How it works
Instead of calling the API to check who paid, let Munim keep a copy of your billing data in your own database. Your app then checks entitlements with its own queries, with no extra network call and no webhook server.
- On connect, Munim backfills everything you already have.
- After that, every change (a payment, a refund, a renewal, a store notification) is written within moments. If your database is unreachable, changes queue up and are retried with backoff.
- Rows are upserts by key, so a resend never duplicates anything.
- Credentials are sealed at rest and never shown again.
Connect a database
In the dashboard under Integrations, or with a full-access key (read-only keys can’t). Signing in with Convex or Supabase needs a person in the dashboard; with a key, send a token instead.
curl https://billing-sandbox-api.munimtech.com/v1/integrations \
-H "Authorization: Bearer $MUNIM_BILLING_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"provider": "supabase",
"credentials": { "access_token": "sbp_…", "project_ref": "abcdefghijklmnopqrst" }
}'const sync = await munim.integrations.create({
provider: 'supabase',
credentials: { access_token: 'sbp_…', project_ref: 'abcdefghijklmnopqrst' },
})
// sync.status: 'backfilling', then 'active'providerstringrequiredconvex,supabase,neon,turso,d1orendpoint.credentialsobjectrequired- The provider's fields, below.
project_idstring- Only sync this project's rows. Default: everything.
namestring- A label for it.
GET /v1/integrations lists your syncs plus every provider’s credential fields and setup files. An account can have up to 5.
Convex
Billing tables in your Convex app, updated in real time; your queries check entitlements with a normal index lookup. Add two files and deploy (npx convex deploy) before connecting. Munim calls the internal mutation munimBilling:sync with your deploy key, so nobody else can.
// convex/schema.ts: add these tables to your defineSchema({ ... })
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
// ...your tables
munimTransactions: defineTable({ munimId: v.string(), appUserId: v.union(v.string(), v.null()), status: v.string(), data: v.any() })
.index("by_munimId", ["munimId"])
.index("by_appUserId", ["appUserId"]),
munimSubscriptions: defineTable({ munimId: v.string(), appUserId: v.union(v.string(), v.null()), status: v.string(), data: v.any() })
.index("by_munimId", ["munimId"])
.index("by_appUserId", ["appUserId"]),
munimSubscribers: defineTable({ appUserId: v.string(), activeEntitlements: v.array(v.string()), data: v.any() })
.index("by_appUserId", ["appUserId"]),
});// convex/munimBilling.ts: Munim Billing writes your billing data here.
// Keep the file and function names: Munim calls munimBilling:sync.
import { v } from "convex/values";
import { internalMutation, type QueryCtx } from "./_generated/server";
export const sync = internalMutation({
args: {
ping: v.optional(v.boolean()),
transactions: v.optional(v.array(v.any())),
subscriptions: v.optional(v.array(v.any())),
subscribers: v.optional(v.array(v.any())),
},
handler: async (ctx, args) => {
if (args.ping) return { ok: true, version: 1 };
for (const row of args.transactions ?? []) {
const doc = { munimId: row.id, appUserId: row.app_user_id ?? null, status: row.status, data: row };
const existing = await ctx.db.query("munimTransactions").withIndex("by_munimId", (q) => q.eq("munimId", row.id)).unique();
if (existing) await ctx.db.replace(existing._id, doc);
else await ctx.db.insert("munimTransactions", doc);
}
for (const row of args.subscriptions ?? []) {
const doc = { munimId: row.id, appUserId: row.app_user_id ?? null, status: row.status, data: row };
const existing = await ctx.db.query("munimSubscriptions").withIndex("by_munimId", (q) => q.eq("munimId", row.id)).unique();
if (existing) await ctx.db.replace(existing._id, doc);
else await ctx.db.insert("munimSubscriptions", doc);
}
for (const row of args.subscribers ?? []) {
const doc = { appUserId: row.app_user_id, activeEntitlements: row.active_entitlements ?? [], data: row };
const existing = await ctx.db.query("munimSubscribers").withIndex("by_appUserId", (q) => q.eq("appUserId", row.app_user_id)).unique();
if (existing) await ctx.db.replace(existing._id, doc);
else await ctx.db.insert("munimSubscribers", doc);
}
return { ok: true };
},
});
/** In your own queries and mutations: does this user have the entitlement (e.g. "pro")? */
export async function hasEntitlement(ctx: QueryCtx, appUserId: string, entitlement: string) {
const row = await ctx.db.query("munimSubscribers").withIndex("by_appUserId", (q) => q.eq("appUserId", appUserId)).unique();
return row?.activeEntitlements.includes(entitlement) ?? false;
}// convex/notes.ts
import { query } from "./_generated/server";
import { hasEntitlement } from "./munimBilling";
export const canExport = query({
args: {},
handler: async (ctx) => {
const user = await ctx.auth.getUserIdentity();
return user ? await hasEntitlement(ctx, user.subject, "pro") : false;
},
});deploy_keystringrequired- prod:happy-otter-123|eyJ… from the Convex dashboard → your production deployment → Settings → Deploy keys.
urlstring- Only if the deployment isn't at <deployment>.convex.cloud (EU region or a custom domain).
In the dashboard you can also sign in with Convex instead of pasting a key. That creates a deploy key named “Munim Billing sync” on the deployment you pick; delete it in Convex to disconnect.
Supabase
Tables in your Supabase Postgres (public.munim_*), created for you, with row-level security on and no policies, so only the service role reads them. Read them from your server or edge functions.
access_tokenstringrequired- sbp_… from supabase.com/dashboard/account/tokens. Munim uses it to create the tables and write rows.
project_refstringrequired- The project's ref (the dashboard lets you pick it after pasting the token).
Or sign in with Supabase in the dashboard: Munim asks for database read/write and read-only project access.
Neon
Tables in your Neon Postgres (public.munim_*), written over Neon’s HTTPS SQL API.
connection_stringstringrequired- postgresql://user:password@ep-….neon.tech/neondb from Neon console → Connect, for a role that can create tables in public.
Turso
Tables in your Turso (libSQL / SQLite) database, written over Turso’s HTTP API. Times are milliseconds and entitlements are JSON text.
urlstringrequired- libsql://your-db-your-org.turso.io (turso db show <name> --url).
auth_tokenstringrequired- turso db tokens create <name>. A full-access token: Munim creates the munim_* tables.
Cloudflare D1
Tables in a D1 database (SQLite), written over Cloudflare’s API. Read them from your Worker with a D1 binding.
account_idstringrequired- Cloudflare dashboard → Workers & Pages → Account ID.
database_idstringrequired- From wrangler d1 list, or the database's page.
api_tokenstringrequired- My Profile → API Tokens → a token with Account · D1 · Edit.
Any backend: a signed endpoint
For any other database or backend, give Munim an HTTPS URL. It POSTs JSON batches signed like webhooks; you verify, write the rows wherever you like, and answer 2xx. A ping with empty lists comes first, on connect and on every test.
urlstringrequired- https://api.example.com/munim/sync
The response has signing_secret (whsec_…), shown once: store it as MUNIM_BILLING_SYNC_SECRET. POST /v1/integrations/:id/rotate_secret makes a new one; the old one stops working at once.
// Any backend: Munim POSTs your billing data to this route as it changes.
// Verify the signature, upsert each row by its key, answer 2xx.
import { verifyWebhook } from "munim-billing";
export async function POST(request: Request) {
const raw = await request.text();
// Same scheme as webhooks: Munim-Signature: t=…,v1=HMAC-SHA256(secret, `${t}.${raw}`)
await verifyWebhook(raw, request.headers.get("munim-signature"), process.env.MUNIM_BILLING_SYNC_SECRET!);
const batch = JSON.parse(raw); // { object: "munim.sync", version: 1, ping, transactions, subscriptions, subscribers }
if (batch.ping) return Response.json({ ok: true });
for (const t of batch.transactions) await db.upsert("munim_transactions", t.id, t);
for (const s of batch.subscriptions) await db.upsert("munim_subscriptions", s.id, s);
// One row per app_user_id: active_entitlements is what they have right now ("pro", …).
for (const u of batch.subscribers) await db.upsert("munim_subscribers", u.app_user_id, u);
return Response.json({ ok: true });
}{
"object": "munim.sync",
"version": 1,
"ping": false,
"sent_at": 1764460800000,
"transactions": [ { "id": "txn_…", "source": "web", "status": "completed", "amount": 999, … } ],
"subscriptions": [ { "id": "sub_…", "status": "active", "mrr": 999, … } ],
"subscribers": [
{
"app_user_id": "user_123",
"customer_id": "ctm_…",
"active_entitlements": ["pro"],
"entitlements": { "pro": { "active": true, "expires_at": 1767139200000, "source": "web", … } },
"updated_at": 1764460800000
}
]
}Tables
Three tables, always the latest state. Money is in cents. Every table also keeps the whole row in data and the time it was written in synced_at. Rows cover web purchases and App Store / Google Play purchases alike (source).
| Column type | Postgres (Supabase, Neon) | SQLite (Turso, D1) |
|---|---|---|
| text | text | text |
| money | bigint | integer |
| time | timestamptz | integer (ms) |
| boolean | boolean | integer (0 / 1) |
| list | text[] | JSON text |
| object (data, entitlements) | jsonb | JSON text |
munim_transactions
Every payment. Key id. Columns: id, created_at (time), source, status, kind, project_id, product_id, price_id, customer_id, customer_email, app_user_id, currency, amount, tax, fee, net, refunded_amount (money), subscription_id, environment.
munim_subscriptions
Every subscription. Key id. Columns: id, created_at (time), source, status, project_id, product_id, price_id, customer_id, customer_email, app_user_id, currency, unit_amount, interval, mrr (money), current_period_end (time), cancel_at_period_end (boolean), canceled_at (time), environment.
munim_subscribers
One row per app_user_id (the key): customer_id, active_entitlements (list, e.g. ["pro"]), entitlements (object: each entitlement’s active, expires_at, product_id, source, will_renew), updated_at (time).
Postgres and SQLite tables get an index on app_user_id. In Convex the tables are munimTransactions, munimSubscriptions and munimSubscribers, with the row in data.
-- Supabase / Neon (Postgres)
select 'pro' = any(active_entitlements) as is_pro
from public.munim_subscribers
where app_user_id = $1;-- Turso / Cloudflare D1 (SQLite): arrays and objects are JSON text
select exists (
select 1 from munim_subscribers, json_each(munim_subscribers.active_entitlements)
where app_user_id = ?1 and json_each.value = 'pro'
) as is_pro;Status and upkeep
| Status | Meaning |
|---|---|
needs_setup | The target isn't ready: the Convex file isn't deployed, or the endpoint doesn't answer 2xx. Fix it, then test. |
backfilling | Copying what you already have. |
active | Up to date, writing changes as they happen. |
paused | Not writing; changes keep collecting and go out on resume. |
error | Writes are failing; see last_error. Munim keeps retrying. |
| Call | Does |
|---|---|
POST /v1/integrations/:id/test | Checks Munim can reach the database and the tables or sync function are there. A needs_setup sync starts its backfill once this passes. |
POST /v1/integrations/:id/resync | Sends every row again from the start, for example after the tables were wiped. |
POST /v1/integrations/:id/pause | Stops writing. |
POST /v1/integrations/:id/resume | Starts again, with everything that changed while paused. |
POST /v1/integrations/:id/delete | Stops syncing and forgets the credentials. Tables and rows already written stay. |
counts, pending, last_synced_at and last_error, so you can see at a glance whether it’s keeping up.