# Core Banking Integration Guide

**How to connect your Core Banking system to Monetarie SPB**

**Version**: 1.0
**Date**: 2026-02-07
**Audience**: Core Banking vendors, integration engineers, technical architects

---

## 1. Overview

Monetarie SPB acts as the middleware layer between your Core Banking system and BACEN's SPB (Sistema de Pagamentos Brasileiro). Your Core Banking sends transaction requests to Monetarie SPB via REST API or NATS messaging. Monetarie handles the full BACEN protocol: XML message generation, XMLDSig signing, IBM MQ routing, response processing, and settlement tracking.

```
+------------------+          +------------------+          +------------------+
|                  |  REST    |                  |  IBM MQ  |                  |
|  Core Banking    | -------> |  Monetarie SPB      | -------> |  BACEN RSFN      |
|  (your system)   | <------- |  (middleware)     | <------- |  (central bank)  |
|                  |  Events  |                  |  XML/MQ  |                  |
+------------------+          +------------------+          +------------------+
```

**What Monetarie SPB handles for you:**
- BACEN message catalog (979 message types, v5.11)
- XMLDSig RSA-SHA256 signing with ICP-Brasil certificates
- IBM MQ domain routing (5 domains per BACEN Manual de Redes v9.3)
- Message state lifecycle (pending → sent → confirmed/failed)
- Retry logic with exponential backoff
- 5,306+ error code mapping
- Audit trail (10-year retention)
- Alcada/Visto approval workflow for high-value transactions

**What your Core Banking provides:**
- Transaction origination (TED, DOC, Boleto, STR, LPI)
- Account management
- Balance management
- Customer data
- Compliance checks (AML/KYC)

---

## 2. Integration Architecture

### 2.1 Integration Patterns

Monetarie SPB supports two integration patterns:

#### Pattern A: REST API (recommended for most integrations)

Your Core Banking calls Monetarie SPB REST API endpoints to submit operations and query status.

```
Core Banking  --HTTP POST-->  Monetarie SPB /api/operations  --IBM MQ-->  BACEN
Core Banking  <--HTTP GET---  Monetarie SPB /api/operations/:id
Core Banking  <--Webhook---   Monetarie SPB (on state change)
```

**Pros**: Simple, standard HTTP, easy to implement, supports any programming language.
**Cons**: Polling required unless webhooks are configured.

#### Pattern B: NATS Messaging (recommended for high-throughput)

Your Core Banking connects directly to the NATS JetStream cluster and publishes/subscribes to topics.

```
Core Banking  --NATS pub-->  spb.operations.new  -->  Monetarie SPB  --IBM MQ-->  BACEN
Core Banking  <--NATS sub--  spb.operations.confirmed
Core Banking  <--NATS sub--  spb.operations.failed
```

**Pros**: Real-time, bidirectional, high throughput (10K+ msgs/sec), at-least-once delivery.
**Cons**: Requires NATS client library, more complex to implement.

### 2.2 Authentication

All API calls require a JWT token:

```bash
# 1. Obtain token
POST /api/auth/login
Content-Type: application/json

{
  "email": "api@your-institution.com",
  "password": "your-secure-password"
}

# Response
{
  "success": true,
  "token": "eyJhbGci...",
  "user": {
    "id": 42,
    "role": "api_user",
    "institution_ispb": "12345678"
  }
}

# 2. Use token in all subsequent requests
Authorization: Bearer eyJhbGci...
```

For NATS integration, authentication is handled at the NATS connection level with credentials.

---

## 3. REST API Integration

### 3.1 Base URL

| Environment | URL |
|-------------|-----|
| Development | `https://spbapi-dev.fluxiq.com.br/api` |
| Homologation | `https://spbapi-hml.fluxiq.com.br/api` |
| Production | `https://spbapi.fluxiq.com.br/api` |

### 3.2 Submitting Operations

#### Create a New Operation (TED/DOC/STR)

```bash
POST /api/operations
Authorization: Bearer {token}
Content-Type: application/json

{
  "type": "STR",
  "message_type": "STR0001",
  "amount": 1500000.00,
  "currency": "BRL",
  "payer": {
    "ispb": "12345678",
    "account": "123456-7",
    "name": "Empresa ABC Ltda",
    "cpf_cnpj": "12345678000100"
  },
  "beneficiary": {
    "ispb": "60701190",
    "account": "987654-3",
    "name": "Fornecedor XYZ S.A.",
    "cpf_cnpj": "98765432000100"
  },
  "description": "Pagamento NF 12345",
  "priority": 1
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": 1234,
    "message_id": "MSG0000001234",
    "state": "pending",
    "message_type": "STR0001",
    "created_at": "2026-02-07T10:00:00Z"
  }
}
```

#### Query Operation Status

```bash
GET /api/operations/1234
Authorization: Bearer {token}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": 1234,
    "message_id": "MSG0000001234",
    "state": "confirmed",
    "message_type": "STR0001",
    "amount": 1500000.00,
    "confirmation_code": "BACEN20260207100500",
    "sent_at": "2026-02-07T10:00:01Z",
    "confirmed_at": "2026-02-07T10:00:05Z"
  }
}
```

#### Send Operation to Clearing

```bash
POST /api/operations/1234/send
Authorization: Bearer {token}
```

This triggers the full BACEN message flow: XML generation → XMLDSig signing → IBM MQ send.

### 3.3 Querying Messages

```bash
# List all messages with filtering
GET /api/messages?message_type=STR0001&state=confirmed&limit=50&offset=0
Authorization: Bearer {token}

# Get specific message with full XML
GET /api/messages/1234
Authorization: Bearer {token}

# Get message categories
GET /api/messages/categories
Authorization: Bearer {token}

# Get possible message states
GET /api/messages/states
Authorization: Bearer {token}
```

### 3.4 Webhooks (Event Notifications)

Configure webhooks to receive real-time notifications when operations change state:

```bash
# Webhook payload sent to your URL
POST https://your-core-banking.com/webhook/fluxiq

{
  "event": "operation.confirmed",
  "timestamp": "2026-02-07T10:00:05Z",
  "data": {
    "operation_id": 1234,
    "message_id": "MSG0000001234",
    "state": "confirmed",
    "message_type": "STR0001",
    "confirmation_code": "BACEN20260207100500"
  }
}
```

Events: `operation.created`, `operation.sent`, `operation.confirmed`, `operation.failed`, `operation.cancelled`

### 3.5 Dashboard & Monitoring

```bash
# Dashboard statistics
GET /api/dashboard/stats

# Account balances (STR, LPI, CIP, SELIC)
GET /api/balances

# Clearing system status
GET /api/clearings/status

# Reports
GET /api/reports/audit-log?from=2026-02-01&to=2026-02-07
GET /api/reports/message-movement?date=2026-02-07
GET /api/reports/reserve-statement
GET /api/reports/message-stats
```

---

## 4. NATS Messaging Integration

### 4.1 Connection

```python
# Python example using nats-py
import nats

nc = await nats.connect("nats://10.10.40.5:4222")
js = nc.jetstream()
```

```javascript
// Node.js example using nats.js
const { connect } = require('nats');
const nc = await connect({ servers: 'nats://10.10.40.5:4222' });
const js = nc.jetstream();
```

```elixir
# Elixir example using Gnat
{:ok, conn} = Gnat.start_link(%{host: "10.10.40.5", port: 4222})
```

### 4.2 Publishing Operations

```json
// Publish to: spb.operations.new
{
  "type": "STR",
  "message_type": "STR0001",
  "amount": 1500000.00,
  "currency": "BRL",
  "payer_ispb": "12345678",
  "payer_account": "123456-7",
  "payer_name": "Empresa ABC Ltda",
  "beneficiary_ispb": "60701190",
  "beneficiary_account": "987654-3",
  "beneficiary_name": "Fornecedor XYZ S.A.",
  "description": "Pagamento NF 12345",
  "correlation_id": "your-unique-id-12345",
  "timestamp": "2026-02-07T10:00:00Z"
}
```

### 4.3 Subscribing to Events

```json
// Subscribe to: spb.operations.confirmed
{
  "event": "confirmed",
  "operation_id": 1234,
  "message_id": "MSG0000001234",
  "correlation_id": "your-unique-id-12345",
  "confirmation_code": "BACEN20260207100500",
  "timestamp": "2026-02-07T10:00:05Z"
}

// Subscribe to: spb.operations.failed
{
  "event": "failed",
  "operation_id": 1234,
  "message_id": "MSG0000001234",
  "correlation_id": "your-unique-id-12345",
  "error_code": "BSMP0001",
  "error_description": "Saldo insuficiente",
  "retryable": true,
  "timestamp": "2026-02-07T10:00:03Z"
}
```

### 4.4 NATS Topics Reference

| Topic | Direction | Purpose |
|-------|-----------|---------|
| `spb.operations.new` | Core Banking → SPB | Submit new operation |
| `spb.operations.confirmed` | SPB → Core Banking | Operation confirmed by BACEN |
| `spb.operations.failed` | SPB → Core Banking | Operation failed |
| `spb.operations.cancelled` | SPB → Core Banking | Operation cancelled |
| `spb.messages.state_changed` | SPB → Core Banking | Any message state change |
| `spb.balances.updated` | SPB → Core Banking | Balance update notification |
| `spb.clearings.status` | SPB → Core Banking | Clearing system status change |

---

## 5. BACEN Message Types

### 5.1 Supported Clearing Systems

| System | Code | Messages | Purpose |
|--------|------|----------|---------|
| STR | STR0001-STR0010 | 10 | Reserve transfers (LBTR) |
| LPI | LPI0001-LPI0005 | 5 | Instant payment account operations |
| PAG | PAG0101-PAG0102 | 2 | TED payments |
| CAM | CAM0001-CAM0005 | 5 | Foreign exchange |
| SEL | SEL0001-SEL0005 | 5 | SELIC (government securities) |
| LDL | LDL0001-LDL0005 | 5 | Deferred net settlement |
| DDA | DDA0001-DDA0005 | 5 | Authorized direct debit |
| CIR | CIR0001-CIR0005 | 5 | Cash operations |
| CTP | CTP0001-CTP0005 | 5 | Custody and securities transfer |
| GEN | GEN0001-GEN0015 | 3 | General SPB control |

### 5.2 Message Lifecycle

```
pending → sent → received → acknowledged → confirmed
                                         → failed (retryable)
                                         → failed (permanent)
pending → cancelled (by operator)
```

| State | Meaning |
|-------|---------|
| `pending` | Created, awaiting processing |
| `sent` | Sent to BACEN via IBM MQ |
| `received` | BACEN acknowledged receipt |
| `acknowledged` | BACEN processing |
| `confirmed` | BACEN confirmed (settlement complete) |
| `failed` | BACEN rejected (check error_code) |
| `cancelled` | Cancelled by operator before sending |

---

## 6. Integration Steps

### Step 1: Registration

1. Request an ISPB code from BACEN (if you don't have one)
2. Contact Monetarie to provision your institution in the platform
3. Receive API credentials (email + password) and ISPB assignment

### Step 2: Development Environment

1. Access dev API: `https://spbapi-dev.fluxiq.com.br/api`
2. Login to obtain JWT token
3. Explore the API using the documentation at `https://spbdocs-dev.fluxiq.com.br`
4. Use the simulator (`spb-simulator`) for BACEN response simulation

### Step 3: API Integration

1. Implement authentication (JWT token management)
2. Implement operation submission (`POST /api/operations`)
3. Implement status polling or webhook receiver
4. Implement error handling (retry on transient errors, alert on permanent failures)
5. Implement balance monitoring (`GET /api/balances`)

### Step 4: NATS Integration (optional)

1. Install NATS client library for your platform
2. Connect to NATS cluster
3. Publish to `spb.operations.new`
4. Subscribe to `spb.operations.confirmed` and `spb.operations.failed`
5. Implement correlation ID tracking

### Step 5: Homologation

1. Switch to homologation environment
2. Run BACEN certification tests (message exchange, error handling, settlement)
3. Validate all message types your institution uses
4. Load test with production-like volumes
5. Security audit (penetration testing, credential rotation)

### Step 6: Go-Live

1. Switch to production environment
2. Activate IBM MQ connection to BACEN RSFN
3. Install ICP-Brasil certificates for XMLDSig
4. Configure production alcadas (authorization levels)
5. Train operators on the admin portal
6. Enable monitoring alerts

---

## 7. Error Handling

### 7.1 HTTP Error Codes

| Code | Meaning | Action |
|------|---------|--------|
| 200 | Success | Process response |
| 400 | Bad request | Fix request payload |
| 401 | Unauthorized | Refresh JWT token |
| 403 | Forbidden | Check user role/permissions |
| 404 | Not found | Check resource ID |
| 422 | Validation error | Check response body for details |
| 500 | Server error | Retry with backoff |

### 7.2 BACEN Error Codes

Monetarie maps 5,306+ BACEN error codes. The `bacen_error_codes` table provides:
- Error code
- Description
- Category (validation, authentication, business, system)
- Retry policy (retryable or permanent)
- Suggested action

```bash
# Query error codes
GET /api/messages/1234
# Response includes error_code and error_description when state is "failed"
```

### 7.3 Retry Strategy

For retryable errors, Monetarie implements exponential backoff:
- Attempt 1: immediate
- Attempt 2: 1 second
- Attempt 3: 2 seconds
- Attempt 4: 4 seconds
- Attempt 5: 8 seconds (max 3 retries by default)

After max retries, the message is moved to the Dead Letter Queue (DLQ).

---

## 8. Security Requirements

### 8.1 For REST API Integration

- TLS 1.2+ for all API calls (enforced by load balancer)
- JWT tokens must be stored securely (not in URLs, not in logs)
- Rotate API credentials every 90 days
- Implement IP allowlisting for production

### 8.2 For NATS Integration

- TLS connection to NATS cluster (production)
- NATS credentials (user/password or NKey authentication)
- Topic-level authorization (read/write per institution)

### 8.3 For Production

- ICP-Brasil certificates for XMLDSig (mandatory for BACEN)
- mTLS for IBM MQ connections
- HSM integration for private key storage (recommended)

---

## 9. Support

| Channel | Purpose |
|---------|---------|
| API Docs | `https://spbdocs-dev.fluxiq.com.br` |
| Admin Portal | `https://spbadmin-dev.fluxiq.com.br` |
| BACEN Simulator | Available in dev environment for testing |
| Integration Support | Contact Monetarie engineering team |

---

*Document generated 2026-02-07. This guide covers the Monetarie SPB platform v1.0.*
