Handle payment results
What to do in each Altruon.js callback, from success and failure to redirects and QR codes, and how to recover from a failed payment.
After you call processPaymentAndSubscription(), Altruon.js reports the outcome through one of four callbacks. This guide shows what your page and your server do in each case.
| Callback | Fires when | What you do |
|---|---|---|
onSuccess | The payment and the subscription are complete | Send the transaction ID to your server and confirm to the shopper |
onFailure | The payment failed | Show the message and offer a retry on a new session |
onDataRequired | The payment cannot complete because data is missing | Collect the missing fields and trigger the payment again |
onActionRequired | The shopper has one more step: 3D Secure (3DS), a bank page or a QR code | Redirect the shopper or show the QR code |
The Callbacks reference lists every payload field.
Register the callbacks
Register all four, once, before you call renderComponent().
altruon
.init('pk_sandbox_...', 'your-domain')
.on('onSuccess', handleSuccess)
.on('onFailure', handleFailure)
.on('onDataRequired', handleDataRequired)
.on('onActionRequired', handleActionRequired);
altruon.setSession(sessionId);
altruon.renderComponent('#altruon-payment-container');Success
onSuccess gives you a transactionId and a message, nothing more. Send the ID to your server, which reads the full result with the secret key, then move the shopper on.
async function handleSuccess(data) {
await fetch('/api/payment-success', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transactionId: data.transactionId }),
});
window.location.href = `/success?trx_id=${data.transactionId}`;
}If the call to your own server fails, the payment has still succeeded. Show the transaction ID so the shopper can quote it to your support team.
Failure
onFailure gives you a status and a message written for the shopper. Show the message, re-enable your pay button and offer a retry.
function handleFailure(error) {
document.getElementById('error-message').textContent = error.message;
document.getElementById('pay-button').disabled = false;
}The status tells you why, for example declined, insufficient_funds or expired_card. See status values for the list and a suggested action for each. A retry needs a new session: see Recover from a failed payment.
Data required
onDataRequired fires when a required value is missing, such as part of the billing address, a phone number or a tax document. requiredFields is a comma-separated string of field names, for example billingAddress.zipCode,phone,document.
Ask the shopper for the missing values, pass them with the setters and trigger the payment again.
const customer = {}; // what you passed to setCustomer()
const billing = {}; // what you passed to setAddresses()
function handleDataRequired(info) {
const fields = info.requiredFields.split(',').map((field) => field.trim());
// Your own form: shows info.details and one input per field.
askForFields(fields, info.details, (values) => {
for (const field of fields) {
if (field.startsWith('billingAddress.')) {
billing[field.split('.')[1]] = values[field];
} else if (field === 'document') {
altruon.setPaymentExtra({ document: values[field] });
} else {
customer[field] = values[field];
}
}
altruon.setCustomer(customer);
altruon.setAddresses({ billing });
altruon.processPaymentAndSubscription();
});
}Customer data explains each setter. The field names you can receive are listed under required fields.
Action required
onActionRequired fires when the payment needs one more step from the shopper. actionType is REDIRECT or QR_CODE.
Redirects
3D Secure and bank authorization happen on another page. Send the shopper to redirectUrl.
function handleActionRequired(action) {
if (action.actionType === 'REDIRECT') {
sessionStorage.setItem('paymentInProgress', 'true');
window.location.href = action.redirectUrl;
}
}After the redirect flow, Altruon returns the shopper to the redirectUrl you set on the session, with ?trx_id= and the transaction ID appended. On that page, read the ID and ask your server for the result.
const transactionId = new URLSearchParams(window.location.search).get('trx_id');
if (transactionId) {
sessionStorage.removeItem('paymentInProgress');
const response = await fetch(`/api/transactions/${transactionId}`);
const details = await response.json();
showResult(details.transaction.status); // success, failed or pending
}On mobile, make sure the shopper can return from a 3D Secure or bank redirect. Save what you need before the redirect, as with the paymentInProgress flag above, and check the payment status with your server when your page loads again.
The merchant demo shows a short notice before it redirects, so the shopper knows why they leave the page. See RedirectModal.jsx.
QR codes
Pix and UPI are paid by scanning a code. qrData is a PNG image as a base64 data URI, so you can use it directly as the src of an image. Show it with the message.
<div id="qr-overlay" hidden>
<p id="qr-message"></p>
<img id="qr-image" alt="Payment QR code" />
</div>function handleActionRequired(action) {
if (action.actionType === 'QR_CODE' && action.qrData) {
document.getElementById('qr-message').textContent = action.message;
document.getElementById('qr-image').src = action.qrData;
document.getElementById('qr-overlay').hidden = false;
pollPaymentStatus();
}
}The shopper completes the payment outside your page, so keep the code on screen and ask your server whether the payment has arrived. In this example /api/check-payment-status is your own endpoint: the page polls it every 3 seconds and stops after 10 minutes. Your server can track the outcome with webhooks, for example the payment.succeeded event.
function pollPaymentStatus() {
const poll = setInterval(async () => {
const response = await fetch('/api/check-payment-status');
const { status } = await response.json();
if (status === 'completed') {
clearInterval(poll);
window.location.href = '/success';
}
}, 3000);
setTimeout(() => clearInterval(poll), 10 * 60 * 1000);
}The merchant demo has a complete scan-to-pay overlay in QrOverlay.jsx.
Fetch transaction details
The browser only ever holds the transaction ID. Your server reads the transaction, the customer, the invoice and the subscription with the secret key.
app.get('/api/transactions/:id', async (req, res) => {
const response = await fetch(
`https://{your-domain}.api.sandbox.altruon.io/api/v1/transaction/${req.params.id}/details`,
{
headers: {
'Content-Type': 'application/json',
'x-secret-key': process.env.ALTRUON_SECRET_KEY,
},
},
);
res.status(response.status).json(await response.json());
});Use the result to link the payment to the account in your own system and to store the subscription and invoice IDs from your billing platform. Get transaction details lists every field.
Recover from a failed payment
A session is single use. After onFailure, do not reuse it: ask your server for a new session with the same cart, bind it and render the component again.
function handleFailure(error) {
showFailureMessage(error.message, { onRetry: retryCheckout });
}
async function retryCheckout() {
// 1. A new session for the same cart.
const response = await fetch('/api/session', { method: 'POST' });
const { sessionId } = await response.json();
// 2. Bind it and mount the component again. Altruon.js appends an iframe
// to the container, so clear the previous one first.
altruon.setSession(sessionId);
document.querySelector('#altruon-payment-container').innerHTML = '';
await altruon.renderComponent('#altruon-payment-container');
}Do not call init() again: the callbacks you registered stay in place. The merchant demo implements this pattern in FailureModal.jsx.
Test it
Trigger each callback in the sandbox. Testing has the card numbers.
| Callback | How to trigger it |
|---|---|
onSuccess | Pay with a card that is approved |
onFailure | Pay with a card that is declined |
onDataRequired | Leave required fields empty and trigger the payment |
onActionRequired with REDIRECT | Pay with a card that requires 3D Secure |
onActionRequired with QR_CODE | Select Pix or UPI as the payment method |
Troubleshooting
- Register the callbacks before you call
renderComponent(). - Check that
setSession()was called with thesession_idyour server returned. - Look for errors in the browser console.
altruon
.init('pk_sandbox_...', 'your-domain')
.on('onSuccess', handleSuccess)
.on('onFailure', handleFailure);
altruon.setSession(sessionId);
altruon.renderComponent('#altruon-payment-container');Altruon.js was initialized more than once. Call init() one time per page.
if (!window.altruonInitialized) {
altruon.init('pk_sandbox_...', 'your-domain');
window.altruonInitialized = true;
}Check that qrData is present and starts with data:image/png;base64, before you set it as the image source.
altruon.on('onActionRequired', (action) => {
if (action.actionType === 'QR_CODE') {
console.log(action.qrData.substring(0, 50));
}
});For problems outside the callbacks, see Troubleshooting.