npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@umohpyro/better-auth-nuvion

v0.7.0

Published

Better Auth plugin for Nuvion: hosted checkout, multi-level fee splits and child merchants. Beta, unofficial.

Readme

@umohpyro/better-auth-nuvion

npm license types

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 zod

npm · 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 idempotencyKey and a double-click or a retry returns the first payment instead of creating a second checkout. Payments that will never be paid end as failed or expired, 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 organization plugin for tenancy and @better-auth/api-key for 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 zod

One 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/webhook

Keep 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.legs

Request 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

  1. Hierarchy. POST /nuvion/organization/parent sets an organization's parent. Cycles and depth above 3 are rejected.

  2. Bind to Nuvion. POST /nuvion/organization/bind maps an organization to a Nuvion entityId and accountId.

  3. Fee rules. POST /nuvion/fee-rule is 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" }
  4. Charge. POST /nuvion/payments quotes the split and creates a hosted checkout:

    { "organizationId": "org_merchant", "amountMinor": 10000, "currency": "GBP", "redirectUrl": "https://shop.example.com/done" }

    The response contains checkoutUrl, chargedMinor and the computed legs. With bearer: "payer", chargedMinor is the base plus the fee and the merchant nets the base.

  5. Settle. When Nuvion sends inflows.completed, the plugin verifies the signature, checks the amount against the quote, and issues one book-transfer per beneficiary from the merchant's account. Nuvion's outflows.* events move each leg to completed or failed.

  6. Recover. POST /nuvion/payments/retry re-runs failed or stuck legs.

  7. Counterparties are created for you. A book transfer needs a counterparty and a book-transfer payment 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's nuvion_ban, and saves the ids in nuvionDestination. 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 the counterparty option (email, relationship, address); the defaults are placeholders.

  8. Refund. POST /nuvion/payments/refund cancels 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/list returns payments with their legs, newest first. With organizationId it lists that organization's (admins only); without it, the caller's own. Optional status (comma-separated), limit (max 100) and offset.
  • 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 still sent in that organization and its descendants, and settles each the way its webhook would. Call it from a cron; repeating it is safe. A sent leg without a Nuvion transfer id (Nuvion answered a duplicate reference) cannot be looked up and is counted as unresolved.

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. Set confirmEvents: false to trust a valid signature alone.
  • The webhook only asks for a retry when a retry can help. 503 for a temporary failure (Nuvion unreachable, 5xx, 429); everything else is acknowledged with 200 and logged, and a setup problem (for example an organization that is not bound) marks that leg failed so 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 cronSecret and call GET|POST /nuvion/cron/reconcile with Authorization: Bearer <secret> from Vercel Cron, GitHub Actions or any scheduler. It settles sent legs and recovers a checkout that settled while its webhook was lost.
  • Rebinding. bind with replace: true changes an organization's Nuvion account while it has no open payments, and forgets the saved counterparties.
  • Per-tenant credentials. apiKey: (organizationId) => key and webhookSecret: (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 2xx is 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 200 for events it cannot match (unknown payment or leg, event types it ignores) and 401 only for a bad signature. It answers 5xx only when its own processing throws, so alert on 5xx from /nuvion/webhook: repeated failures cost you the endpoint.
  • Order. Not guaranteed. A retried outflows.created arrived after outflows.completed for the same transfer. The plugin ignores created, 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) answers 400 and also emits outflows.created then outflows.failed; its reference is used up. The plugin marks the leg failed from the 400, fires onLegFailed once, 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.cancelled is handled as a failure but cannot be provoked. outflows.refunded is 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 typecheck

npm 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.completed splitting the payment into real book transfers; their real outflows.completed webhooks 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 real outflows.created and outflows.failed webhooks, the payment went partial, and the retry used a new reference. A forced 500 was 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.completed delivered 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

License

MIT