React
A React single-page app (Vite, Create React App and similar) cannot hold your API secret, so the integration has two halves:
- Your backend (here, Express) creates checkout sessions, receives webhooks and reports shipments.
- Your React app asks the backend for a checkout URL and shows it with
<OnChargeCheckout>.
Backend#
import express from 'express';
import { OnCharge } from '@oncharge/node';
const app = express();
const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY, apiSecret: process.env.ONCHARGE_API_SECRET });
// Webhooks need the raw body, so register this route before express.json().
app.post('/api/webhooks/oncharge', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = OnCharge.webhooks.constructEvent(req.body.toString('utf8'), req.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET, {
toleranceSeconds: 300,
});
} catch {
return res.status(400).send('Invalid signature');
}
if (event.type === 'payment.captured') await orders.markPaid(event.data.order_id, event.data.session_id);
if (event.type === 'payment.refused' || event.type === 'payment.cancelled') await orders.markFailed(event.data.order_id);
res.sendStatus(200);
});
app.use(express.json());
// The browser sends only the order ID; the amount comes from your database.
app.post('/api/checkout', async (req, res) => {
const order = await orders.get(req.body.orderId);
if (!order || order.paid) return res.status(404).json({ error: 'order_not_found' });
const session = await oncharge.checkout.sessions.create(
{
amount: order.totalCents,
currency: order.currency,
reference: `order-${order.id}`,
order_id: order.id,
return_url: `https://shop.example.com/orders/${order.id}`,
customer_email: order.email,
shipping: order.shippingAddress, // { name, line1, line2, city, state, postal_code, country }
},
{ idempotencyKey: `order-${order.id}` },
);
res.json({ checkoutUrl: session.checkout_url });
});
app.listen(3001);React component#
import { useEffect, useState } from 'react';
import { OnChargeCheckout } from '@oncharge/js/react';
export function Checkout({ orderId }: { orderId: string }) {
const [checkoutUrl, setCheckoutUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orderId }),
})
.then((res) => (res.ok ? res.json() : Promise.reject(new Error('Could not start checkout'))))
.then((data) => setCheckoutUrl(data.checkoutUrl))
.catch((err) => setError(err.message));
}, [orderId]);
if (error) return <p role="alert">{error}</p>;
if (!checkoutUrl) return <p>Loading secure checkout…</p>;
return (
<OnChargeCheckout
url={checkoutUrl}
minHeight={480}
onComplete={() => {
window.location.href = `/orders/${orderId}`;
}}
onRedirect={({ url }) => window.location.assign(url)}
onError={(err) => console.warn(err)}
/>
);
}The order page reads the order from your backend; it shows "paid" once the payment.captured webhook has arrived.
Notes#
- Never put
ONCHARGE_API_SECRETinVITE_*,REACT_APP_*or any variable your bundler exposes. - The page that shows the checkout must be on a registered store domain over HTTPS. For local development, use the redirect flow or register a staging domain.
- Report tracking numbers from your backend with
oncharge.shipments.report(...)when orders ship. See Shipments & payouts.