> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lerian.studio/llms.txt
> Use this file to discover all available pages before exploring further.

# Developer guide

> Implement Bank Transfer integrations correctly — idempotency, retry strategy, state handling, and webhook validation patterns for reliable transfers.

This guide is for developers who implement the Bank Transfer plugin integration. It covers the patterns and decisions that go beyond individual endpoint calls: idempotency, retry strategy, state handling, and webhook validation.

For endpoint parameters and response schemas, see the [API Reference](/en/reference/midaz/plugins/ted/initiate-transfer).

## Idempotency

***

Every mutating request (initiate, process, cancel) requires an `X-Idempotency` header. If you send the same key twice, the plugin returns the original response without creating a duplicate operation.

**Rules:**

* Use a UUID v4 or a unique business identifier (e.g. your internal order ID)
* Maximum length: 255 characters
* The plugin scopes each key to the effective organization. The same key from two organizations counts as two distinct requests.
* The plugin returns a cached response for the configured idempotency window (`IDEMPOTENCY_RETRY_WINDOW_SEC`, default 300 seconds)
* A replayed response is byte-identical to the original: same status code, same body. The response has no header to mark a replay, so design your client to stay safe in either case.

```http theme={null}
POST /v1/transfers/initiate
X-Organization-Id: 019c9ac2-3f5d-7df9-9215-bdccc1451def
X-Idempotency: 7f3d9a1b-4e2c-4f8a-b3d1-9e6f2a4c8b7e
```

<Warning>
  Do not reuse idempotency keys across different operations. Do not reuse an initiate key to process or cancel the same transfer.
</Warning>

### Duplicate detection

Beyond idempotency keys, the plugin detects content-based duplicates. It builds a fingerprint from:

* `senderAccountId`
* recipient details (ISPB, branch, account, holder document)
* amount
* purpose

The plugin stores the fingerprint in Redis for 5 minutes. The default is 300 seconds. Operators tune it per tenant through the systemplane setting `idempotency.duplicate_guard_ttl_seconds`. The organization is not part of the fingerprint. Tenant isolation comes from the Redis key prefix. The plugin rejects the request with `409 BTF-0012` if the client already submitted a matching transfer inside the window.

This catches cases where the client sends the same transfer with a different idempotency key. One example is a retry after a timeout, when the client did not receive the original response.

## Retry strategy

***

Use exponential backoff for transient errors. Do not retry every error.

| HTTP status | Retry? | Notes                                                                     |
| ----------- | ------ | ------------------------------------------------------------------------- |
| `400`       | No     | Validation error — fix the request before retrying                        |
| `404`       | No     | Not found — the resource does not exist                                   |
| `409`       | No     | Duplicate — idempotent; use the original response                         |
| `410`       | No     | Expired — create a new initiation                                         |
| `422`       | No     | Business rule (operating hours, limits) — the condition must change first |
| `429`       | Yes    | Rate limit — wait for the `Retry-After` header value (seconds)            |
| `500`       | Yes    | Internal error — retry with backoff                                       |
| `503`       | Yes    | Unavailable — retry with backoff                                          |

**Recommended backoff schedule for 5xx/503:** 0s, 5s, 25s, 60s, 120s (5 attempts total).

<Note>
  When JD SPB is unavailable, the response is `HTTP 503`. The `error.code` field then carries the raw JD vendor code — for example, `TRANSPORT` for transport failures or `ACE95` for timeouts. The plugin does not wrap JD-chain failures in a `BTF-` code. Flag the transfer for manual reconciliation after the retries run out. Do not retry without limit. The JD SPB network has defined operating hours.
</Note>

## State handling

***

### TED OUT state machine

Transfers follow a strict progression. You cannot cancel a transfer after it leaves `CREATED` or `PENDING`.

<Frame>
  <img src="https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/ted-state-machine-ted-out.svg?fit=max&auto=format&n=SEOef3JqTInYAAau&q=85&s=87af4c9fd8729f61190f55afb4fc9885" alt="TED OUT state machine" width="1068" height="552" data-path="images/en/d2/ted-state-machine-ted-out.svg" />
</Frame>

**What to do in each state:**

| State        | Meaning                                    | Recommended action                                         |
| ------------ | ------------------------------------------ | ---------------------------------------------------------- |
| `CREATED`    | Confirmed by user, queued for submission   | Show "Processing" in UI; poll or wait for webhook          |
| `PENDING`    | Submitted to JD, awaiting acknowledgment   | Show "Processing"; do not allow cancellation               |
| `PROCESSING` | JD accepted and is routing the transfer    | Show "Processing"; typical SLA under 10 minutes            |
| `COMPLETED`  | Settled                                    | Show confirmation with `confirmationNumber`                |
| `REJECTED`   | JD rejected (invalid data, rule violation) | Show error to user; funds already released                 |
| `FAILED`     | JD unreachable or timed out                | Show error; funds already released; allow retry if desired |
| `CANCELLED`  | Cancelled before submission                | Show cancellation confirmation                             |

### Initiation state machine

The initiate endpoint creates a `PaymentInitiation` entity. This entity has its own lifecycle before the plugin creates a `Transfer`.

<Frame>
  <img src="https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/ted-state-machine-initiation.svg?fit=max&auto=format&n=SEOef3JqTInYAAau&q=85&s=5c6f09d31bce1c536e38a68611ab256a" alt="Initiation state machine" width="991" height="410" data-path="images/en/d2/ted-state-machine-initiation.svg" />
</Frame>

### TED IN state machine

<Frame>
  <img src="https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/ted-state-machine-ted-in.svg?fit=max&auto=format&n=SEOef3JqTInYAAau&q=85&s=6823092769b666c0b03cdaf80892f002" alt="TED IN state machine" width="839" height="410" data-path="images/en/d2/ted-state-machine-ted-in.svg" />
</Frame>

### P2P state machine

P2P does not have a `PENDING` state. Settlement is atomic and instant.

<Frame>
  <img src="https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/ted-state-machine-ted-p2p.svg?fit=max&auto=format&n=SEOef3JqTInYAAau&q=85&s=9129b5880915cbe6e6e8b8be0eaa7765" alt="P2P state machine" width="784" height="461" data-path="images/en/d2/ted-state-machine-ted-p2p.svg" />
</Frame>

### Polling vs. webhooks

Prefer webhooks for real-time status. If you have not configured webhooks yet, poll `GET /v1/transfers/{transferId}`. Use a maximum of 10 attempts with the same backoff schedule as retries. Flag the transfer for manual review after 10 minutes with no terminal state (`COMPLETED`, `REJECTED`, `FAILED`, `CANCELLED`).

See [Get Transfer](/en/reference/midaz/plugins/ted/retrieve-transfer) and [Webhooks](/en/rails/ted/jd/ted-webhooks).

## Webhook integration

***

For event payload schemas and the full list of events, see [Webhooks](/en/rails/ted/jd/ted-webhooks).

### Signature validation

Every webhook request includes headers your endpoint uses to verify authenticity:

* `X-Webhook-Signature` — versioned HMAC-SHA256 signature in the form `v1,sha256=<hex>`
* `X-Webhook-Timestamp` — Unix timestamp in seconds (UTC) when the plugin built the request
* `X-Webhook-Event` — the event type (for example, `transfer.completed`). This header is not part of the signature.

The plugin computes the signature as:

```
X-Webhook-Signature: v1,sha256=hex(HMAC_SHA256(WEBHOOK_SIGNING_SECRET, "v1:" + <timestamp> + "." + <raw_body>))
```

The signed string has four parts in order: the prefix `v1:`, the timestamp value from `X-Webhook-Timestamp`, one ASCII dot (`.`), then the **raw request body bytes**. Use the body bytes exactly as they arrive on the wire. Do not parse or re-encode them first.

To validate:

1. Read `X-Webhook-Signature` and `X-Webhook-Timestamp` from the request headers.
2. Build the signed string: `"v1:" + timestamp + "." + rawBody`.
3. Compute `HMAC-SHA256` over the signed string with your `WEBHOOK_SIGNING_SECRET`, then hex-encode the result.
4. Prepend `v1,sha256=`, then compare against `X-Webhook-Signature` with a constant-time equality function.
5. Reject the request if the timestamp is outside an acceptable freshness window (a 5-minute tolerance is typical) to prevent replay.

Aside from `X-Webhook-Signature` and `X-Webhook-Timestamp`, the plugin sets only `X-Webhook-Event` (the event type). It does not send `X-Webhook-Event-Type`, `X-Webhook-Routing-Key`, or `X-Webhook-Delivery-Attempt`.

<AccordionGroup>
  <Accordion title="JavaScript">
    ```javascript theme={null}
    const crypto = require('crypto');
    const express = require('express');

    const TOLERANCE_SECONDS = 300; // 5 minutes

    function validateWebhook(rawBody, timestamp, signature, secret) {
      if (!timestamp || !signature) return false;

      const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - parseInt(timestamp, 10));
      if (Number.isNaN(ageSeconds) || ageSeconds > TOLERANCE_SECONDS) return false;

      const signedPayload = Buffer.concat([
        Buffer.from('v1:', 'utf8'),
        Buffer.from(timestamp, 'utf8'),
        Buffer.from('.', 'utf8'),
        rawBody,
      ]);

      const expected = 'v1,sha256=' + crypto
        .createHmac('sha256', secret)
        .update(signedPayload)
        .digest('hex');

      const expectedBuf = Buffer.from(expected);
      const receivedBuf = Buffer.from(signature);
      if (expectedBuf.length !== receivedBuf.length) return false;

      return crypto.timingSafeEqual(expectedBuf, receivedBuf);
    }

    // Use raw body — not req.body (parsed JSON)
    app.post('/webhooks/ted',
      express.raw({ type: 'application/json' }),
      (req, res) => {
        const timestamp = req.headers['x-webhook-timestamp'];
        const signature = req.headers['x-webhook-signature'];

        if (!validateWebhook(req.body, timestamp, signature, process.env.WEBHOOK_SIGNING_SECRET)) {
          return res.status(401).send('Invalid signature');
        }

        const payload = JSON.parse(req.body.toString());
        // process payload...
        res.status(200).send('OK');
      }
    );
    ```
  </Accordion>

  <Accordion title="Python">
    ```python theme={null}
    import hmac
    import hashlib
    import time

    TOLERANCE_SECONDS = 300  # 5 minutes

    def validate_webhook(raw_body: bytes, timestamp: str, signature: str, secret: str) -> bool:
        if not timestamp or not signature:
            return False

        try:
            age = abs(int(time.time()) - int(timestamp))
        except ValueError:
            return False
        if age > TOLERANCE_SECONDS:
            return False

        signed_payload = b"v1:" + timestamp.encode() + b"." + raw_body
        expected = "v1,sha256=" + hmac.new(
            secret.encode(),
            signed_payload,
            hashlib.sha256,
        ).hexdigest()

        return hmac.compare_digest(expected, signature)
    ```
  </Accordion>

  <Accordion title="Go">
    ```go theme={null}
    import (
        "crypto/hmac"
        "crypto/sha256"
        "encoding/hex"
        "strconv"
        "time"
    )

    const toleranceSeconds = 300 // 5 minutes

    func validateWebhook(rawBody []byte, timestamp, signature, secret string) bool {
        if timestamp == "" || signature == "" {
            return false
        }

        ts, err := strconv.ParseInt(timestamp, 10, 64)
        if err != nil {
            return false
        }
        if diff := time.Now().Unix() - ts; diff < -toleranceSeconds || diff > toleranceSeconds {
            return false
        }

        mac := hmac.New(sha256.New, []byte(secret))
        mac.Write([]byte("v1:"))
        mac.Write([]byte(timestamp))
        mac.Write([]byte("."))
        mac.Write(rawBody)
        expected := "v1,sha256=" + hex.EncodeToString(mac.Sum(nil))

        return hmac.Equal([]byte(expected), []byte(signature))
    }
    ```
  </Accordion>
</AccordionGroup>

### Idempotent webhook processing

Your endpoint may receive the same event more than once (at-least-once delivery). Use `transferId` + `event` as a composite key to deduplicate.

```javascript theme={null}
const alreadyProcessed = await db.webhookEvents.exists({
  transferId: payload.transferId,
  event: payload.type,
});

if (alreadyProcessed) {
  return res.status(200).send('OK'); // acknowledge without reprocessing
}
```

## Error handling patterns

***

Map API error codes to user-facing actions. See the [full error list](/en/reference/midaz/plugins/ted/ted-error-list) for all codes.

| Scenario                                         | User-facing message                                                        | Action                                                                                                   |
| ------------------------------------------------ | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| **Outside operating hours** (`BTF-0010`)         | "Transfers available Mon–Fri, 06:30–17:00 (Brasília). Next window: {time}" | Show next available time                                                                                 |
| **Daily limit exceeded** (`BTF-0011`)            | "Daily transfer limit reached. Try again tomorrow."                        | Show remaining limit                                                                                     |
| **Duplicate transfer** (`BTF-0012`)              | "This transfer was already submitted."                                     | Return original `transferId`                                                                             |
| **Invalid recipient data** (`BTF-0001`)          | "Check recipient details and try again."                                   | Highlight invalid fields                                                                                 |
| **Initiation expired** (`BTF-0202`)              | "Session expired. Please start a new transfer."                            | Restart initiation flow                                                                                  |
| **JD SPB unavailable** (`TRANSPORT`, HTTP `503`) | "Transfer service temporarily unavailable. Try again in a few minutes."    | Retry with backoff; detect via `503` + raw JD vendor code (`TRANSPORT`, `ACE95`, …), not a `BTF-` prefix |
| **Midaz unavailable** (`BTF-2000`)               | "Service temporarily unavailable. Try again in a few minutes."             | Retry with backoff                                                                                       |

Error responses follow this structure:

```json theme={null}
{
  "error": {
    "code": "BTF-0010",
    "service": "plugin",
    "category": "deterministic",
    "message": "Transfers can only be initiated Monday-Friday between 06:30 and 17:00 Brasília time",
    "requestId": "6d3e2a68-1f2b-4c3d-9e4f-5a6b7c8d9e0f",
    "fields": {
      "currentTime": "2026-01-21T18:30:00-03:00",
      "nextAvailableTime": "2026-01-22T06:30:00-03:00"
    }
  }
}
```

## Go-live checklist

***

Before enabling the integration in production:

* [ ] Send `X-Idempotency` on every initiate, process, and cancel request
* [ ] Retry logic implemented with exponential backoff for 5xx/503 errors
* [ ] Webhook endpoint deployed and returning `200` within 5 seconds
* [ ] Signature validation active on the webhook endpoint
* [ ] Webhook event deduplication implemented using `transferId + event`
* [ ] Operating hours validated client-side before calling initiate (reduces unnecessary 422s)
* [ ] Both `transferId` and `confirmationNumber` stored for reconciliation
* [ ] Terminal states (`COMPLETED`, `REJECTED`, `FAILED`, `CANCELLED`) handled in UI
* [ ] Initiation expiry (24h) handled — prompt the user to restart when the window passes
* [ ] Service readiness monitored in your alerting system for BYOC deployments
* [ ] Redis reachable and monitored — the service rejects requests when Redis is down
* [ ] `PLUGIN_AUTH_ENABLED=true` configured in production, with a valid `PLUGIN_AUTH_ADDRESS` (HTTPS)
