CR-API-006 · API SPECIFICATION

API Specification

REST resources, endpoints, payloads, authentication, error model, idempotency, pagination, rate limits and webhooks for the Engagement & Loyalty Platform — including the event-ingestion, scratch-card and milestone APIs.

ConfidentialVersion: v1Base: /api/v1Format: JSONDate: 19 Jul 2026
Implementation status — target contract vs. current build. This document describes the target external API contract (single /api/v1 gateway base, OAuth2/mTLS, application-layer signing, snake_case is illustrative). The current build is a set of mock microservices on distinct ports — core-api :3001 (mounts /api/v1, incl. the new events / triggers / scratch-cards / milestones modules), config-service :3004 (config, capabilities, approvals, audit), mis-reporting :3005, merchant-service :3006, campaign-engine :3103, loyalty-scheduler :3104, axis-txn-provider :3101 (renamed from iob-txn-provider), axis-comms-gateway :3102 (renamed from iob-comms-gateway), plus sample apps rewards-portal :4002, axis-bank-app :4005 and admin-dashboard :5173 — with camelCase JSON bodies and offset (limit/offset) pagination. core-api enables CORS for http://localhost:4002, 4005, 5173. Request signing (HMAC-SHA256) is implemented on core-api but feature-flagged off by default; OAuth2/mTLS are edge concerns for the the Bank deployment, not in this repo. Endpoints below marked roadmap are part of the target contract and not yet implemented.

Conventions

Authentication & Authorization

CallerMechanismNotes
Internal services / channelsOAuth2 client-credentials + mTLSScoped tokens; short-lived; mTLS between zones.
Admin portalOIDC (the Bank IdP) → sessionRBAC enforced per endpoint/action.
Customer (via the Bank's mobile app app)Channel-issued token (exchanged)Customer-scoped; cannot access admin resources.
Partners (fulfilment)Signed webhooks / mTLSEgress only to approved endpoints.

Authorization uses scopes such as accrual:write, campaign:write, ledger:read, redemption:write, admin:approve. See RBAC in CR-CFG-008.

Standard Headers

# Request
Authorization: Bearer <token>
Content-Type: application/json
X-Request-Id: 5e9c…           # correlation
Idempotency-Key: 3f1a-…-acc   # required on POST that mutate value

# Response
X-Request-Id: 5e9c…
X-RateLimit-Remaining: 480

Message Signing (Reward Redemptions & Value Mutations)

In addition to transport security (TLS/mTLS) and bearer tokens, every reward redemption and value-mutating request (/redemptions, /transactions:reverse, /ledger/adjustments) and every settlement file MUST carry an application-layer digital signature. This binds the request to the calling channel, makes payloads tamper-evident, and — combined with a nonce + timestamp + idempotency key — defeats replay. Full key-management, rotation and verification flow in CR-SEC-009.

Signing scheme

AspectSpecification
Default algorithmHMAC-SHA256 with a per-client shared secret (symmetric); secret provisioned out-of-band and stored in Vault.
High-assurance optionRSASSA-PSS (RSA-2048+) or ECDSA-P256 (ES256) asymmetric signatures referenced by X-Signature-KeyId; partner holds the private key, the Engagement Suite verifies with the registered public key.
Canonical stringMETHOD\nPATH\nX-Timestamp\nX-Nonce\nIdempotency-Key\nSHA256(body) — joined with newline (\n); body hash is lowercase hex of the raw request bytes.
Signature valueBase64 of HMAC-SHA256(secret, canonicalString) (or the asymmetric signature over the canonical string).
Replay windowX-Timestamp must be within ±300s of server time; X-Nonce must be unique per client for 10 minutes (cached, rejected on reuse).
IdempotencyIdempotency-Key is covered by the signature so a replay with a new nonce still collapses to the original result (no double redemption).
Settlement filesBatch/settlement files signed with a detached signature (.sig sidecar) over the SHA-256 of the file; key id named in the manifest; verified before ingest.

Required signing headers

# On signed (value-mutating) requests, in addition to the standard headers
X-Signature: t=2026-06-06T10:21:00Z,v1=Base64(HMAC-SHA256(secret, canonical))
X-Signature-KeyId: chan-axisapp-2026Q2   # selects secret/public key & algorithm
X-Signature-Alg: HMAC-SHA256            # or RSA-PSS-SHA256 | ES256
X-Nonce: 9f3c1d2e-7a44-4b90-bb12-...      # unique per client, 10-min memory
X-Timestamp: 2026-06-06T10:21:00Z        # ISO-8601 UTC, ±300s window
Idempotency-Key: rdm-7c2a-001            # covered by the signature

Example — signed redemption request

POST /api/v1/redemptions
Authorization: Bearer <token>
Content-Type: application/json
X-Request-Id: 5e9c-...
Idempotency-Key: rdm-7c2a-001
X-Signature-KeyId: chan-axisapp-2026Q2
X-Signature-Alg: HMAC-SHA256
X-Nonce: 9f3c1d2e-7a44-4b90-bb12-2a91c0d77f10
X-Timestamp: 2026-06-06T10:21:00Z
X-Signature: t=2026-06-06T10:21:00Z,v1=Base64(HMAC-SHA256(secret,canonical))
{
  "account_id": "acct_8f12",
  "catalogue_sku": "GV-AMZ-500",
  "method": "voucher",
  "otp_token": "otp_..."
}

// canonical string the signature is computed over:
//   POST
//   /api/v1/redemptions
//   2026-06-06T10:21:00Z
//   9f3c1d2e-7a44-4b90-bb12-2a91c0d77f10
//   rdm-7c2a-001
//   <lowercase-hex SHA256 of the raw JSON body>

// 201 Created — response is itself signed for return-path integrity
X-Signature-KeyId: rewards-resp-2026Q2
X-Signature: t=2026-06-06T10:21:02Z,v1=Base64(...)
{
  "redemption_id": "rdm_3320",
  "status": "fulfilled",
  "points_debited": 5000,
  "voucher": { "code_masked": "AMZ-****-9KQ2", "value_minor": 50000, "expiry": "2026-12-31" }
}

Server-side verification order

  1. Resolve X-Signature-KeyId → algorithm + secret/public key (reject UNKNOWN_KEY if absent/disabled).
  2. Check X-Timestamp is within ±300s → else SIGNATURE_EXPIRED (401).
  3. Check X-Nonce not seen for this client within the window → else NONCE_REPLAYED (409).
  4. Recompute the canonical string + body hash; constant-time compare the signature → else SIGNATURE_INVALID (401).
  5. Apply idempotency on Idempotency-Key + request fingerprint; only then process and emit a signed response.

Event Triggers, Scratch Cards & Milestones v1

The engagement core. Bank systems POST lifecycle events to POST /api/v1/events on core-api :3001; the trigger engine evaluates rules and issues rewards (usually scratch cards). Credit-card spend does not use this API — it keeps flowing through POST /api/v1/transactions; the engine additionally evaluates spend milestones (internal source CARD_SPEND) after each posted card transaction. All of these endpoints are served under CORS for http://localhost:4002, 4005, 5173. Ingestion is idempotent on eventRef; scratch reveal and ledger writes are idempotent by key.
MethodPathPurposeScope
POST/eventsIngest a bank event; evaluate triggers & milestones; issue rewards. Idempotent on eventRef.event:write
GET/events?limit=&account=Recent events (admin).event:read
GET/triggersList trigger rules (admin).trigger:read
GET/scratch-cards?account=&status=List an account's scratch cards; hidden prize NOT returned for ISSUED.reward:read
POST/scratch-cards/:id/scratchReveal a scratch card (idempotent); POINTS prizes post an ACCRUAL credit.reward:write
GET/milestones?account=Milestone definitions joined with the account's current progress.milestone:read

Canonical event types (v1)

eventTypeFired by the bank system when…
USER_REGISTEREDcustomer completes first-time registration on the Bank's mobile app.
CARD_ACTIVATEDdebit/credit card activated.
KYC_COMPLETEDfull KYC done.
UPI_TRANSACTIONa UPI payment succeeds (payload has amountMinor, vpa, merchant).
BILL_PAYMENTbill pay succeeds (payload has biller, amountMinor).
SALARY_CREDITsalary credited to account.
FD_BOOKEDfixed deposit booked (payload has amountMinor, tenureMonths).

Example — ingest an event (POST /api/v1/events)

POST /api/v1/events
{
  "eventRef": "evt-upi-000123",          // UNIQUE — idempotency key; replay = same response, no double reward
  "eventType": "UPI_TRANSACTION",
  "cardRef": "card_demo_nilesh",          // OR "customerRef" OR "accountId" — same resolution as accounts API
  "amountMinor": 45000,
  "occurredAt": "2026-07-19T10:20:30Z",
  "payload": { "vpa": "merchant@upi", "merchant": "Blinkit" }
}

// 201 Created
{
  "eventId": 17, "duplicate": false, "accountId": 1,
  "evaluations": [ { "triggerId": 3, "triggerName": "First UPI transaction", "matched": true,
                     "reward": { "type": "SCRATCH_CARD", "scratchCardId": 9 } } ],
  "scratchCards": [ { "scratchCardId": 9, "state": "ISSUED", "expiresAt": "2026-08-18" } ]
}
Idempotency: re-posting the same eventRef returns the original response with "duplicate": true and issues no additional reward, ledger entry or milestone progress (NFR-04).

Example — reveal a scratch card (POST /api/v1/scratch-cards/:id/scratch)

POST /api/v1/scratch-cards/9/scratch

// 200 OK — POINTS prize posts an idempotent ACCRUAL credit (source_type scratch_card)
{
  "prize": { "kind": "POINTS", "points": 200, "label": "200 Reward Points" },
  "ledgerEntryId": 55,
  "balance": { "available": 2700 }
}

Example — milestones (GET /api/v1/milestones?account=)

GET /api/v1/milestones?account=card_demo_nilesh

// 200 OK — definitions joined with the account's current progress
[
  { "code": "UPI_STREAK_3_WEEKLY", "name": "3 UPI payments this week", "window": "weekly",
    "targetCount": 3, "progressCount": 2, "status": "in_progress" },
  { "code": "SPEND_25K_MONTHLY", "name": "Spend ₹25,000 this month", "window": "monthly",
    "targetAmountMinor": 2500000, "progressAmountMinor": 1840000, "status": "in_progress" }
]
Seeded trigger rules & milestones (the Bank journey). First USER_REGISTERED → Welcome scratch card (100/250/500 pts weighted); first CARD_ACTIVATED → Activation card (150/300/750); first UPI_TRANSACTION → First-UPI card (50/100/200); first BILL_PAYMENT → First-bill card (50/150); first KYC_COMPLETED → 100 pts direct (no scratch card); FD_BOOKED → Premium card (500 pts / ₹250 Amazon voucher); SALARY_CREDIT monthly (max 1/month) → Salary-day card (100/250). Milestones: UPI_STREAK_3_WEEKLY, SPEND_25K_MONTHLY (→ 1,000-pt card via CARD_SPEND), BILL_PAY_3_MONTHLY.

Accrual & Transactions

MethodPathPurposeScope
POST/transactionsIngest a transaction (single).accrual:write
POST/transactions:batchIngest a batch (file/stream).accrual:write
GET/transactions/{id}Fetch a transaction & accrual status.accrual:read
POST/transactions/{id}/reverseReverse a transaction (full clawback). Optional body { refundAmountMinor } → pro-rata partial-refund clawback. Clawback beyond available balance is carried as recoverable debt (never drives the balance negative).accrual:write
GET/accruals?account_id=List accrual entries for an account.ledger:read

Example — reverse (full & partial refund)

POST /api/v1/transactions/TXN-9011/reverse        # full reversal
→ { "reversed": true, "refundType": "full", "pointsDebited": 1200,
      "recoveredFromAvailable": 1200, "clawbackShortfall": 0 }

POST /api/v1/transactions/TXN-9011/reverse
{ "refundAmountMinor": 400000 }                          # 40% partial refund of a ₹10,000 purchase
→ { "reversed": true, "refundType": "partial", "pointsDebited": 480,
      "recoveredFromAvailable": 480, "clawbackShortfall": 0 }   # original txn stays 'posted'
Negative-balance safety: if the clawback exceeds the cardholder’s available balance (points already redeemed), the balance is clamped at 0 and the remainder is carried in point_balance.clawback_pending — a recoverable debt that the next accrual pays down before crediting the cardholder. The invariant (available − clawback_pending) == net ledger position always holds. See CR-EDG-017.

Example — ingest transaction

POST /api/v1/transactions
{
  "external_txn_ref": "AXISTXN-99001",
  "account_ref": "acct_8f12",
  "amount_minor": 500000,            // ₹5,000.00
  "currency": "INR",
  "mcc": "5812",                     // dining
  "merchant_id": "MER-2231",
  "channel": "POS",
  "txn_type": "purchase",
  "txn_datetime": "2026-06-06T10:21:00Z"
}

// 201 Created
{
  "txn_id": "txn_7781",
  "accrual_status": "accrued",
  "points_awarded": 300,            // 3× dining accelerator
  "rule_id": "rule_dining_3x",
  "ledger_entry_id": "le_55120"
}

Campaigns & Milestones

MethodPathPurposeScope
POST/campaignsCreate a campaign (draft).campaign:write
PUT/campaigns/{id}Update draft campaign.campaign:write
POST/campaigns/{id}:submitSubmit for approval (maker).campaign:write
POST/campaigns/{id}:approveApprove / reject (checker).admin:approve
POST/campaigns/{id}:simulateDry-run on sample population.campaign:read
GET/campaigns/{id}/enrolmentsEnrolment & progress.campaign:read
GET/milestones?account_id=Milestone progress for a customer.campaign:read

Ledger & Balances

MethodPathPurposeScope
GET/accountsList loyalty accounts (paginated).account:read
GET/accounts/{idOrRef}Customer 360 lookup — resolve by numeric account_id or card_ref / customer_ref; returns the profile with its balance projection embedded.account:read
GET/accounts/{id}/balanceAvailable / pending / locked / lifetime.ledger:read
GET/accounts/{id}/ledgerPaginated ledger entries.ledger:read
POST/ledger/adjustmentsManual adjustment (maker-checker).ledger:adjust

Redemption & Catalogue

As implemented — redemption runs on redemption-service (:3005). Requests use camelCase (accountId or cardRef, sku, method); the optional Idempotency-Key header guarantees exactly-once. Every response is wrapped { "simulated": true, … } — the points are really debited from the ledger (a REDEMPTION debit + balance decrement, in one ACID transaction) and a masked voucher is issued; only the downstream fulfilment is deferred to the Cheggout marketplace. There is no OTP step and no GET /redemptions/{id} in the build.
MethodPathPurposeScope
GET/catalogue?category=Browse the reward catalogue (active SKUs).catalogue:read
POST/redemptionsRedeem points (idempotent). Debits the ledger, issues a masked voucher.redemption:write
POST/redemptions/{id}/reverseReverse a redemption — credits points back (idempotent).redemption:write
GET/accounts/{id}/redemptionsAn account's redemptions + current balance.redemption:read
GET/accounts/{id}/vouchersVoucher vault for an account.redemption:read
GET/redemptions?limit=Recent redemptions across the programme (admin list).redemption:read

Example — redeem points

POST :3005/redemptions
Idempotency-Key: rdm-7c2a-001
{
  "accountId": 8,
  "sku": "GV-AMZ-500",
  "method": "voucher"
}

// 201 Created
{
  "simulated": true,
  "note": "fulfilment deferred to Cheggout; points are really debited",
  "replayed": false,
  "redemption": { "redemptionId": "3320", "catalogueSku": "GV-AMZ-500", "method": "voucher",
                  "pointsDebited": 5000, "status": "simulated", "idempotencyKey": "rdm-7c2a-001" },
  "voucher": { "codeMasked": "AMZ-••••-9KQ2", "valueMinor": 50000, "expiryDate": "2026-12-31", "status": "active" },
  "balance": { "available": 13920, "lifetimeRedeemed": 5000 }
}

Merchants, Notifications, Admin & Reports

MethodPathPurpose
POST/merchantsOnboard merchant.
POST/merchants/{id}/offersCreate funded offer.
GET/settlements?period=Merchant settlement report.
POST/notifications:sendTrigger a templated notification.
GET/templatesList notification templates.
GET/reportsList report definitions + per-report supported_filters.
GET/reports/{key}/runRun a standard report (liability, accrual, redemption, campaign, expiry/reversal, budget, audit) — filterable, see below.
GET/recon/runs/{id}Reconciliation run & exceptions.
GET/audit?entity=Audit trail query (read-only).

Flexible Reporting Dimensions

Every standard report accepts an orthogonal set of filter query-params; each report applies only the dimensions its query shape supports (discoverable via GET /reports → supported_filters). Filters compose with AND.

DimensionQuery param(s)Applies to
Useraccount_id, customer_ref, card_refpoints_liability, accrual_summary, redemption_summary, expired_reversed
Card segmentcard_variant, tierpoints_liability, accrual_summary, redemption_summary, expired_reversed
Campaigncampaign_idaccrual_summary, campaign_performance, budget_utilisation
Date rangefrom, toaccrual_summary, redemption_summary, expired_reversed, audit_trail
Othermcc, method, category, point_value_minoraccrual_summary (mcc); redemption_summary (method, category); points_liability (point_value_minor)
# accrual earned by a single Signature-card customer on one campaign, in May
GET /reports/accrual_summary/run?card_variant=SIGNATURE&customer_ref=cust_8f12&campaign_id=64&from=2026-05-01&to=2026-05-31

# outstanding points liability for one card segment
GET /reports/points_liability/run?tier=PLATINUM

Idempotency

All value-mutating POSTs (transactions, redemptions, adjustments) require an Idempotency-Key. The key + request fingerprint is stored; a repeat returns the original result without re-executing — guaranteeing no double accrual/redemption (NFR-04).

Pagination, Filtering & Sorting

GET /api/v1/accounts/acct_8f12/ledger?cursor=eyJ…&limit=50&from=2026-05-01&sort=-posted_at

{
  "data": [ /* … */ ],
  "page": { "next_cursor": "eyJ…", "limit": 50, "has_more": true }
}

Error Model

{
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Available balance is lower than required points.",
    "request_id": "5e9c…",
    "details": { "required": 5000, "available": 3200 }
  }
}
HTTPCodeMeaning
400VALIDATION_ERRORMalformed/invalid payload.
401UNAUTHENTICATEDMissing/invalid token.
403FORBIDDENScope/role not permitted.
404NOT_FOUNDResource absent.
409CONFLICT / DUPLICATEIdempotency/version conflict.
422INSUFFICIENT_BALANCEBusiness rule failure.
429RATE_LIMITEDThrottled — see Retry-After.
5xxINTERNAL / UPSTREAMServer / partner failure (safe to retry idempotently).

Signing & replay error codes

HTTPCodeMeaning
401SIGNATURE_INVALIDSignature does not match the recomputed canonical string (tamper / wrong key / bad secret).
401SIGNATURE_EXPIREDX-Timestamp outside the ±300s window.
401UNKNOWN_KEYX-Signature-KeyId not registered, disabled or revoked.
400SIGNATURE_MISSINGRequired signing header(s) absent on a value-mutating request.
409NONCE_REPLAYEDX-Nonce already seen for this client within the replay window.

Rate Limits & Webhooks

Example — fulfilment webhook & signature verification

# Inbound from partner (mTLS, source allow-listed)
POST /api/v1/webhooks/fulfilment
X-Signature-KeyId: partner-vouchers-2026Q2
X-Signature-Alg: HMAC-SHA256
X-Nonce: 5b1f-...
X-Timestamp: 2026-06-06T10:21:05Z
X-Signature: t=2026-06-06T10:21:05Z,v1=Base64(HMAC-SHA256(partnerSecret,canonical))
{
  "event": "fulfilment.completed",
  "redemption_id": "rdm_3320",
  "partner_ref": "VENDOR-AMZ-77120",
  "status": "issued",
  "voucher_code_token": "tok_...",   // tokenised; raw code never in webhook
  "occurred_at": "2026-06-06T10:21:04Z"
}

# Verification (pseudocode) — must pass ALL before processing
key   = lookupKey(headers["X-Signature-KeyId"])          // else 401 UNKNOWN_KEY
assert abs(now - X-Timestamp) <= 300s                     // else 401 SIGNATURE_EXPIRED
assert nonceStore.putIfAbsent(keyId, X-Nonce, ttl=10m)   // else 409 NONCE_REPLAYED
canonical = "POST\n/api/v1/webhooks/fulfilment\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256hex(rawBody)
expected  = base64(hmacSha256(key.secret, canonical))    // or verify(key.pub, sig, canonical)
assert constantTimeEquals(expected, X-Signature.v1)      // else 401 SIGNATURE_INVALID
// only now: advance the redemption saga (idempotent on redemption_id)

// 200 OK
{ "received": true, "redemption_id": "rdm_3320" }

Full machine-readable contract is published as an OpenAPI 3.1 document (openapi.yaml) generated from the services.