Next.js
This guide adds OnCharge to a Next.js (App Router) store: a server action creates the checkout session, a client component embeds the checkout, a route handler receives webhooks, and an admin action reports shipments. It uses @oncharge/node and @oncharge/js.
Environment#
ONCHARGE_API_KEY=oc_key_...
ONCHARGE_API_SECRET=oc_sec_...
ONCHARGE_WEBHOOK_SECRET=oc_cbsec_...Never prefix these with NEXT_PUBLIC_: that would ship them to the browser.
1. A server-only client#
import 'server-only';
import { OnCharge } from '@oncharge/node';
export const oncharge = new OnCharge({
apiKey: process.env.ONCHARGE_API_KEY!,
apiSecret: process.env.ONCHARGE_API_SECRET!,
});2. Create the session on the server#
Compute the amount from your own database, never from the browser.
import { oncharge } from '@/lib/oncharge';
import { getOrder } from '@/lib/orders';
import { CheckoutFrame } from './checkout-frame';
export const dynamic = 'force-dynamic';
export default async function CheckoutPage({ params }: { params: Promise<{ orderId: string }> }) {
const { orderId } = await params;
const order = await getOrder(orderId);
const session = await oncharge.checkout.sessions.create(
{
amount: order.totalCents,
currency: 'USD',
reference: `order-${order.id}`,
order_id: order.id,
return_url: `https://shop.example.com/checkout/${order.id}/complete`,
customer_email: order.email,
shipping: order.requiresShipping
? {
name: order.shipping.name,
line1: order.shipping.line1,
line2: order.shipping.line2,
city: order.shipping.city,
state: order.shipping.state,
postal_code: order.shipping.postalCode,
country: order.shipping.country,
}
: undefined,
},
{ idempotencyKey: `order-${order.id}` },
);
await saveSessionId(order.id, session.session_id);
return <CheckoutFrame url={session.checkout_url} orderId={order.id} />;
}The same idempotency key returns the same open session if the page is reloaded within 50 minutes.
These pages are written for Next.js 15, where params is a promise. On Next.js 14, params is a plain object: type it as { orderId: string } and read params.orderId without await.
3. Embed the checkout#
'use client';
import { useRouter } from 'next/navigation';
import { OnChargeCheckout } from '@oncharge/js/react';
export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
const router = useRouter();
return (
<OnChargeCheckout
url={url}
minHeight={480}
onComplete={() => router.push(`/checkout/${orderId}/complete`)}
onRedirect={({ url: target }) => window.location.assign(target)}
onError={(error) => console.warn('OnCharge checkout error', error)}
/>
);
}Prefer a full-page redirect? Replace the component with redirect(session.checkout_url) from next/navigation in the page.
4. Receive webhooks#
import { createWebhookHandler } from '@oncharge/node/next';
import { markOrderPaid, markOrderFailed, recordRefund, flagOrder } from '@/lib/orders';
export const { POST } = createWebhookHandler({
secret: process.env.ONCHARGE_WEBHOOK_SECRET!,
async onEvent(event) {
const orderId = event.data.order_id;
switch (event.type) {
case 'payment.captured':
await markOrderPaid(orderId, event.data.session_id);
break;
case 'payment.refused':
case 'payment.cancelled':
await markOrderFailed(orderId);
break;
case 'refund.succeeded':
await recordRefund(orderId, event.data.amount);
break;
case 'chargeback.opened':
await flagOrder(orderId);
break;
}
},
});Register https://shop.example.com/api/webhooks/oncharge as the store's webhook URL in the merchant portal. The handler skips repeated event IDs in memory; on serverless or with several instances, pass eventIdStore: { has(id), add(id) } backed by your database so a retry that lands on another instance is still recognised.
5. The return page#
import { getOrder } from '@/lib/orders';
export const dynamic = 'force-dynamic';
export default async function Complete({ params }: { params: Promise<{ orderId: string }> }) {
const { orderId } = await params;
const order = await getOrder(orderId);
return order.paid ? <p>Thank you! Your order is confirmed.</p> : <p>We are confirming your payment. This page will update shortly.</p>;
}order.paid is set by the webhook. To check without waiting, call oncharge.checkout.sessions.retrieve(sessionId) with the saved session ID.
6. Report shipments#
'use server';
import { oncharge } from '@/lib/oncharge';
export async function markShipped(orderId: string, carrier: string, trackingNumber: string) {
const result = await oncharge.shipments.report({
order_id: orderId,
shipments: [{ carrier, tracking_number: trackingNumber }],
});
const rejected = result.shipments.filter((s) => s.status === 'rejected');
if (rejected.length) throw new Error(rejected.map((s) => s.message).join('; '));
}7. Refunds#
await oncharge.refunds.create({ session_id: sessionId, amount: 1500, currency: 'USD', reference: `refund-${refundId}` });8. RUO stores: the compliance feed#
import { createComplianceFeedRoute } from '@oncharge/node/next';
import { listPublishedCatalog } from '@/lib/catalog';
export const dynamic = 'force-dynamic';
export const { GET } = createComplianceFeedRoute({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
host: 'shop.example.com',
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
listItems: async ({ cursor, limit }) => listPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
});See RUO compliance feed.
Content Security Policy#
If you set a CSP in next.config.js or middleware, allow the checkout frame:
const csp = ["frame-src 'self' https://app.oncharge.io"].join('; ');
module.exports = {
async headers() {
return [{ source: '/checkout/:path*', headers: [{ key: 'Content-Security-Policy', value: csp }] }];
},
};Without the SDKs#
Until the packages are published, this client component replaces OnChargeCheckout:
'use client';
import { useEffect, useMemo, useRef, useState } from 'react';
export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
const frame = useRef<HTMLIFrameElement>(null);
const [height, setHeight] = useState(480);
const [src, setSrc] = useState<string | null>(null);
const nonce = useMemo(() => Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join(''), []);
useEffect(() => {
const checkout = new URL(url);
checkout.searchParams.set('embed', '1');
checkout.searchParams.set('parent_origin', window.location.origin);
checkout.searchParams.set('embed_nonce', nonce);
setSrc(checkout.toString());
function onMessage(event: MessageEvent) {
if (event.origin !== checkout.origin || event.source !== frame.current?.contentWindow) return;
const msg = event.data;
if (!msg || msg.source !== 'oncharge-checkout' || msg.version !== 1 || msg.nonce !== nonce) return;
if ((msg.type === 'ready' || msg.type === 'resize') && typeof msg.height === 'number') setHeight(Math.max(480, Math.ceil(msg.height)));
if (msg.type === 'complete') window.location.href = `/checkout/${orderId}/complete`;
if (msg.type === 'redirect' && typeof msg.url === 'string') window.location.assign(msg.url);
}
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, [url, orderId, nonce]);
if (!src) return null;
return <iframe ref={frame} src={src} title="Secure checkout" allow="payment" referrerPolicy="origin" style={{ width: '100%', height, border: 0 }} />;
}On the server, session.checkout_url becomes new URL(session.iframe_url, 'https://app.oncharge.io').href.