API References

Transaction Authorization

Real-time card transaction authorization over NATS request-reply, with approval decisions made by your platform.

Overview

Transaction authorization lets your platform control card usage in real time: every card transaction is sent to you for an approve or decline decision before it completes.

The flow uses NATS request-reply. Your platform subscribes to an authorization subject and must respond within 2 seconds. If no response arrives in that window, the transaction is automatically declined.

Opt-in during partner onboarding

Transaction authorization is optional. You choose whether to use it when you onboard as a partner with SAVA. If you opt in, every card payment is sent to you for a decision. If you don't, SAVA authorizes card payments for you: a payment is approved when the cardholder's account has the funds, and you still receive the usual notifications.

Authorization sequence

The real-time flow for a single transaction:

CardholderCard NetworkSAVA BaaSPool AccountPartnerpurchase, R100auth requestreserve R100reserved, funds availableauth requestdecision: 000 or decline codedecisionresultapply rules, under 2s

SAVA reserves the funds, then asks the partner to approve or decline. The partner must reply within 2 seconds with an ISO 8583:1993 code, where 000 approves and anything else declines. No reply within the window means an automatic decline.

Authorization decision factors

Within the 2 second window, your platform can apply any combination of checks:

FactorDescription
Internal balance checkValidates the user has sufficient funds in your internal ledger
MCC whitelistingValidates the transaction MCC against approved merchant category codes
Merchant ID whitelistingValidates the transaction merchant ID against approved merchants
Card controlsApplies configured limits and features (daily, weekly, monthly, geographic, and so on)
Custom logicAny authorization rules specific to your product

MCC and merchant ID whitelisting

Partners are required to maintain whitelists for both Merchant Category Codes (MCC) and merchant IDs to control where card transactions can be authorized. During authorization, validate the incoming mcc and merchantID fields against these lists.

  • MCC whitelisting: maintain a list of approved merchant category codes, for example 5411 (grocery stores), 5541 (service stations), 5812 (restaurants). Decline transactions at non-approved MCCs with code 119 (transaction not permitted to cardholder).
  • Merchant ID whitelisting: maintain a list of approved merchant IDs for specific use cases, useful for restricting transactions to specific partner merchants. Decline non-approved merchants with code 119.

Authorization request

Your platform receives authorization requests on this subject:

Subject: psvc.transaction.{partner_id}.auth

Authorization request
{
  "transaction_id": "550e8400-e29b-41d4-a716-446655440000",
  "retrievalRefNumber": "080100756412",
  "account_id": "62570910-bab4-42bd-bf88-8e355833c45a",
  "card_id": "7aa53a6d-5869-c814-5cee-2af0f5d92aa5",
  "timestamp": "2024-01-15T10:30:45.123Z",
  "transactionAmount": 35540,
  "mcc": "5499",
  "merchantID": "123456789012345",
  "merchantName": "MERCHANT NAME",
  "transactionCurrencyCode": "710"
}
FieldTypeDescription
transaction_idstringUUID of the transaction
retrievalRefNumberstringRetrieval reference number for the transaction
account_idstringUUID of the account the card is tied to
card_idstringUUID of the card being used
timestampstringTransaction timestamp (RFC 3339)
transactionAmountnumberAmount in minor units (cents)
mccstringMerchant category code
merchantIDstringMerchant identifier
merchantNamestringMerchant display name
transactionCurrencyCodestringISO 4217 numeric currency code, e.g. 710 for ZAR

Authorization response

Reply on the NATS message itself (the reply subject is handled by the request-reply pattern). The decision field must be an ISO 8583:1993 3-digit response code: 000 approves, any other code declines.

Authorization response
{
  "transaction_id": "550e8400-e29b-41d4-a716-446655440000",
  "retrievalRefNumber": "080100756412",
  "decision": "000",
  "reason": "Transaction approved",
  "processed_at": "2024-01-15T10:30:46.500Z"
}
FieldTypeRequiredDescription
transaction_idstringrequiredEcho of the request's transaction_id
retrievalRefNumberstringrequiredEcho of the request's retrievalRefNumber
decisionstringrequiredISO 8583:1993 3-digit response code. 000 approves, anything else declines
reasonstringrequiredHuman-readable reason for the decision
processed_atstringrequiredWhen your platform processed the request (RFC 3339)

After you reply, the transaction's notifications follow: created, then succeeded when it settles, or failed if you declined it or it was reversed before settling. See the Card Transaction Lifecycle guide.

Implementation example

Subscribing to authorization requests and responding. Pick your client library. These use a standard subscription, which suits a single instance; if you run more than one, use a queue group as shown in Queue Subscriptions.

Authorization responder
import { connect } from "@nats-io/transport-node";
import { jwtAuthenticator } from "@nats-io/nats-core";
 
// Connect to NATS
const nc = await connect({
  servers: ["wss://hermes.sava.africa"],
  authenticator: jwtAuthenticator(jwt, seed),
});
 
// Subscribe to transaction authorization requests
const subject = `psvc.transaction.${config.partnerId}.auth`;
const sub = nc.subscribe(subject);
 
(async () => {
  for await (const msg of sub) {
    try {
      // Parse incoming request
      const authRequest = msg.json();
 
      // Apply your custom authorization logic
      const decision = await evaluateTransaction(authRequest);
 
      // Build response. You must respond within 2 seconds, and the
      // decision field uses ISO 8583:1993 3-digit codes.
      const response = {
        transaction_id: authRequest.transaction_id,
        retrievalRefNumber: authRequest.retrievalRefNumber,
        decision: decision.approved ? "000" : decision.code,
        reason: decision.reason,
        processed_at: new Date().toISOString(),
      };
 
      msg.respond(JSON.stringify(response));
    } catch (err) {
      console.error("Failed to process auth request:", err);
 
      // Send a decline on error to avoid the timeout.
      // 100 (do not honour) is used for system errors.
      msg.respond(JSON.stringify({
        transaction_id: "unknown",
        retrievalRefNumber: "",
        decision: "100",
        reason: "System error",
        processed_at: new Date().toISOString(),
      }));
    }
  }
})();
 
console.log(`Listening for auth requests on: ${subject}`);
 
// Graceful shutdown
process.on("SIGINT", async () => {
  console.log("Shutting down...");
  sub.unsubscribe();
  await nc.drain();
  process.exit(0);
});

Always respond

Respond to every request, including failures inside your handler. A missed reply counts as a timeout and the transaction declines with no reason attached, which is harder to debug than an explicit 100.

Recommended

If you run more than one instance of your authorization service, and most production setups do, subscribe with a queue group so each payment is decided by exactly one instance.

The implementation examples above use a standard subscription: every subscriber receives every authorization request. That's fine when you run a single instance. With more than one, every instance decides and replies to every payment. SAVA uses the first reply and ignores the rest, so your instances can disagree (one approves, another declines) and each payment is evaluated several times.

Standard subscription
What the examples on this page use
SAVA
1 authorization request
NATS
Instance A
decides
Instance B
decides
Instance C
decides
Every instance decides and replies: SAVA uses the first reply
Queue subscription
All instances join the group "auth-workers"
SAVA
1 authorization request
NATS
Instance A
not sent
Instance B
decides
Instance C
not sent
NATS picks one member: decided once

Same subject, same authorization request. The only difference is the queue group name your instances subscribe with. NATS picks a member at random, and a group needs no setup on SAVA's side.

A queue subscription adds a queue group name to the subscription. NATS treats every subscriber using the same name as one group, and delivers each request to exactly one member, chosen at random. Queue groups are standard Core NATS behaviour: the subject, payload, response format and 2-second limit stay the same.

Why it helps

  • One decision per payment. Only one instance evaluates and answers each request.
  • Shared load. Adding instances spreads requests across them instead of multiplying the work.
  • Failover. If an instance stops, NATS sends new requests to the remaining members.
  • Safe deploys. Replace instances one at a time: as long as one member is subscribed, payments keep being authorized.

What to know for authorization

  • Each request gets one chance. SAVA sends a request once and waits 2 seconds. It doesn't retry or try another instance, so a slow or stuck instance means a declined payment. Reply with a decline yourself before the 2 seconds run out rather than letting it time out.
  • Keep at least one instance subscribed. If no instance is subscribed, NATS reports no responders and the payment is declined immediately. Use rolling deploys.
  • Shut down with drain(). Draining finishes the requests an instance has already received before it leaves the group. Closing abruptly drops them, and those payments are declined.
  • Share balances and limits. Any instance can receive any card's request, so keep balances, limits and card state in storage every instance shares. Two taps on the same card can reach two instances at once, so make the balance check and the reservation one atomic step.
  • Use a separate group from notifications, and don't run another subscriber on the authorization subject that replies: it receives every request as well, and its reply races yours.
  • Choose any group name and use the same name on every instance. SAVA never sees it.
Authorization responder with a queue group
import { connect } from "@nats-io/transport-node";
import { jwtAuthenticator } from "@nats-io/nats-core";
 
const nc = await connect({
  servers: ["wss://hermes.sava.africa"],
  authenticator: jwtAuthenticator(jwt, seed),
});
 
const subject = `psvc.transaction.${partnerId}.auth`;
 
// Same queue group name on every instance: each request goes to one of them.
const sub = nc.subscribe(subject, { queue: "auth-workers" });
 
// SAVA waits 2 seconds and never retries, so always reply before that.
const BUDGET_MS = 1500;
 
type Decision = { code: string; reason: string };
 
function withinBudget(work: Promise<Decision>): Promise<Decision> {
  const timeout = new Promise<Decision>((resolve) =>
    setTimeout(() => resolve({ code: "100", reason: "Timed out" }), BUDGET_MS),
  );
  return Promise.race([work, timeout]);
}
 
(async () => {
  for await (const msg of sub) {
    const req = msg.json<AuthRequest>();
    let decision: Decision;
    try {
      // Balances and limits must live in shared storage.
      decision = await withinBudget(evaluateTransaction(req));
    } catch (err) {
      console.error("Failed to process auth request:", err);
      decision = { code: "100", reason: "System error" };
    }
 
    msg.respond(JSON.stringify({
      transaction_id: req.transaction_id,
      retrievalRefNumber: req.retrievalRefNumber,
      decision: decision.code, // "000" approves
      reason: decision.reason,
      processed_at: new Date().toISOString(),
    }));
  }
})();
 
// Finish in-flight requests before leaving the group.
for (const signal of ["SIGINT", "SIGTERM"] as const) {
  process.on(signal, async () => {
    await nc.drain();
    process.exit(0);
  });
}

ISO 8583:1993 response codes

The following response codes are recommended during transaction authorization.

CodeDescriptionPartner use case
000approvedTransaction approved
100do not honourGeneric decline (catch-all)
101expired cardCard expired in partner system
102suspected fraudPartner fraud rules triggered
104restricted cardCard frozen or blocked by partner
110invalid amountAmount validation failed (too low or too high)
116not sufficient fundsUser balance insufficient
119transaction not permitted to cardholderMCC restrictions, card controls blocked
121exceeds withdrawal amount limitDaily, weekly, or monthly limits exceeded
122security violationSecurity rule triggered
123exceeds withdrawal frequency limitVelocity checks (too many transactions)
125card not effectiveCard not yet activated

Simplified core response set

If you want to start with a minimal set:

CodeMeaning
000Approved
100Do Not Honour (generic decline)
116Not Sufficient Funds
119Transaction Not Permitted (MCC or controls)
121Exceeds Amount Limit
104Restricted Card
123Exceeds Frequency Limit

Technical requirements

RequirementDescription
Communication protocolNATS request-reply over wss://hermes.sava.africa
Authentication methodJWT + NKey authentication
Partner identificationPartner ID in the subject path
Authorization subjectpsvc.transaction.{partner_id}.auth
Response timeout2 seconds (transactions auto-declined if exceeded)
Response code formatISO 8583:1993 3-digit codes