@umohpyro/better-auth-nuvion
v0.7.0
Published
Better Auth plugin for Nuvion: hosted checkout, multi-level fee splits and child merchants. Beta, unofficial.
Maintainers
Readme
@umohpyro/better-auth-nuvion
Accept payments with Nuvion from your Better Auth app, and split every payment across your platform, resellers and merchants automatically.
npm install @umohpyro/better-auth-nuvion better-auth zod
pnpm add @umohpyro/better-auth-nuvion better-auth zod
yarn add @umohpyro/better-auth-nuvion better-auth zod
bun add @umohpyro/better-auth-nuvion better-auth zodnpm · Documentation · Live example · Example source
- Multi-level merchants. Organizations form a hierarchy of one to three levels: a lone merchant, a merchant under a platform, or merchant, reseller and platform. Each payment cascades child to parent. See Choosing a structure.
- Two ways to pay. An Open Banking hosted checkout (GBP, EUR) or an Interac e-Transfer request emailed to the payer (CAD). See Interac.
- Safe to repeat. Pass an
idempotencyKeyand a double-click or a retry returns the first payment instead of creating a second checkout. Payments that will never be paid end asfailedorexpired, with hooks. - Flexible fees. Per-merchant flat fee, basis points, or both, with a minimum and a cap. The payer or the merchant can bear the fee.
- Exact money math. Integer minor units only. Splits always sum to the amount charged, and rounding remainders go to the platform.
- Safe by construction. Signed webhooks (HMAC-SHA256, constant-time, replay window), event de-duplication, and an idempotent leg executor that retries without double-paying.
- Built on Better Auth. Uses the
organizationplugin for tenancy and@better-auth/api-keyfor developer keys. Tables are created by Better Auth's schema migration. - Provider-agnostic engine. The split engine knows nothing about Nuvion; the Nuvion integration is one provider behind a two-method interface.
Beta (0.x). Every release is in the changelog, with what to read before you upgrade. Tested on SQLite, Postgres, MariaDB and the Drizzle and Prisma adapters, and end to end against Nuvion's test environment, from a paid hosted checkout to settled and refunded payments driven by real signed webhooks. The money-moving half is also verified on Nuvion production (book transfers and a refund reversal, settled by real signed webhooks); the hosted-checkout half is not yet. See Going to production and Status and limits.
Install
npm install @umohpyro/better-auth-nuvion better-auth zod
pnpm add @umohpyro/better-auth-nuvion better-auth zod
yarn add @umohpyro/better-auth-nuvion better-auth zod
bun add @umohpyro/better-auth-nuvion better-auth zodOne package, four entry points:
| Import | What |
|---|---|
| @umohpyro/better-auth-nuvion | The Better Auth plugin: schema, endpoints, webhook receiver |
| @umohpyro/better-auth-nuvion/client | The typed client plugin |
| @umohpyro/better-auth-nuvion/react | A drop-in admin view of payments and legs (optional; needs React 18+) |
| @umohpyro/better-auth-nuvion/engine | The provider-agnostic split engine (fee math, hierarchy rules, ledger, leg executor) for use on its own |
ESM and CommonJS are both supported. It is an independent project under the author's npm scope (@umohpyro), not an official Nuvion product. If Nuvion adopts it, the package may move to Nuvion's scope, with a deprecation notice here.
Setup
import { betterAuth } from "better-auth";
import { organization } from "better-auth/plugins";
import { apiKey } from "@better-auth/api-key";
import { nuvion } from "@umohpyro/better-auth-nuvion";
export const auth = betterAuth({
plugins: [
organization(),
apiKey(),
nuvion({
apiKey: process.env.NUVION_API_KEY!, // your Nuvion secret key
webhookSecret: process.env.NUVION_WEBHOOK_SECRET!, // nv_wsk_...
baseUrl: "https://api.nuvion.dev", // default: Nuvion's test environment. Production: "https://api.nuvion.co"
webhookToleranceMs: 5 * 60_000, // optional replay window
}),
],
});Upgrading from 0.1.x? 0.2 adds one optional column, nuvionPayment.userId. Run your usual migration. If it fails on Postgres with type "nuvionPayment_userId_idx" does not exist, you are on 0.2.0 to 0.2.2 with an older Better Auth CLI: upgrade to 0.2.3, or add the column yourself (ALTER TABLE "nuvionPayment" ADD COLUMN "userId" text;). See Upgrading.
Create the tables with Better Auth's CLI (npx @better-auth/cli migrate, or generate for Prisma and Drizzle). The plugin adds parentOrganizationId to organization and six nuvion* tables; amounts and timestamps are bigint so they do not overflow on Postgres. Then register this webhook URL in Nuvion and subscribe to inflows.completed, outflows.completed, outflows.failed and outflows.cancelled:
https://your-app.example.com/api/auth/nuvion/webhookKeep keys in the environment. Never commit them.
Typed client
import { createAuthClient } from "better-auth/client";
import { organizationClient } from "better-auth/client/plugins";
import { nuvionClient } from "@umohpyro/better-auth-nuvion/client";
const authClient = createAuthClient({ plugins: [organizationClient(), nuvionClient()] });
const { data } = await authClient.nuvion.payments({
organizationId: "org_merchant",
amountMinor: 10_000,
currency: "GBP",
redirectUrl: "https://shop.example.com/done",
});
// data.checkoutUrl, data.chargedMinor, data.legsRequest bodies are typed from the server schema; a wrong type fails tsc. Other calls: authClient.nuvion.organization.parent, .organization.bind, .feeRule, .payments.retry.
How it works
Hierarchy.
POST /nuvion/organization/parentsets an organization's parent. Cycles and depth above 3 are rejected.Bind to Nuvion.
POST /nuvion/organization/bindmaps an organization to a NuvionentityIdandaccountId.Fee rules.
POST /nuvion/fee-ruleis called by an admin of the parent organization. The rule is what the parent takes from the child's payments:{ "organizationId": "org_merchant", "flatMinor": 0, "bps": 300, "minMinor": 50, "capMinor": 5000, "bearer": "merchant" }Charge.
POST /nuvion/paymentsquotes the split and creates a hosted checkout:{ "organizationId": "org_merchant", "amountMinor": 10000, "currency": "GBP", "redirectUrl": "https://shop.example.com/done" }The response contains
checkoutUrl,chargedMinorand the computed legs. Withbearer: "payer",chargedMinoris the base plus the fee and the merchant nets the base.Settle. When Nuvion sends
inflows.completed, the plugin verifies the signature, checks the amount against the quote, and issues onebook-transferper beneficiary from the merchant's account. Nuvion'soutflows.*events move each leg tocompletedorfailed.Recover.
POST /nuvion/payments/retryre-runs failed or stuck legs.Counterparties are created for you. A book transfer needs a counterparty and a
book-transferpayment detail on the sending entity. The plugin creates the pair the first time a transfer needs it (and for refund reversals), using the receiving organization's name and its account'snuvion_ban, and saves the ids innuvionDestination.POST /nuvion/organization/destinations { organizationId }does it ahead of time for that organization and all its ancestors and reports a problem (for example two organizations bound to the same Nuvion account, which cannot transfer to each other) before a customer pays. Set the contact details Nuvion requires on these counterparties with thecounterpartyoption (email,relationship,address); the defaults are placeholders.Refund.
POST /nuvion/payments/refundcancels unsent legs and adds a reversal leg for every moved leg (beneficiary back to the paying org), so the merchant account is made whole. It does not pay the customer back; Nuvion documents no refund API for funding-session inflows. Each beneficiary-to-origin pair needs a counterparty, like the forward legs.
Hooks
Run your own code when a payment changes state. Hooks are awaited after the change is saved, fire once per change, and a hook that throws is logged and ignored, so it cannot fail a webhook. A crash between the save and the call loses that call, so make hooks idempotent.
nuvion({
// ...
hooks: {
onPaymentSettled: async ({ payment, legs }) => { await grantAccess(payment.userId, payment.id); },
onPaymentPartial: async ({ payment }) => { await alertOps(payment.id); },
onLegFailed: async ({ payment, leg }) => { console.warn(leg.error); },
onRefunded: async ({ payment }) => { /* reverse what you granted */ },
onEntityUpdated: async ({ entityId, status }) => { if (status === "approved") await createAccountsAndBind(entityId); },
},
});Server-to-server calls (API keys)
The payment endpoints use the Better Auth session. Turn on enableSessionForAPIKeys in the apiKey plugin and a request with an x-api-key header is treated as a request by the key's owner, so a backend can charge and list without a cookie. The owner must be an admin of the organization, as for a browser session.
plugins: [organization(), apiKey({ enableSessionForAPIKeys: true }), nuvion({ /* ... */ })]Customers without an organization
Set defaultOrganizationId and any signed-in user can call POST /nuvion/payments without an organizationId. The payment is charged to that organization (your platform account), recorded with the payer's userId, and split by the fee rules above it, if any. Without the option, organizationId is required and the caller must administer it.
Listing, reading and reconciling
GET /nuvion/payments/listreturns payments with their legs, newest first. WithorganizationIdit lists that organization's (admins only); without it, the caller's own. Optionalstatus(comma-separated),limit(max 100) andoffset.GET /nuvion/payments/get?paymentId=returns one payment and its legs, to its payer or an admin of its organization.POST /nuvion/payments/reconcile { organizationId }asks Nuvion for the state of every leg stillsentin that organization and its descendants, and settles each the way its webhook would. Call it from a cron; repeating it is safe. Asentleg without a Nuvion transfer id (Nuvion answered a duplicate reference) cannot be looked up and is counted asunresolved.
Admin view
import { PaymentsAdmin } from "@umohpyro/better-auth-nuvion/react";
<PaymentsAdmin api={authClient.nuvion} organizationId={orgId} />A table of payments with leg progress, a Retry button on partial payments, and a button that runs the reconcile above. It refreshes every 15 seconds (pollMs). PaymentsTable is the same table without the fetching, for your own data loading.
It renders plain elements with class names and no inline styles, so it works under a strict CSP and you decide how it looks. Import the optional default look, or skip it and style the classes yourself:
import "@umohpyro/better-auth-nuvion/react.css"; // optional; every rule is zero-specificity, so yours win
<PaymentsAdmin
api={authClient.nuvion}
organizationId={orgId}
classNames={{ button: "rounded-full border px-3 py-1", status: "font-semibold" }} // added to the defaults
labels={{ retry: "Try again" }}
renderActions={(payment) => <a href={`/orders/${payment.id}`}>Open</a>}
/>unstyled drops the default class names so only yours apply. Colours and spacing are --pay-* CSS variables. Rows and status cells carry data-status. Everything the server sends is rendered as text, never as HTML. See Styling the admin view for the full list of parts and variables.
Production safety
- Events are confirmed with Nuvion before the plugin acts (
confirmEvents, on by default). An inflow must match a settled funding session of ours (reference, amount, currency); a transfer event is settled from Nuvion's own record of the transfer. SetconfirmEvents: falseto trust a valid signature alone. - The webhook only asks for a retry when a retry can help.
503for a temporary failure (Nuvion unreachable, 5xx, 429); everything else is acknowledged with200and logged, and a setup problem (for example an organization that is not bound) marks that legfailedso it can be retried. Failing every retry would get the webhook blacklisted. - The split is fixed at checkout. Legs are saved when the payment is created, so a rule or parent change while a customer is paying does not change what that payment pays out.
- Scheduled reconcile. Set
cronSecretand callGET|POST /nuvion/cron/reconcilewithAuthorization: Bearer <secret>from Vercel Cron, GitHub Actions or any scheduler. It settlessentlegs and recovers a checkout that settled while its webhook was lost. - Rebinding.
bindwithreplace: truechanges an organization's Nuvion account while it has no open payments, and forgets the saved counterparties. - Per-tenant credentials.
apiKey: (organizationId) => keyandwebhookSecret: (tenant) => secret(webhook URL/nuvion/webhook/<tenant>) for apps where each tenant is its own Nuvion customer.
See Webhooks and Going to production.
Fee cascade
A rule on organization X is what X's parent takes from money flowing through X. For a merchant under a reseller under the platform, with 3% on the merchant and 50% on the reseller, a 10,000 payment gives the merchant 9,700, the reseller 150 and the platform 150. Fees round down, so remainders accumulate at the platform. This is property-tested to sum exactly.
Failure semantics
Nuvion has no atomic multi-recipient settlement, so each leg is its own transfer. The executor is built for that:
| Situation | Behavior |
|---|---|
| Duplicate or replayed webhook | Ignored by event id and by payment state |
| Amount differs from the quote | Not split |
| One leg rejected (for example insufficient funds) | Payment becomes partial; retry re-issues only that leg under a new reference |
| Timeout or 5xx | Same reference reused; a 409 from Nuvion means the transfer already exists |
| Late event for an older attempt | Ignored |
| Refund after split | Unsent legs cancelled, reversal legs created for moved legs |
Webhook delivery
How Nuvion delivers events, as observed in its test environment, and what the plugin does about it:
- Retries. A delivery that does not get a
2xxis retried twice, about 1 and 2 minutes later. Each attempt keeps the event id but carries a new timestamp and a new signature, so the replay window applies per attempt. The plugin de-duplicates by event id. - Blacklisting. After 3 failed attempts within 24 hours Nuvion stops delivering to the endpoint until you reactivate it. The plugin answers
200for events it cannot match (unknown payment or leg, event types it ignores) and401only for a bad signature. It answers5xxonly when its own processing throws, so alert on5xxfrom/nuvion/webhook: repeated failures cost you the endpoint. - Order. Not guaranteed. A retried
outflows.createdarrived afteroutflows.completedfor the same transfer. The plugin ignorescreated, and a leg is only ever moved by its terminal events, matched by reference and attempt number, so a late event cannot move a leg backwards. - Rejected transfers. A transfer Nuvion refuses (for example
error_transfer_insufficient_funds) answers400and also emitsoutflows.createdthenoutflows.failed; its reference is used up. The plugin marks the leg failed from the400, firesonLegFailedonce, and treats the later failure event as already handled. The retry uses the next attempt number. - Cancelled and refunded. Transfers have no cancel endpoint and book transfers complete in seconds, so
outflows.cancelledis handled as a failure but cannot be provoked.outflows.refundedis documented as a card-network credit and does not identify a book transfer, so the plugin ignores it. Refunding a split payment is the reversal legs described above. - Fees. Nuvion does not charge for book transfers, so a leg costs the merchant account exactly its amount. A leg larger than the account balance is still rejected for insufficient funds.
Changelog
What changed in each version, and what to read before you upgrade: CHANGELOG.md.
Development
npm install
npm test # builds, then runs the tests (in-memory, SQLite, PGlite); no network or keys needed
npm run typechecknpm run build bundles the single package with tsup into dist/ (ESM, CommonJS and .d.ts for index, client and engine). The integration tests run the same scenarios against Better Auth's in-memory adapter, SQLite (node:sqlite) and Postgres (PGlite), using migrations generated from the plugin schema, with a simulated Nuvion API.
Set these to run the same integration scenarios against real servers (each is skipped when its variable is unset): NUVION_TEST_PG (a Postgres URL, schema public is dropped for each test), NUVION_TEST_MYSQL (a MySQL URL, database nuvion_test is dropped for each test), NUVION_TEST_DRIZZLE_SCHEMA with NUVION_TEST_PG (a Drizzle schema from npx auth generate, tables created with drizzle-kit push), and NUVION_TEST_PRISMA_DIR with NUVION_TEST_PG (a folder with a pushed schema.prisma, its generated client with importFileExtension = "ts", and @prisma/adapter-pg). MySQL needs explicit_defaults_for_timestamp on (the MySQL 8 default) and table names kept as given; Windows servers lowercase table names by default, which fails Better Auth's schema check for any mixed-case plugin table, so set lower_case_table_names=2 there.
Status and limits
Verified
Databases: SQLite, Postgres (in memory and a real server over TCP), MariaDB 10.4 (configured like MySQL 8), and the Drizzle and Prisma 7 adapters on Postgres, including 8 simultaneous deliveries of the same inflow producing exactly one split.
Against Nuvion's test environment, with real requests: a paid hosted checkout; the real signed
inflows.completedsplitting the payment into real book transfers; their realoutflows.completedwebhooks settling the legs; counterparty and payment-detail creation; reconcile settling legs from Nuvion's transfer status; and a refund whose reversal transfers settled through real webhooks.Failures and delivery: a split larger than the merchant's balance was refused with
400, Nuvion then delivered realoutflows.createdandoutflows.failedwebhooks, the payment wentpartial, and the retry used a new reference. A forced500was retried about 60 seconds later with the same event id, and out-of-order delivery was observed. Both are handled as described under Webhook delivery.Confirm before acting: a real settled funding session is confirmed, a wrong amount, reference, currency or unknown session is refused, and a real finished transfer is found by its reference.
On Nuvion production (2026-11-20), NGN, between two accounts of one entity: a split leg of ₦1.00 sent as a book transfer, its signed
outflows.completeddelivered and confirmed against Nuvion's own record, and the payment settled; then a refund whose reversal transfer settled the same way. Balances ended exactly where the two transfers put them. The pay-in was simulated, because NGN has no hosted checkout.Interac, against Nuvion's test environment: a CAD request is created from the plugin's own code, Nuvion accepts its fields, and a refresh moves it to
processing. The payer accepting and settlement are tested end to end against a simulated Nuvion.
Next to verify: a real hosted checkout payment on production (Open Banking needs a GBP or EUR payer), MySQL 8 or MariaDB on Linux, the Drizzle and Prisma adapters on MySQL or SQLite, and a real outflows.cancelled or outflows.refunded for a book transfer (Nuvion's test environment offers no way to produce either).
Not built: mobile money and stablecoin funding, mapping refund events to payments, paying a customer back on refund, subscriptions, and multi-currency splits. Amounts use JavaScript numbers, which is safe for fiat. The status page says why.
A book transfer also produces an inflows.completed on the receiving account, with unique_reference set to book-transfer-inflow-for-<our reference>; the plugin ignores it.
Security and support
- Report a vulnerability privately, as described in SECURITY.md. Please do not open a public issue for one.
- How keys and data are handled: Security. Versioning and what is supported: Support and versioning.
License
MIT
