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

# Platform integration guide

> Step by step — onboard your stores, take stablecoin payments priced in naira, receive signed events, and pay every store to its own bank account.

This guide walks a platform — a storefront builder, a marketplace, a booking or
delivery app — through a complete integration. By the end, each of your stores
can be paid in USDT or USDC at checkout, priced in its own currency, and receive
naira in its own bank account, with your platform fee kept by you.

It uses Node.js with `fetch`; every call is plain HTTPS and JSON, so any language
works the same way. Read [Platforms & marketplaces](https://docs.rach.finance/products/platforms.md) for the
concepts; this page is the how-to.

## How it fits together

```mermaid theme={null}
flowchart LR
  subgraph Your platform
    S[Store signup] --> A[Create sub-merchant]
    O[Order at checkout] --> C[Create checkout]
    W[Webhook endpoint]
    J[Daily payout job]
  end
  A --> R[(Rach)]
  C --> R
  R -- payment.confirmed --> W
  J -- quote + payout --> R
  R -- payout.completed / failed --> W
  R -- naira --> B[Store's bank account]
```

| Step | Where | Once or per… |
| - | - | - |
| 1. Get access, keys and a webhook URL | Dashboard | once |
| 2. Create each store as a sub-merchant | API (or dashboard) | per store |
| 3. Add the store's bank account | API or dashboard | per store |
| 4. Price and create a checkout | API | per order |
| 5. Confirm orders from the webhook | Your server | per payment |
| 6. Pay stores out | API or dashboard | daily, or on demand |
| 7. Reconcile | API or dashboard | daily |

## 1. Access, keys and your webhook

1. Request access at [payments.rach.finance/contact](https://payments.rach.finance/contact).
   Rach sends an activation link; sign in and complete business verification
   (KYB) — your platform is the verified business, and you vouch for your stores.
2. Under **Developers → API Keys** take your `test_sk_…` and `live_sk_…` keys. Keep
   them on your server only.
3. Under **Developers → Webhooks** set your HTTPS webhook URL and copy the signing
   secret (`whsec_…`, shown once). Every event below is signed with it.

```js theme={null}
const RACH = 'https://api.rach.finance/api/v1';
const headers = { 'X-API-Key': process.env.RACH_KEY, 'Content-Type': 'application/json' };
async function rach(method, path, body, extra = {}) {
  const res = await fetch(RACH + path, { method, headers: { ...headers, ...extra }, body: body && JSON.stringify(body) });
  const data = await res.json();
  if (!res.ok) throw Object.assign(new Error(data.error || res.statusText), { status: res.status, data });
  return data;
}
```

## 2. Create each store

When a merchant signs up on your platform, create them on Rach with **your own ID
for the store** as `reference`. Store the returned `sm_…` ID next to your store
record — though anywhere a store is named, your reference works too.

```js theme={null}
const store = await rach('POST', '/platform/sub-merchants', {
  reference: 'kapo-farms',          // your store ID, unique on your account
  name: 'Kapo Farms',
  email: 'owner@kapo.example',
  country: 'NG',
  metadata: { plan: 'grand-line' },
});
// store.id === 'sm_x8k2p0q4r7t1v5w9y3z6'
```

Repeating the call with the same `reference` and `name` returns the same store
(`200`), so it is safe to retry. A different name for an existing reference is a
`409`. To pause a store, `PATCH /platform/sub-merchants/{id}` with
`{"status": "disabled"}`: it takes no new checkouts or payouts, and its money stays
ring-fenced.

## 3. Add the store's bank account

Get the bank list once and show it in your own onboarding form:

```js theme={null}
const { banks } = await (await fetch(`${RACH}/banks?country=NG`)).json();
// [{ code: '044', name: 'Access Bank', … }, { code: '100004', name: 'OPay', … }, …]

await rach('POST', `/platform/sub-merchants/kapo-farms/bank-accounts`, {
  bank_code: '100004',
  account_number: '8012345678',   // 10-digit NUBAN
  account_name: 'Kapo Farms',     // exactly as the bank shows it
  is_primary: true,
});
```

* Up to **five** accounts per store; the first becomes primary.
* An account added (or changed) **with an API key** can receive payouts only after
  **24 hours** — the response's `payable_after`. Accounts your team adds in the
  dashboard are payable at once.
* Rach's operations team confirms the account name with the bank before the
  first payout to it. A mismatch holds the payout.

## 4. Price and create the checkout

Create one checkout per order, from your server, priced in the store's currency.

```js theme={null}
const session = await rach('POST', '/checkout/create', {
  amount: '50000',
  currency: 'NGN',
  reference: `order-${order.id}`,
  payment_method: 'crypto',
  fee_bearer: 'customer',          // the customer pays Rach's 0.5% (max 1 USD) on top
  sub_merchant: 'kapo-farms',
  platform_fee: '1000',            // your share, in NGN
  customer_email: order.email,
  callback_url: 'https://platform.example/webhooks/rach',
  return_url: `https://kapo-farms.platform.example/orders/${order.id}`,
  metadata: { order_id: order.id, store: 'kapo-farms' },
}, { 'Idempotency-Key': `order-${order.id}-attempt-1` });

// Send the customer to session.payment_url, or embed it with sdk.js
```

The response tells you exactly what the customer will pay:

| Field | Example | Meaning |
| - | - | - |
| `amount_exact` | `36.69` | Dollars of USDT or USDC the customer sends |
| `invoice_amount` / `invoice_currency` | `50000` / `NGN` | Your price |
| `exchange_rate` | `1369.99` | Naira per dollar, fixed for this checkout |
| `fee` | `0.19` | Rach's fee included in `amount_exact` (customer-borne) |
| `platform_fee` | `0.729932` | Your share, in dollars at the same rate |
| `sub_merchant` | `sm_x8k2…` | The store |

> [!TIP]
>
> **Counter sales.** For a walk-in customer, create the checkout the same way and
> show `payment_url` as a QR code on the store's screen. The customer scans and pays
> from their phone; you get the same webhook.

**How the money divides** (customer bears the fee):

| | Amount |
| - | - |
| Customer pays | 36.69 USDT |
| Rach's fee | 0.19 |
| Your platform fee | 0.729932 — yours to spend or withdraw |
| Kapo Farms' share | 35.770068 — ring-fenced, paid out only to Kapo Farms' accounts |

With `fee_bearer: "merchant"` the customer pays 36.50, Rach's 0.5% comes out of your
platform fee first, and the store still receives the price less your platform fee.

To show customers a naira price converted live before creating a checkout, use
`GET /fx/convert?from=NGN&to=USD&amount=50000` ([FX rates](https://docs.rach.finance/guides/fx-rates.md)) —
then rely on the amount the checkout returns.

## 5. Confirm orders from the webhook

Fulfil an order only from the signed `payment.confirmed` event (or a server-side
`GET /checkout/verify/{session_id}`), never from the browser.

```js theme={null}
import crypto from 'node:crypto';

app.post('/webhooks/rach', express.raw({ type: 'application/json' }), async (req, res) => {
  const signature = req.get('X-Webhook-Signature') || '';
  const expected = crypto.createHmac('sha256', process.env.RACH_WEBHOOK_SECRET).update(req.body).digest();
  const given = Buffer.from(signature, 'hex');
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return res.sendStatus(401);

  const event = JSON.parse(req.body);
  await db.transaction(async tx => {
    if (await tx.seenEvent(event.event_id)) return;          // retries carry the same event_id
    await tx.recordEvent(event.event_id);
    switch (event.event) {
      case 'payment.confirmed': {
        const order = await tx.orderByReference(event.reference);
        // Check it is this order, this store, the amount you priced, and live mode.
        if (event.sub_merchant !== order.storeRachId || event.invoice_amount !== order.priceNGN || event.is_test_mode) throw new Error('mismatch');
        await tx.markPaid(order.id, { paidUSD: event.charged_amount_exact, rachFee: event.fee, platformFee: event.platform_fee, txHash: event.tx_hash });
        break;
      }
      case 'payout.completed':
        await tx.markPayout(event.reference, 'paid', event.payout_amount, event.payout_reference);
        break;
      case 'payout.failed':
        await tx.markPayout(event.reference, 'failed', 0, event.failure_reason);
        break;
    }
  });
  res.sendStatus(200);
});
```

The exact payloads are in [Webhooks](https://docs.rach.finance/guides/webhooks.md). Respond `2xx` quickly;
failed deliveries are retried with the same body and `event_id`.

A customer who pays from an exchange sometimes arrives short, because many
exchanges take their withdrawal fee out of the amount sent. The payment stays
open until the full amount has arrived (the hosted page tells customers this), and
a late payment is still matched for 24 hours after the checkout expires.

## 6. Pay stores out

### Switch on payouts by API key

In the dashboard, **Payment gateway → Stores → Payouts by API key → Turn on** (a
workspace owner, with a 2FA code). Until then the payout endpoint answers `403`
`api_payouts_disabled`; your team can still pay stores from the dashboard.

### Quote, then pay

```js theme={null}
// What would 20,000 NGN to Kapo Farms cost its share right now?
const q = await rach('POST', '/platform/sub-merchants/kapo-farms/payouts/quote', { amount: '20000', currency: 'NGN' });
// q.debit_usd = '15.598647' (includes the 1 USD fee), q.exchange_rate = '1369.99', q.bank_account = primary

const payout = await rach('POST', '/platform/sub-merchants/kapo-farms/payouts', {
  amount: '20000',
  currency: 'NGN',                       // or 'USD' to send a dollar amount
  reference: `payout-kapo-farms-${today}`, // your idempotency key
});
// payout.status === 'pending'; payout.payout_amount === '20000'
```

### A daily payout job

Pay each store everything it holds, once a day:

```js theme={null}
for (let page = 1; ; page++) {
  const { sub_merchants, total } = await rach('GET', `/platform/sub-merchants?page=${page}&limit=100`);
  for (const s of sub_merchants) {
    const held = s.balances.reduce((sum, b) => sum + Number(b.available), 0);
    if (s.status !== 'active' || held < 5 || !s.bank_accounts.some(a => a.is_primary)) continue;
    const amount = (Math.floor(held * 100) / 100).toFixed(2);  // USD to send, fee included
    await rach('POST', `/platform/sub-merchants/${s.id}/payouts`, { amount, currency: 'USD', reference: `daily-${s.reference}-${today}` });
  }
  if (page * 100 >= total) break;
}
```

Because `reference` is unique per store per day, rerunning the job never pays
twice. Each payout ends in `payout.completed` (with `payout_reference`, the bank
transfer reference) or `payout.failed` (the store's money returns to its share).
Payouts are made within 24 hours on business days.

## 7. Reconcile

| Question | Where |
| - | - |
| How much do I hold for stores, and how much is mine? | `GET /platform/summary` or **Stores** tab |
| Where did a store's money come from and go? | `GET /platform/sub-merchants/{id}/ledger` |
| Which payouts are still pending? | `GET /platform/sub-merchants/{id}/payouts` |
| What did a payment cost? | `fee` and `platform_fee` in `payment.confirmed` |

Ledger entry types: `checkout_share` (a payment's share), `payout_locked` (held
for a payout), `payout_settled` (paid out), `payout_reversed` (a failed payout
returned).

## Test mode

Test keys create testnet checkouts: the hosted page, webhooks and sub-merchant
fields behave exactly as in live mode, but **testnet receipts never credit
balances or store shares**, so payouts are tested with small live amounts.
Never send mainnet funds to a test checkout.

## Errors you will meet

| Status | When | What to do |
| - | - | - |
| `400` | Unknown currency, too many decimals for it, `network` set on a non-dollar price, `platform_fee` above the amount or without `sub_merchant`, unknown or disabled store, invalid bank code or NUBAN | Fix the request |
| `409` | Checkout reference or `Idempotency-Key` reused with other details; store reference with another name; a sixth bank account | Reuse the original request, or remove an account |
| `403 api_payouts_disabled` | Payout by API key while the switch is off | Switch it on in the dashboard |
| `400` (payout) | Account still in its 24-hour hold, or disabled by Rach | Wait for `payable_after`, or choose another account |
| `422 insufficient_funds` | The store's share cannot cover the payout and fee | Quote first; pay less |
| `503` | Live rates unavailable (very rare) | Retry shortly, or price in USD |

## Go-live checklist

* [ ] KYB approved; live key on your server only
* [ ] Webhook URL set; signatures verified; `event_id` deduplicated in the same
  transaction as the order update
* [ ] Every store created with your own `reference`, and a primary bank account
* [ ] Checkouts send `sub_merchant`, `platform_fee`, an `Idempotency-Key` per order attempt
* [ ] Orders fulfilled only from `payment.confirmed` or server-side verify
* [ ] API payouts switched on, payout job idempotent per store per period
* [ ] `payout.completed` / `payout.failed` handled


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.