Skip to main content

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.

Installation

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:

  1. Backend: Create a payment session via API (returns sessionId)
  2. Frontend: Initialize Altruon with the session
  3. Frontend: Set customer data using setter methods
  4. Frontend: Render the payment component
  5. 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': {
'planId': 'price_1SMtJj4hYau76GhIakR22BKu',
'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 paymentMethod in the paymentData object, 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: {
planId: 'price_1SMtJj4hYau76GhIakR22BKu',
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 styleCustomization object 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.data.url;
}
})
.on("onDataRequired", (info) => {
// Additional data required
console.warn("Required fields:", info.requiredFields);
});

Available Callbacks:

CallbackWhen TriggeredResponse Data
onSuccessPayment completed successfully{ transactionId, message }
onFailurePayment failed{ status, message }
onActionRequiredExtra action needed (3DS, QR code){ actionType, data, message }
onDataRequiredMissing required data{ message, details, requiredFields }

Note: You can find your publishable key in the Altruon Dashboard under Settings > API Keys.

Important: The onSuccess callback only provides the transactionId. 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}/details

For 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, planId, and billingPlatformId must be set during session creation on your backend. Only billingAddress.country can 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({
planId: "price_1SMtJj4hYau76GhIakR22BKu",
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

Here's a complete implementation with backend and frontend:

Backend (Node.js/Express)

// server.js
app.post('/create-checkout-session', async (req, res) => {
const { planId, billingPlatformId, currency } = req.body;

try {
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': process.env.ALTRUON_SECRET_KEY
},
body: JSON.stringify({
paymentData: {
currency: currency || 'USD',
paymentMethod: 'card'
},
redirectUrl: 'https://yourdomain.com/success',
billingData: {
planId: planId,
billingPlatformId: billingPlatformId
},
styleCustomization: {
backgroundColor: '#ffffff',
primaryColor: '#0066FF',
accentColor: '#0066FF',
borderRadius: '8px'
}
})
});

const data = await response.json();
res.json({ sessionId: data.session_id });
} catch (error) {
res.status(500).json({ error: error.message });
}
});

Frontend (HTML + JavaScript)

<!DOCTYPE html>
<html>
<head>
<title>Checkout - My Store</title>
<script src="https://cdn.sandbox.altruon.io/altruon-sdk.min.js"></script>
<style>
body {
font-family: system-ui, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
}
button {
background: #0066FF;
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
</head>
<body>
<h1>Complete Your Purchase</h1>

<div id="customer-form">
<input type="email" id="email" placeholder="Email" />
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<button onclick="initializeCheckout()">Continue to Payment</button>
</div>

<div id="payment-section" style="display: none;">
<div id="altruon-payment-container"></div>
<button id="pay-button">Pay Now</button>
</div>

<script>
let sessionId = null;

// Step 1: Initialize checkout and create session
async function initializeCheckout() {
const email = document.getElementById('email').value;
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;

// Create session on backend
const response = await fetch('/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
planId: 'price_1SMtJj4hYau76GhIakR22BKu',
billingPlatformId: '3287b8c7-ce43-41fd-9d58-f510e610b8f3',
currency: 'USD'
})
});

const { sessionId: newSessionId } = await response.json();
sessionId = newSessionId;

// Initialize Altruon with callbacks
altruon
.init("pk_sandbox_your_publishable_key", "your-domain")
.on("onSuccess", (data) => {
window.location.href = '/success';
})
.on("onFailure", (error) => {
alert('Payment failed: ' + error.message);
});

// Set session
altruon.setSession(sessionId);

// Set customer data
altruon.setCustomer({
firstName: firstName,
lastName: lastName,
email: email
});

// Render component
altruon.renderComponent("#altruon-payment-container");

// Show payment section
document.getElementById('customer-form').style.display = 'none';
document.getElementById('payment-section').style.display = 'block';
}

// Note: Payment is handled automatically by the component
// Success/failure callbacks are triggered automatically
</script>
</body>
</html>

Next Steps


Getting Help

If you need assistance: