Skip to Content
Checkout · Altruon.js

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.

CallbackFires whenWhat you do
onSuccessThe payment and the subscription are completeSend the transaction ID to your server and confirm to the shopper
onFailureThe payment failedShow the message and offer a retry on a new session
onDataRequiredThe payment cannot complete because data is missingCollect the missing fields and trigger the payment again
onActionRequiredThe shopper has one more step: 3D Secure (3DS), a bank page or a QR codeRedirect 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.

Redirect flow
BrowserYour serverAltruon01 processPaymentAndSubscription02 onActionRequired: REDIRECT03 Shopper authenticates04 Back to redirectUrl?trx_id=05 trx_id06 GET transaction details
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.

server.js
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.

CallbackHow to trigger it
onSuccessPay with a card that is approved
onFailurePay with a card that is declined
onDataRequiredLeave required fields empty and trigger the payment
onActionRequired with REDIRECTPay with a card that requires 3D Secure
onActionRequired with QR_CODESelect Pix or UPI as the payment method

Troubleshooting

For problems outside the callbacks, see Troubleshooting.

Next steps