Examples
The Altruon merchant demo, Altruon.js checkout components for React, Vue and Next.js, and a multi-step checkout.
Working code for the most common Altruon.js setups. Start with the merchant demo if you want a complete integration to read, or copy one of the shorter examples below.
The merchant demo
The Altruon merchant demo is the open-source reference integration: a branded SaaS checkout built with React and a minimal Express backend. It uses every Altruon.js method and callback, and every file is commented to be read.
git clone https://github.com/Altruon-io/merchant-demo
cd merchant-demo
npm run setup
cp server/.env.example server/.env # fill in your sandbox keys
npm run dev # backend on :4242, frontend on :3030| What it shows | Where to look |
|---|---|
| Session creation on the server, with the secret key isolated in one file | server/src/altruonClient.js, server/src/routes.js |
| The full Altruon.js flow: init, set session, render, process | client/src/pages/CheckoutPage.jsx |
| Live tax and discount estimates with coupon codes | client/src/components/OrderSummary.jsx |
A notice before a 3D Secure or bank redirect (onActionRequired with REDIRECT) | client/src/components/RedirectModal.jsx |
A scan-to-pay overlay for Pix and UPI (onActionRequired with QR_CODE) | client/src/components/QrOverlay.jsx |
| Failure handling with a retry on a fresh session | client/src/components/FailureModal.jsx |
| A transaction report after payment, with deep links to the acquirer and billing dashboards | client/src/pages/ResultPage.jsx |
| Styling the component to match the host page | buildStyleCustomization() in server/src/routes.js |
Server: create the session
The browser never sees the secret key. It calls the demo's own /api/session route, which calls Altruon. The route runs when the checkout page mounts, and again when the shopper changes something that needs new pricing, such as a coupon.
router.post("/session", async (req, res) => {
const { customer, country, couponCodes, redirectUrl } = req.body || {};
const data = await createSession({
paymentData: { currency: "USD" },
// After a redirect flow (3D Secure, bank login) Altruon returns the
// shopper to this URL with ?trx_id=<transaction id> appended.
redirectUrl,
billingData: {
billingPlatformId: process.env.BILLING_CONNECTION_ID,
// Strict ordering: exactly one "plan" item first, then add-ons.
lineItems: [{ type: "plan", id: process.env.PLAN_ID, quantity: 1 }],
...(couponCodes?.length ? { couponCodes } : {}),
},
customerData: {
email: customer?.email,
...(country ? { billingAddress: { country } } : {}),
},
// Make the embedded component match the storefront brand.
styleCustomization: { accentColor: "#6366F1", borderRadius: "10px" },
});
res.json({ sessionId: data.session_id });
});createSession() lives in server/src/altruonClient.js. It sets the x-secret-key header, resolves the environment and handles errors. It is the only file in the demo that talks to Altruon with the secret key.
Browser: bind Altruon.js and pay
// 1. The backend creates the session with the secret key.
const { sessionId } = await createCheckoutSession({ couponCodes, redirectUrl });
// 2. Bind Altruon.js to the session and mount the component.
altruon
.init(publishableKey, tenant)
.on("onSuccess", handleSuccess) // go to /result?trx_id=...
.on("onFailure", handleFailure) // failure modal; a retry needs a new session
.on("onActionRequired", handleActionRequired) // redirect notice or QR overlay
.on("onDataRequired", handleDataRequired);
altruon.setSession(sessionId);
await altruon.renderComponent("#altruon-payment-container");
// 3. When the shopper clicks Subscribe, pass their details to the session
// and trigger the payment.
altruon.setCustomer({ firstName, lastName, email });
altruon.setAddresses({ billing: { street, city, zipCode, country } });
altruon.processPaymentAndSubscription();
// 4. The outcome arrives through the callbacks registered above.Framework examples
Each component takes a sessionId that your server created, loads the script, renders the component and triggers the payment from its own button.
import { useEffect, useState } from 'react';
type Props = {
sessionId: string;
customerEmail?: string;
onSuccess: (data: { transactionId: string; message: string }) => void;
};
export default function AltruonCheckout({ sessionId, customerEmail, onSuccess }: Props) {
const [loaded, setLoaded] = useState(false);
const [processing, setProcessing] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://cdn.altruon.io/altruon-sdk.min.js';
script.async = true;
script.onload = () => {
const altruon = (window as any).altruon;
altruon
.init(process.env.REACT_APP_ALTRUON_PUBLIC_KEY!, 'your-domain')
.on('onSuccess', (data: any) => {
setProcessing(false);
onSuccess(data);
})
.on('onFailure', (failure: any) => {
setProcessing(false);
setError(failure.message);
});
altruon.setSession(sessionId);
if (customerEmail) altruon.setCustomer({ email: customerEmail });
altruon.renderComponent('#altruon-payment-container');
setLoaded(true);
};
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
const pay = () => {
setProcessing(true);
setError(null);
(window as any).altruon.processPaymentAndSubscription();
};
return (
<div>
{error && <p role="alert">{error}</p>}
<div id="altruon-payment-container" />
{loaded && (
<button onClick={pay} disabled={processing}>
{processing ? 'Processing...' : 'Pay now'}
</button>
)}
</div>
);
}The page asks your server for a session, then renders the component.
function CheckoutPage() {
const navigate = useNavigate();
const [sessionId, setSessionId] = useState<string | null>(null);
useEffect(() => {
fetch('/api/create-checkout-session', { method: 'POST' })
.then((res) => res.json())
.then((data) => setSessionId(data.sessionId));
}, []);
if (!sessionId) return <div>Loading...</div>;
return (
<AltruonCheckout
sessionId={sessionId}
customerEmail="customer@example.com"
onSuccess={(data) => navigate(`/success?trx_id=${data.transactionId}`)}
/>
);
}Each example initializes Altruon.js when the script has loaded. If your component can mount more than once, guard init() so it runs one time: see Troubleshooting.
Multi-step checkout
The shopper picks a plan, enters their details and then pays. The session is created when the shopper reaches the payment step, not when the page loads: a session lasts 15 minutes.
let selectedPlan = null;
// Initialise once, when the page loads.
altruon
.init('pk_sandbox_...', 'your-domain')
.on('onSuccess', (data) => showSuccessStep(data.transactionId))
.on('onFailure', (error) => showError(error.message));
// Step 1: the shopper picks a plan.
document.querySelectorAll('.plan-option').forEach((option) => {
option.addEventListener('click', () => {
selectedPlan = option.dataset.planId;
showStep('customer-info-step');
});
});
// Step 2: the shopper enters their details. Your server creates the session.
document.getElementById('continue-button').addEventListener('click', async () => {
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ planId: selectedPlan }),
});
const { sessionId } = await response.json();
// Step 3: bind the session, pass the details and render the component.
altruon.setSession(sessionId);
altruon.setCustomer({
email: document.getElementById('email').value,
firstName: document.getElementById('firstName').value,
lastName: document.getElementById('lastName').value,
});
document.querySelector('#altruon-payment-container').innerHTML = '';
altruon.renderComponent('#altruon-payment-container');
showStep('payment-step');
});
// Step 4: the shopper pays with your button.
document.getElementById('pay-button').addEventListener('click', () => {
altruon.processPaymentAndSubscription();
});
// Step 5: confirm.
function showSuccessStep(transactionId) {
showStep('success-step');
// Send transactionId to your server to set up the account.
}
function showStep(id) {
for (const step of document.querySelectorAll('.checkout-step')) {
step.hidden = step.id !== id;
}
}Retry with a fresh session
A session is single use, so a retry after onFailure needs a new one: create it, call setSession(), clear the container and render again. The code is in Recover from a failed payment, and the merchant demo implements it in FailureModal.jsx.
More patterns
| Pattern | Where |
|---|---|
| One HTML page and an Express server | Quickstart: complete example |
| Pre-filled customer details and progressive collection | Customer data |
| Redirects, QR codes and missing data | Handle payment results |
| Coupons that the shopper applies at checkout | Coupons |
| Themes and per-plan styling | Style the component |
Next steps
Style the component
Set the colors, corner radius, font and shadow of the Altruon.js component with styleCustomization when you create the session.
How billing sync works
Your billing platform stays the source of truth. Altruon creates the subscription after the first payment and records every payment on its invoice.