Quick Start
Get started with Altruon JS in minutes. This guide will walk you through integrating Altruon's payment components into your custom checkout page.
Overview
Altruon JS allows you to embed our intelligent payment routing capabilities directly into your own checkout pages. Instead of redirecting customers to a hosted payment page, you can create a seamless, branded payment experience while still leveraging Altruon's powerful routing engine.
🛠 Reference implementation: the Altruon Merchant Demo
The fastest way to learn the integration is the open-source Altruon Merchant Demo: a branded SaaS checkout (React + Express) that exercises the full SDK surface, including session creation, live tax estimates, redirect and QR payment flows, failure handling, and a post-payment transaction report. Every file is heavily commented and meant 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 :4242, frontend :3030Throughout these docs, code snippets are taken from the demo so you can see them in their full working context.
Installation
Via CDN (Recommended)
Add the Altruon JS script to your HTML page:
<script src="https://cdn.altruon.io/altruon-sdk.min.js"></script>
Via NPM
npm install @altruon/altruon-js
import Altruon from '@altruon/altruon-js';
Integration Overview
Altruon JS uses a session-based approach:
- Backend: Create a payment session via API (returns
sessionId) - Frontend: Initialize Altruon with the session
- Frontend: Set customer data using setter methods
- Frontend: Render the payment component
- Frontend: Process the payment
Basic Integration
Step 1: Create a Payment Session (Backend)
First, create a payment session from your backend by calling the Altruon Create Session API:
Endpoints:
- Sandbox:
https://{your-domain}.api.sandbox.altruon.io/api/session/v1/create - Production:
https://{your-domain}.api.altruon.io/api/session/v1/create
# Python example
import requests
response = requests.post(
'https://{your-domain}.api.sandbox.altruon.io/api/session/v1/create',
headers={
'Content-Type': 'application/json',
'x-secret-key': 'sk_sandbox_test_XXXXXX...'
},
json={
'paymentData': {
'currency': 'USD',
'paymentMethod': 'card'
},
'redirectUrl': 'https://yourdomain.com/success',
'billingData': {
'lineItems': [
{
'type': 'plan',
'id': 'price_1SMtJj4hYau76GhIakR22BKu',
'quantity': '1'
}
],
'billingPlatformId': '3287b8c7-ce43-41fd-9d58-f510e610b8f3'
},
'styleCustomization': {
'backgroundColor': '#3a3a3a',
'primaryColor': '#4B5563',
'secondaryColor': '#3a3a3a',
'accentColor': '#5B7FFF',
'borderRadius': '5px',
'headerTextColor': '#ffffff',
'fontFamily': 'Verdana, cursive',
'textColor': '#ffffff',
'dropShadow': False
}
}
)
session_id = response.json()['session_id']
Component Rendering Behavior: If you don't specify a
paymentMethodin thepaymentDataobject, the component will automatically adapt based on your routing configuration:
- Multiple payment methods available: Shows a drawer UI for payment method selection
- Single payment method available: Shows only the payment fields (e.g., card fields) without the drawer
// Node.js example
const response = await fetch('https://{your-domain}.api.sandbox.altruon.io/api/session/v1/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-secret-key': 'sk_sandbox_test_XXXXXX...'
},
body: JSON.stringify({
paymentData: {
currency: 'USD',
paymentMethod: 'card'
},
redirectUrl: 'https://yourdomain.com/success',
billingData: {
lineItems: [
{
type: 'plan',
id: 'price_1SMtJj4hYau76GhIakR22BKu',
quantity: '1'
}
],
billingPlatformId: '3287b8c7-ce43-41fd-9d58-f510e610b8f3'
},
styleCustomization: {
backgroundColor: '#3a3a3a',
primaryColor: '#4B5563',
secondaryColor: '#3a3a3a',
accentColor: '#5B7FFF',
borderRadius: '5px',
headerTextColor: '#ffffff',
fontFamily: 'Verdana, cursive',
textColor: '#ffffff',
dropShadow: false
}
})
});
const { session_id } = await response.json();
Tip: The
styleCustomizationobject lets you customize the payment component's appearance to match your brand. See the Style Customization guide for all available options and examples.
Note: See the Session API Reference for complete Create Session API details.
Pass the session_id to your frontend (e.g., render it in the page template or return it via your own API).
Step 2: Initialize Altruon (Frontend)
Initialize Altruon with your publishable key and domain:
altruon.init("pk_sandbox_your_publishable_key", "your-domain");
You can also chain callback handlers during initialization to handle payment events:
altruon
.init("pk_sandbox_your_publishable_key", "your-domain")
.on("onSuccess", (data) => {
// Payment completed successfully
console.log("Transaction ID:", data.transactionId);
window.location.href = '/success';
})
.on("onFailure", (error) => {
// Payment failed
console.error("Payment failed:", error.message);
alert(error.message);
})
.on("onActionRequired", (action) => {
// Extra action needed (3DS, QR code, etc.)
if (action.actionType === 'REDIRECT') {
window.location.href = action.redirectUrl;
}
})
.on("onDataRequired", (info) => {
// Additional data required
console.warn("Required fields:", info.requiredFields);
});
Available Callbacks:
| Callback | When Triggered | Response Data |
|---|---|---|
onSuccess | Payment completed successfully | { transactionId, message } |
onFailure | Payment failed | { status, message } |
onActionRequired | Extra action needed (3DS, QR code) | { actionType, message, redirectUrl?, qrData? } |
onDataRequired | Missing required data | { message, details, requiredFields } |
Note: You can find your publishable key in the Altruon Dashboard under Settings > API Keys.
Important: The
onSuccesscallback only provides thetransactionId. To get complete details (subscription ID, customer ID, invoice ID, etc.), call the Transaction Details API from your backend:GET https://{your-domain}.api.sandbox.altruon.io/api/v1/transaction/{transactionId}/detailsFor detailed information about callbacks and the Transaction Details API, see the Callbacks documentation.
Step 3: Set the Session
Set the session ID received from your backend:
altruon.setSession(sessionId);
Step 4: Set Customer Data (Optional)
If customer data wasn't provided during session creation, or if you're collecting it progressively, use the setter methods.
Important: The required fields
currency,lineItems(in billingData), andbillingPlatformIdmust be set during session creation on your backend. OnlybillingAddress.countrycan be set from the frontend. All other customer fields are optional.
// Set customer information
altruon.setCustomer({
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
phone: "+1234567890",
ip: "127.0.0.1" // Optional: customer's IP address
});
// Set billing and shipping addresses
altruon.setAddresses({
billing: {
street: "123 Main St",
number: "Apt 4B", // Optional
city: "New York",
state: "NY",
zipCode: "10001",
country: "US"
},
shipping: { // Optional: if different from billing
street: "456 Oak Ave",
city: "Brooklyn",
state: "NY",
zipCode: "11201",
country: "US"
}
});
// Set billing platform data (if not provided in session creation)
altruon.setBilling({
lineItems: [
{
type: "plan",
id: "price_1SMtJj4hYau76GhIakR22BKu",
quantity: "1"
}
],
platformId: "3287b8c7-ce43-41fd-9d58-f510e610b8f3",
platformName: "stripe" // e.g., "stripe", "chargebee"
});
Step 5: Add Container Element
Add a container element to your HTML where the payment component will be rendered:
<div id="altruon-payment-container"></div>
Step 6: Render the Component
Render the payment component in your designated container:
altruon.renderComponent("#altruon-payment-container");
Step 7: Handle Payment
Once all the proper frontend setter method called (as required), you will trigger payment submission by calling:
altruon.processPaymentAndSubscription()
You can then listen for payment results using the callback handlers set during initialization:
altruon
.init("pk_sandbox_your_key", "your-domain")
.on("onSuccess", (data) => {
console.log('Payment successful!', data);
// Redirect to success page
window.location.href = '/success';
})
.on("onFailure", (error) => {
console.error('Payment failed:', error);
// Display error message to user
alert('Payment failed: ' + error.message);
});
Complete Example: the Merchant Demo
Rather than maintaining a separate toy example, the complete reference implementation lives in the Altruon Merchant Demo. The snippets below are taken from it (lightly trimmed); follow the file links to see them in full context.
Backend: create the session with the secret key
From server/src/routes.js: the browser never sees the secret key; it calls the demo's own /api/session route, which calls Altruon server-side.
/*
* POST /api/session - create the Altruon checkout session.
* Called when the checkout page mounts (and again if the shopper changes
* something that requires re-pricing, e.g. coupons, since sessions are
* cheap and single-use).
*/
router.post("/session", async (req, res) => {
const { customer, country, couponCodes, redirectUrl } = req.body || {};
const data = await createSession({
paymentData: { currency: "USD" },
// After a redirect flow (3-D 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 addons.
lineItems: [{ type: "plan", id: process.env.PLAN_ID, quantity: 1 }],
...(couponCodes?.length ? { couponCodes } : {}),
},
customerData: {
email: customer?.email,
...(country ? { billingAddress: { country } } : {}),
},
// Make the embedded payment component match the storefront brand.
styleCustomization: { accentColor: "#6366F1", borderRadius: "10px" },
});
res.json({ sessionId: data.session_id });
});
The createSession helper (with the x-secret-key header, error handling and environment resolution) lives in server/src/altruonClient.js. It's the only file in the demo that talks to Altruon with the secret key.
Frontend: bind the SDK and process the payment
From client/src/pages/CheckoutPage.jsx:
// Step 1 - our backend creates the session with the SECRET key.
const { sessionId } = await createCheckoutSession({ couponCodes, redirectUrl });
// Step 2 - bind the SDK to the session and mount the component.
altruon
.init(publishableKey, tenant)
.on("onSuccess", handleSuccess) // → navigate to /result?trx_id=...
.on("onFailure", handleFailure) // → failure modal; retry = new session
.on("onActionRequired", handleActionRequired) // → 3DS redirect modal / QR overlay
.on("onDataRequired", handleDataRequired);
altruon.setSession(sessionId);
await altruon.renderComponent("#altruon-payment-container");
// Step 3 - when the shopper clicks Subscribe, sync their details
// onto the session and trigger the payment.
altruon.setCustomer({ firstName, lastName, email });
altruon.setAddresses({ billing: { street, city, zipCode, country } });
altruon.processPaymentAndSubscription();
// Step 4 - the outcome arrives via the callbacks registered above.
The demo also shows production-grade handling of the trickier parts:
| Concern | Demo file |
|---|---|
| Pre-redirect disclaimer for 3-D Secure / bank flows | client/src/components/RedirectModal.jsx |
| Scan-to-pay QR overlay (Pix / UPI) | client/src/components/QrOverlay.jsx |
| Live tax & discount estimate (order summary) | client/src/components/OrderSummary.jsx |
| Post-payment transaction report with dashboard deep links | client/src/pages/ResultPage.jsx |
| Failure handling & retry with a fresh session | client/src/components/FailureModal.jsx |
Next Steps
- Configuration Options - Customize the payment component
- Event Callbacks - Handle all payment lifecycle events
- Coupons - Add coupons with API or SDK
- Style Customization - Match your brand
- Examples - See real-world implementations
Getting Help
If you need assistance:
- Explore the Merchant Demo for a complete working integration
- Check our Examples for common use cases
- Contact support at support@altruon.com