Skip to Content
better-auth-nuvion

Accept payments for an online shop

Build a checkout for a shop end to end. Orders, a server-side total, the Nuvion checkout, fulfilling on settle, abandoned carts and refunds.

This guide takes a shop with one seller: you. A customer fills a cart, pays through Nuvion's hosted checkout, and the order is marked paid only when Nuvion has confirmed the money. For several sellers, see Marketplace.

It assumes the plugin is installed and that your shop is one organization, bound to your Nuvion entity and account. Payments are in GBP or EUR (FAQ), from 100 (£1.00).

The shape

PieceWhere it lives
Products, prices, stock, ordersYour database
The money, the checkout, the confirmationNuvion, driven by the plugin
The link between themorder.paymentId, the id the plugin returns for the checkout

The plugin does not store your cart or order. It stores the payment. You keep one column on your order, the paymentId, and everything else follows from it.

1. Check out

A server action does four things, in this order: read prices from your database, create the order, create the payment, send the customer to Nuvion.

app/actions.ts
"use server";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

const SHOP_ORG_ID = process.env.SHOP_ORG_ID!;

export async function checkout(cart: { productId: string; qty: number }[]) {
  const h = await headers();
  const session = await auth.api.getSession({ headers: h });
  if (!session) redirect("/sign-in");

  // Prices come from your database, never from the browser.
  const products = await db.product.findMany({
    where: { id: { in: cart.map((i) => i.productId) } },
  });
  const totalMinor = cart.reduce(
    (sum, i) =>
      sum + products.find((p) => p.id === i.productId)!.priceMinor * i.qty,
    0,
  );

  const order = await db.order.create({
    data: {
      userId: session.user.id,
      totalMinor,
      currency: "GBP",
      status: "awaiting_payment",
      items: cart,
    },
  });
  const payment = await auth.api.createPayment({
    headers: h,
    body: {
      organizationId: SHOP_ORG_ID,
      amountMinor: totalMinor,
      currency: "GBP",
      redirectUrl: `https://shop.example.com/orders/${order.id}`,
      idempotencyKey: order.id, // a double-click or a retry returns this payment, not a second one
    },
  });
  await db.order.update({
    where: { id: order.id },
    data: { paymentId: payment.paymentId },
  });
  redirect(payment.checkoutUrl);
}

Three things matter here:

  • Never trust a price or total from the client. Work the total out on the server from your own products.
  • The customer must be signed in, because the plugin checks a session. For guest checkout, Better Auth's anonymous plugin gives a visitor a session without an account. Test it before you rely on it.
  • redirectUrl is where the customer lands after the bank. It proves nothing about payment. Treat it as a page that shows the order's current state.

2. Mark the order paid, once

The order becomes paid when onPaymentSettled runs. That happens only after Nuvion has confirmed the money and every share has moved. It can run more than once if Nuvion redelivers, so make it a no-op the second time.

lib/auth.ts
nuvion({
  apiKey: process.env.NUVION_API_KEY!,
  webhookSecret: process.env.NUVION_WEBHOOK_SECRET!,
  hooks: {
    onPaymentSettled: async ({ payment }) => {
      const order = await db.order.findFirst({
        where: { paymentId: payment.id },
      });
      if (!order || order.status === "paid") return;
      await db.order.update({
        where: { id: order.id },
        data: { status: "paid" },
      });
      await sendReceipt(order.userId, order.id); // email, stock, shipping, whatever "fulfil" means for you
    },
    onRefunded: async ({ payment }) => {
      await db.order.updateMany({
        where: { paymentId: payment.id },
        data: { status: "refunded" },
      });
    },
  },
});

If a step in the hook can fail halfway (email down), put the fulfilment into a queue keyed on the order id instead of doing it inline. A hook that throws is logged and not retried.

3. Show the customer what happened

The customer can be back on your site before the confirmation arrives. Show the order's own status, and while it is awaiting_payment poll it. The polling component in Recipes does this: it watches the payment and your page re-reads the order.

Say plainly what is going on: "Waiting for your bank", then "Paid" or "Payment did not complete".

4. Abandoned and failed checkouts

A customer who opens the checkout and leaves, or whose bank declines, leaves an awaiting_payment order and a pending payment. The plugin ends that payment for you: when the reconcile or a refresh asks Nuvion and its checkout has expired or failed, the payment becomes expired or failed and a hook runs. Release the order and its stock there.

lib/auth.ts
hooks: {
  onPaymentExpired: async ({ payment }) => {
    await db.order.updateMany({
      where: { paymentId: payment.id, status: "awaiting_payment" },
      data: { status: "expired" },
    });
  },
  onPaymentFailed: async ({ payment }) => {
    await db.order.updateMany({
      where: { paymentId: payment.id, status: "awaiting_payment" },
      data: { status: "payment_failed" },
    });
  },
}

This needs the scheduled reconcile to be running, because Nuvion sends no webhook for an expired or declined checkout. The reconcile asks about payments older than two minutes.

An order whose payment settles after you expired it (a slow bank) is rare. Handle it in onPaymentSettled: if the order is expired, either restore it or refund the payment, and decide which before you launch.

5. Refunds

Call refund from an admin page (Recipes). The plugin reverses the shares, and onRefunded fires when the reversals complete.

The customer is not paid back by the plugin

A refund makes your account whole again. Sending the money back to the customer is a separate step in Nuvion. Say so in your refund process, and do not tell the customer "refunded" until you have done it (Refunds).

Before you launch

  • Prices and totals are computed on the server.
  • onPaymentSettled is idempotent, and nothing is fulfilled from the redirect page.
  • The webhook is registered, reachable over https, and webhookToleranceMs is set (Webhooks).
  • A scheduled reconcile is running, so a lost webhook is recovered.
  • You paid one real order with the smallest amount, from your own bank (Going to production).
  • Your terms and privacy pages say who processes payments, and you know how you will refund a customer.

On this page