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

# Balance Withdrawal

> Customer withdraws a custom amount up to their available balance

## Overview

A balance withdrawal presents the customer with an input form where they can choose how much to withdraw, up to their available balance. This is the standard withdrawal experience.

> [!WARNING]
>
> **Soap does not store your customers' balances and has no endpoint to read one.** You own the ledger. Soap only ever sees the single `balance_amount_cents` figure you supply when you create the checkout, plus the charges it processes itself — it cannot reconstruct a balance you credit or debit for reasons it never sees (bonuses, promotions, corrections, gameplay). See [You Own the Ledger](#you-own-the-ledger) below before you wire up withdrawals.

Every Soap API request is authenticated with a bearer token in the `Authorization` header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

Your API key is in the Soap Dashboard under the Developers section. It looks like `key_...`.

Requests with a missing or invalid API key return `422` — never `401` — with a JSON `error` field, usually `{"error": "API key not found."}`. Branch on the status code rather than the message: `GET /api/v1/device_pings/latest_geo_check` does not yet return the same wording.

Never expose your API key in client-side code — it is server-side only.

## How It Works

1. You create a checkout session with `type: "withdrawal"` and include `balance_amount_cents` (the customer's available balance).
2. The customer is redirected to the Soap-hosted checkout page.
3. The customer enters the amount they'd like to withdraw (up to their balance) and selects a payout method.
4. Upon completion, a webhook is fired and the customer is redirected back to your app.

## API Request

```bash theme={null}
curl -X POST 'https://api-sandbox.paywithsoap.com/api/v1/checkouts' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer YOUR_API_KEY' \
--data '{
    "customer_id": "cus_vi57KegYgcRqcGHqip8q6UZiqtrwMT870",
    "type": "withdrawal",
    "balance_amount_cents": 10000,
    "experience": "web",
    "return_url": "https://myapp.com/wallet"
}'
```

## Key Parameters

| Parameter | Required | Description |
| - | - | - |
| `customer_id` | Yes | The customer's unique identifier |
| `type` | Yes | Must be `"withdrawal"` |
| `balance_amount_cents` | Yes | Your asserted snapshot of the customer's available balance, in cents. Soap enforces it as the ceiling for this one checkout — the customer can't withdraw more than this. Must be at least `1`. |
| `experience` | No | `"web"`, `"webview"`, or `"iframe"`. Use `"iframe"` when embedding the checkout — see [Embedded Checkout](https://docs.paywithsoap.com/get_started/embedded-checkout.md). |
| `return_url` | No | Where to redirect the customer after completion |

## When to Use

* Letting the customer choose their withdrawal amount
* Standard cashout flows where the customer has a balance
* Any scenario where the withdrawal amount is not predetermined

## You Own the Ledger

Soap is a payments layer, not a ledger. There is no endpoint anywhere in the public API to look up a customer's balance — the full API surface is customers, checkouts, charges, products, KYC, device pings, and geo checks. Nothing else. Soap never tracks a running balance for your customers; the only balance-related figure it ever holds is the `balance_amount_cents` you send it, scoped to that single checkout.

This means `balance_amount_cents` is not something Soap validates against a stored balance — it's a **snapshot you assert** at checkout-creation time. Soap stores it on the checkout and enforces it as a ceiling: the amount the customer ultimately withdraws must be less than or equal to what you sent. Soap does not re-check it against anything else, because it has nothing else to check it against.

### Computing `balance_amount_cents`

Since you own the source of truth, compute this figure from your own ledger when you create the checkout:

1. Read the customer's current available balance from your ledger.
2. Subtract any amount you're already holding for withdrawals currently in flight (i.e. checkouts where you've received `checkout.hold` but not yet a terminal event) — otherwise the same funds could be authorized for withdrawal twice.
3. Pass the result as `balance_amount_cents`.

> [!NOTE]
>
> `fixed_amount_cents` is the alternative to `balance_amount_cents` for withdrawals with a preset amount instead of a customer-chosen one. See [Preset Amount Withdrawal](https://docs.paywithsoap.com/api-reference/api-v1/checkouts/preset-withdrawal.md). The rule is by checkout type, not by account: a withdrawal takes either `balance_amount_cents` or `fixed_amount_cents`, never both and never `line_items`; a deposit may take neither amount field (the customer chooses), `fixed_amount_cents`, or `line_items`, never `balance_amount_cents`. An invalid combination returns `422` and the `error` names the offending field.

## The Hold Lifecycle

Withdrawals use a hold handshake so a customer can't spend money that's already being cashed out. Getting this wrong is the single easiest way to double-debit a real customer, so read this before you go live.

```mermaid theme={null}
sequenceDiagram
    participant Customer
    participant YourApp
    participant Soap

    YourApp->>Soap: POST /api/v1/checkouts (type: withdrawal, balance_amount_cents)
    Soap-->>YourApp: checkout url
    YourApp->>Customer: Redirect to hosted checkout
    Customer->>Soap: Chooses amount + payout method
    Soap->>YourApp: webhook: checkout.hold
    YourApp->>YourApp: Debit customer ledger
    YourApp-->>Soap: 2xx (funds available)
    Soap->>YourApp: webhook: checkout.succeeded
    YourApp->>YourApp: No-op — already debited on hold

    alt Payout fails immediately
        Soap->>YourApp: webhook: checkout.release_hold
        YourApp->>YourApp: Credit customer back
    end

    alt Payout is accepted, then fails asynchronously
        Soap->>YourApp: webhook: checkout.failed (off by default)
        YourApp->>YourApp: Credit customer back
    end

    alt Payout is accepted, then cancelled by the rail (some processors)
        Soap->>YourApp: webhook: checkout.cancelled (off by default)
        YourApp->>YourApp: Credit customer back
    end
```

1. You create the withdrawal checkout with `balance_amount_cents`.
2. The customer picks an amount and a payout method.
3. Soap sends `checkout.hold` — a question: does this customer have the funds? Respond **2xx** and the withdrawal proceeds; respond **non-2xx** and it doesn't. `checkout.hold` is delivered synchronously, is never retried, and times out after 10 seconds, so this check must be fast.
4. **Debit the customer immediately when you respond 2xx to `checkout.hold`.** This is what prevents the customer from spending the same funds elsewhere while the withdrawal is in flight.
5. Soap later sends `checkout.succeeded` for the same checkout — treat it as a no-op for withdrawals you already debited on hold.
6. If the withdrawal does not complete, credit the customer back. **Which event tells you depends on how it failed** — see [Every way a hold ends](#every-way-a-hold-ends) below. Getting this set wrong is how held funds go missing.
7. Every event carries a stable `event_id`. Use it as an idempotency key so retries never double-apply a debit or credit.

> [!WARNING]
>
> **The double-debit trap:** debiting the customer on `checkout.hold` *and again* on `checkout.succeeded` for the same withdrawal. If you debit on hold (recommended), `checkout.succeeded` for that checkout must be a no-op.

### Every way a hold ends

Once you have debited on `checkout.hold`, you have taken on an obligation to credit the money back if the withdrawal doesn't complete. A held charge can end in several ways, and they do not all send the same event:

| How it ends | Event you receive | Delivered by default | Carries `charge.amount_cents` |
| - | - | - | - |
| The payout succeeds | `checkout.succeeded` | Always | Yes |
| The payout fails immediately | `checkout.release_hold` | Always | Yes |
| The payout is accepted, then fails | `checkout.failed` | **No** | Yes |
| The payout is accepted, then cancelled by the rail (some processors) | `checkout.cancelled` | **No** | Yes |
| The checkout is abandoned | `checkout.expired` | **No** | **No** |

> [!WARNING]
>
> **`checkout.failed` is off by default and it is the one most likely to strand real money.** When a payout is accepted for processing and then fails, the charge moves from held to pending to failed. Because it was pending rather than held immediately before failing, Soap sends `checkout.failed` — *not* `checkout.release_hold`. This is the normal failure shape for asynchronous payout rails, so if you debit on hold and leave `checkout.failed` disabled, you will debit customers for withdrawals that never arrive and never hear about it.
>
> Enable `checkout.failed` in **Dashboard → Developers** before you take withdrawals live.

`checkout.release_hold` and `checkout.succeeded` are always sent and cannot be disabled. `checkout.cancelled` is processor-specific (bank-transfer rails); ask Soap whether your payout rails emit it. `checkout.expired` is also off by default, and unlike the others its payload contains no `charge` object at all — only `id`, `expired_at`, `type`, `customer.id` and `subscription`. That is why the handler below records the amount it debited rather than reading it back off the event.

> [!NOTE]
>
> A charge can also move from succeeded to failed or returned well after the fact, when a payout bounces. Those arrive as `checkout.failed` (with `charge.from_status` set to `"succeeded"`) and `checkout.returned`. Keep your record of what you debited until your reconciliation window closes so you can credit these back too, rather than deleting it the moment a withdrawal succeeds.

### Example: a single handler for the full lifecycle

```javascript theme={null}
const express = require('express');
const app = express();

// Use a real database, not in-memory collections, to persist these across
// restarts.
const processedEventIds = new Set();

// chargeId -> { checkoutId, customerId, amountCents }
// Withdrawals you have debited and not yet credited back, keyed on the
// charge (one checkout can carry several attempts, each with its own
// ch_ id — see Checkouts, Charges and Reviews). Store the amount yourself:
// checkout.expired arrives with no charge object, so the event cannot tell
// you how much to return.
const debitedWithdrawals = new Map();

// Credits back at most once per charge, whichever event gets here first.
function creditBackCharge(chargeId) {
  const debit = debitedWithdrawals.get(chargeId);
  if (!debit) return; // never debited for this charge — nothing to undo
  creditLedger(debit.customerId, debit.amountCents);
  debitedWithdrawals.delete(chargeId);
}

// checkout.expired has no charge, so it credits back every outstanding
// debit on that checkout.
function creditBackCheckout(checkoutId) {
  for (const [chargeId, debit] of debitedWithdrawals) {
    if (debit.checkoutId === checkoutId) creditBackCharge(chargeId);
  }
}

app.post('/webhooks/soap', express.raw({ type: 'application/json' }), (req, res) => {
  const event = JSON.parse(req.body.toString('utf8'));

  // event_id is your idempotency key — never apply the same event twice.
  if (processedEventIds.has(event.event_id)) {
    return res.sendStatus(200);
  }

  switch (event.type) {
    case 'checkout.hold': {
      const { id: checkoutId, charge, customer } = event.data;
      const hasSufficientFunds = getLedgerBalance(customer.id) >= charge.amount_cents;

      if (!hasSufficientFunds) {
        processedEventIds.add(event.event_id);
        return res.sendStatus(402); // non-2xx: withdrawal does not proceed
      }

      // Debit now, on the hold — this is what stops the customer from
      // spending these funds again before the withdrawal settles.
      debitLedger(customer.id, charge.amount_cents);
      debitedWithdrawals.set(charge.id, {
        checkoutId,
        customerId: customer.id,
        amountCents: charge.amount_cents,
      });
      processedEventIds.add(event.event_id);
      return res.sendStatus(200); // 2xx: withdrawal proceeds
    }

    case 'checkout.succeeded': {
      const { charge, type } = event.data;

      if (type === 'withdrawal' && debitedWithdrawals.has(charge.id)) {
        // Already debited on checkout.hold. Debiting again here would be
        // the double-debit trap — this must be a no-op. The record stays so
        // a later reversal can still find the amount.
        processedEventIds.add(event.event_id);
        return res.sendStatus(200);
      }

      // Deposits (and any withdrawal you didn't debit on hold) settle here.
      applyLedgerUpdateForSucceededCheckout(event.data);
      processedEventIds.add(event.event_id);
      return res.sendStatus(200);
    }

    // Always delivered: the charge went straight from held to failed.
    case 'checkout.release_hold':
    // Off by default, and the one that actually strands money. An accepted
    // payout that fails later goes held -> pending -> failed, so Soap sends
    // this instead of release_hold. Also covers a settled payout bouncing,
    // where charge.from_status is "succeeded".
    case 'checkout.failed':
    // Always delivered. A completed payout was returned by the bank.
    case 'checkout.returned':
    // Off by default and processor-specific: the rail cancelled an accepted
    // payout (pending -> cancelled). Also fires for cancelled deposits on
    // those rails, which creditBackCharge ignores because nothing was debited.
    case 'checkout.cancelled': {
      creditBackCharge(event.data.charge.id);
      processedEventIds.add(event.event_id);
      return res.sendStatus(200);
    }

    // Off by default. Carries no charge object, which is why the amount
    // comes from your own record rather than the payload.
    case 'checkout.expired': {
      creditBackCheckout(event.data.id);
      processedEventIds.add(event.event_id);
      return res.sendStatus(200);
    }

    default:
      processedEventIds.add(event.event_id);
      return res.sendStatus(200);
  }
});
```

> [!NOTE]
>
> `creditBackCharge` is deliberately keyed on your own debit record rather than on
> the event type, so the terminal charge events can share one branch and a
> charge you never debited is ignored safely. Because it deletes the record as
> it credits, two different terminal events for the same charge can never credit
> the customer twice. The record is keyed on `charge.id`, not the checkout id:
> a failed attempt can be followed by a new attempt with a new charge on the
> same checkout, and a checkout-keyed record would let the second hold overwrite
> the first.

For signature verification and the general webhook endpoint setup, see [Receiving Webhooks](https://docs.paywithsoap.com/api-reference/api-v1/webhooks/setup.md). For the full payload shape of each event, see [`checkout.hold`](https://docs.paywithsoap.com/api-reference/api-v1/webhooks/checkout-hold) and [`checkout.release_hold`](https://docs.paywithsoap.com/api-reference/api-v1/webhooks/checkout-release-hold).

> [card] [← Back to Create Checkout](https://docs.paywithsoap.com/api-reference/api-v1/checkouts/create.md)
>
> View the full API reference for creating checkouts.


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