Recipes
Copy-paste code for the common jobs, from a one-merchant checkout to a marketplace with fees, hooks and admin buttons.
Short, complete snippets for the things people build first. They assume the setup from Installation: the plugin on the server (auth) and the typed client (authClient). Server code can call every endpoint through auth.api with the request's headers, and client code through authClient.nuvion. Both check the same permissions.
Amounts are minor units
4_900 is £49.00. Every amount in the plugin is an integer in the currency's
smallest unit.
Charge for one thing
A server action that creates the checkout and sends the customer to Nuvion. The customer must be signed in, and the organization must be bound.
"use server";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
export async function buy(organizationId: string) {
const checkout = await auth.api.createPayment({
headers: await headers(),
body: {
organizationId,
amountMinor: 4_900,
currency: "GBP",
redirectUrl: "https://shop.example.com/thanks",
},
});
redirect(checkout.checkoutUrl);
}If you only ever sell for one organization, set defaultOrganizationId in the plugin options and leave organizationId out of the call.
nuvion({
apiKey: process.env.NUVION_API_KEY!,
webhookSecret: process.env.NUVION_WEBHOOK_SECRET!,
defaultOrganizationId: "org_shop",
});Make checkout safe to repeat
A customer double-clicks Pay, or your server retries after a timeout. Without help that creates two checkouts. Pass an idempotencyKey, such as the order id, and a repeat returns the first payment.
const checkout = await auth.api.createPayment({
headers: await headers(),
body: {
organizationId,
amountMinor: 4_900,
currency: "GBP",
redirectUrl: "https://shop.example.com/thanks",
idempotencyKey: order.id, // one key per order
},
});
// checkout.idempotentReplay is true when this was a repeatThe key is scoped to the signed-in user and the organization. Reusing it for a different amount answers 409. A repeat returns the same paymentId and checkout address, and Nuvion is asked for one checkout only.
Show a customer their payments
Without an organizationId, the list returns the signed-in user's own payments. Each payment comes with its legs.
import { headers } from "next/headers";
import { auth } from "@/lib/auth";
export default async function Orders() {
const { payments } = await auth.api.listPayments({
headers: await headers(),
query: {},
});
return (
<ul>
{payments.map((p) => (
<li key={p.id}>
{(p.chargedMinor / 100).toFixed(2)} {p.currency}: {p.status}
</li>
))}
</ul>
);
}For a merchant's view, pass query: { organizationId } (organization admins only), and status: "partial,pending" to filter.
Unlock something when it is paid
Hooks run after the payment's new state is saved. They can run more than once if Nuvion redelivers, so make them idempotent: write with an upsert keyed on the payment id.
nuvion({
apiKey: process.env.NUVION_API_KEY!,
webhookSecret: process.env.NUVION_WEBHOOK_SECRET!,
hooks: {
onPaymentSettled: async ({ payment }) => {
await db.entitlement.upsert({
where: { paymentId: payment.id },
create: { paymentId: payment.id, userId: payment.userId, active: true },
update: { active: true },
});
},
onRefunded: async ({ payment }) => {
await db.entitlement.updateMany({
where: { paymentId: payment.id },
data: { active: false },
});
},
},
});Do not unlock from the redirect page. The customer reaching redirectUrl proves nothing; onPaymentSettled fires only after Nuvion confirmed the money. More hooks: Hooks, listing and reconciliation.
Show the split before checkout
quote is the same function the plugin uses to fix the split. It is pure, so you can run it in a form, a test or a pricing page.
import { quote } from "@umohpyro/better-auth-nuvion/engine";
const rule = (organizationId: string, bps: number) => ({
organizationId,
flatMinor: 0,
bps,
bearer: "merchant" as const,
});
const { legs } = quote(10_000, [
{ organizationId: "merchant", rule: rule("merchant", 300) }, // the reseller takes 3%
{ organizationId: "reseller", rule: rule("reseller", 5000) }, // the platform takes half of that
{ organizationId: "platform" },
]);
// [ { organizationId: "merchant", amountMinor: 9700 },
// { organizationId: "reseller", amountMinor: 150 },
// { organizationId: "platform", amountMinor: 150 } ]The legs always add up to the amount charged. See Fees for flat fees, minimums, caps and who bears the fee.
Wait for the payment after the redirect
The customer can come back before the webhook lands. Poll the payment from the page they return to, and stop once it leaves pending.
"use client";
import { useEffect, useState } from "react";
import { authClient } from "@/lib/auth-client";
export function PaymentStatus({ paymentId }: { paymentId: string }) {
const [status, setStatus] = useState("pending");
useEffect(() => {
const timer = setInterval(async () => {
const { data } = await authClient.nuvion.payments.get({
query: { paymentId },
});
if (data) {
setStatus(data.payment.status);
if (data.payment.status !== "pending") clearInterval(timer);
}
}, 3_000);
return () => clearInterval(timer);
}, [paymentId]);
return (
<p>
{status === "pending" ? "Waiting for your bank…" : `Payment ${status}`}
</p>
);
}Store the paymentId the checkout call returned (for example in your own order row) so the page knows which payment to poll.
Onboard a merchant under a platform
One call sequence creates the organization, puts it under the platform, binds it to its Nuvion entity and account, and sets what the platform takes. Run it from an admin page or a script signed in as someone who can administer both organizations.
async function onboardMerchant(
platformId: string,
name: string,
entityId: string,
accountId: string,
) {
const org = await authClient.organization.create({
name,
slug: name.toLowerCase().replace(/\W+/g, "-"),
});
if (!org.data) throw new Error(org.error?.message);
await authClient.nuvion.organization.parent({
organizationId: org.data.id,
parentOrganizationId: platformId,
});
await authClient.nuvion.organization.bind({
organizationId: org.data.id,
entityId,
accountId,
});
await authClient.nuvion.feeRule({
organizationId: org.data.id,
bps: 250,
capMinor: 500,
bearer: "merchant",
});
return org.data.id;
}Each organization needs its own Nuvion account: a book transfer needs somewhere else to land. See Choosing a structure. To create the Nuvion entity and accounts when a merchant is approved, use the onEntityUpdated hook (Entity approval).
Retry and refund from an admin page
<button onClick={() => authClient.nuvion.payments.retry({ paymentId })}>Retry failed shares</button>
<button onClick={() => authClient.nuvion.payments.refund({ paymentId })}>Refund</button>Both are safe to press twice: a retry only touches legs that failed, and a second refund answers already-refunded. A refund reverses the split, it does not pay the customer back (Refunds). Or use the ready-made admin view.
Run it outside Next.js
The webhook is handled inside the Better Auth handler, which has to see the raw request body to check the signature. Mount the handler before any body parser.
import express from "express";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./auth";
const app = express();
app.all("/api/auth/*splat", toNodeHandler(auth)); // before express.json()
app.use(express.json());
app.listen(3000);import { Hono } from "hono";
import { auth } from "./auth";
const app = new Hono();
app.on(["GET", "POST"], "/api/auth/*", (c) => auth.handler(c.req.raw));
export default app;In both, the webhook URL you register in Nuvion is https://<your-host>/api/auth/nuvion/webhook.
TanStack Start, SvelteKit, Nuxt and React Router
TanStack Start has its own page: TanStack Start and Router.
Mount Better Auth the way its own guide for your framework says. The plugin's webhook is part of that handler, so there is nothing extra to add for Nuvion. The handler must be given the original Request, so the signature can be checked against the raw body.
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from "$app/environment";
import { auth } from "$lib/auth";
export async function handle({ event, resolve }) {
return svelteKitHandler({ event, resolve, auth, building });
}import { auth } from "~/lib/auth";
export default defineEventHandler((event) => auth.handler(toWebRequest(event)));import type { LoaderFunctionArgs, ActionFunctionArgs } from "react-router";
import { auth } from "~/lib/auth";
export async function loader({ request }: LoaderFunctionArgs) {
return auth.handler(request);
}
export async function action({ request }: ActionFunctionArgs) {
return auth.handler(request);
}Not run against these frameworks
These follow Better Auth's integration
guides. The plugin itself has been
run with Next.js, and its webhook route is tested by calling the handler with
a signed Request (Testing). After you mount it in
another framework, send one signed test request and check that a bad signature
answers 401.
Keep going
- Take the example apart: Examples links the full app and its source.
- Watch real deliveries while you build: Webhooks shows how to capture them with Hookbox.
- Before real money: Going to production.