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

> ## Agent Instructions
> Treat these docs and the Whop MCP server as the source of truth for Whop API behavior. Don't infer endpoint behavior from marketing pages.
> MCP server: connect https://mcp.whop.com/mcp (streamable HTTP, browser sign-in, no API key in the client config) to search these docs and read or change live Whop data. Setup: https://docs.whop.com/developer/guides/ai_and_mcp.md
> Whop CLI: install with `curl -fsSL https://whop.com/install.sh | sh` to scaffold, run, and deploy Whop apps and websites. It acts on production, not the sandbox. Overview: https://docs.whop.com/cli/overview.md Agent mode: https://docs.whop.com/cli/agent-mode.md
> Hosting: Whop serves a site or app from the build `whop apps deploy` uploads, with rollbacks, secrets, and server logs. Guide: https://docs.whop.com/developer/websites/hosting.md
> Plugins: in Claude Code, run `/plugin marketplace add whopio/plugins`, then `/plugin install whop@whop`. Guide: https://docs.whop.com/developer/guides/plugins/claude-code.md Every agent tool: https://docs.whop.com/developer/ai/overview.md
> Environments: build and test in the sandbox (API `https://sandbox-api.whop.com/api/v1`, keys at https://sandbox.whop.com/dashboard/developer, SDK environment `Sandbox`; no real money). Production (API `https://api.whop.com/api/v1`, keys at https://whop.com/dashboard/developer, SDK environment `Production`, the SDK default) moves real money, so use it only at launch. The two share no accounts, keys, products, or webhooks, and their keys look identical: never mix them. Sandbox guide: https://docs.whop.com/developer/guides/sandbox.md Comparison: https://docs.whop.com/developer/quickstart.md
> API: send `Authorization: Bearer <API_KEY>` from your server only, and pin a dated version with the `Api-Version-Date` header. OpenAPI spec: https://api.whop.com/api/v1/openapi.json
> Which API: build on the Current API, whose pages live under https://docs.whop.com/api-reference/ (start at https://docs.whop.com/api-reference/overview.md). Pages under /api-reference/legacy/ are the Legacy API. Use one only when https://docs.whop.com/api-reference/stability.md lists the resource as Legacy-only.

# Habilitar pagos salientes de subcuentas

> Permite que tus subcuentas gestionen sus propios pagos salientes con Whop Elements o un portal alojado

Permite que tus subcuentas completen la verificación Know Your Customer (KYC), añadan métodos de pago saliente y retiren sus fondos por su cuenta. Puedes montar las superficies de wallet de [Whop Elements](https://docs.whop.com/es/elements/latest/getting-started.md) directamente en tu app o redirigir a los usuarios a un portal alojado por Whop.

## Portal de pagos salientes incrustado

### Implementación en el servidor

Para montar los wallet elements, genera un token de acceso para la subcuenta en tu servidor. Los elements leen con él el saldo y los pagos salientes de esa cuenta. Consulta [Autenticación y claves de API](https://docs.whop.com/es/developer/guides/auth-scoping.md) para saber cómo limitar el alcance de ese token y cómo se compara con los demás tipos de credenciales de Whop.

```tsx Next.JS theme={null}
// app/api/token/route.ts
import { WhopClient } from "@whop/sdk";
import type { NextRequest } from "next/server";

const whop = new WhopClient({
	token: process.env.WHOP_API_KEY,
});

export async function GET(request: NextRequest) {
	// Authenticate your user here
	const accountId = request.nextUrl.searchParams.get("accountId");

	if (!accountId) {
		return new Response(null, { status: 400 });
	}
	const tokenResponse = await whop.accessTokens
		.create({
			account_id: accountId,
		})
		.catch(() => {
			return null;
		});
	if (!tokenResponse) {
		return new Response(null, { status: 500 });
	}
	const token = tokenResponse.token;
	return Response.json({
		token,
	});
}
```

```typescript Express.js theme={null}
import express from "express";
import { WhopClient } from "@whop/sdk";

const app = express();
const client = new WhopClient({ token: "Account API Key" });

app.use(express.json());

app.post("/api/access-token", async (req, res) => {
	// Authenticate your user here
	const { accountId } = req.body;

	const { token } = await client.accessTokens.create({
		account_id: accountId,
	});

	res.json({ token });
});

app.listen(3000, () => {
	console.log("Server running on port 3000");
});
```

```python Python theme={null}
from whop_sdk import Whop
from flask import Flask, request, jsonify

app = Flask(__name__)
client = Whop(token="Account API Key")

@app.route('/api/access-token', methods=['POST'])
def create_access_token():
    data = request.get_json()
    # Authenticate your user here
    account_id = data.get('accountId')

    access_token = client.access_tokens.create(
        account_id=account_id
    )

    return jsonify({'token': access_token.token})
```

> [card] [API Create Access Token](https://docs.whop.com/es/api-reference/legacy/access-tokens/create-access-token.md)
>
> Consulta la referencia completa de la API para generar tokens de acceso y todos los
> parámetros disponibles

## Configuración en el cliente

```bash npm theme={null}
npm install @whop/elements-react @whop/elements
```

```bash pnpm theme={null}
pnpm add @whop/elements-react @whop/elements
```

```html HTML theme={null}
<script src="https://cdn.whop.com/elements/amber/elements.js" data-whop-elements></script>
```

## Implementación en el cliente

Crea un handle de `Wallet` para la subcuenta y monta debajo las superficies que necesites. El handle envía su token de acceso a todos los elements que contiene, así que genera un único token que incluya todos los scopes que leen esos elements.

```tsx React theme={null}
"use client";

import { useEffect, useState } from "react";
import {
	ActivityElement,
	BalanceElement,
	Balances,
	Wallet,
	WhopElements,
	WithdrawElement,
} from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function PayoutPortal({ accountId }: { accountId: string }) {
	const [accessToken, setAccessToken] = useState<string | null>(null);

	useEffect(() => {
		fetch(`/api/token?accountId=${accountId}`)
			.then((res) => res.json())
			.then((data) => setAccessToken(data.token));
	}, [accountId]);

	if (!accessToken) return null;

	return (
		<WhopElements elements={loadWhop()}>
			<Wallet accountId={accountId} accessToken={accessToken}>
				<Balances>
					<BalanceElement />
				</Balances>
				<WithdrawElement />
				<ActivityElement />
			</Wallet>
		</WhopElements>
	);
}
```

```html JavaScript theme={null}
<div id="balance"></div>
<div id="withdraw"></div>
<div id="activity"></div>

<script type="module">
  const accountId = "biz_xxxxxxxxxxxxx";
  const { token } = await (await fetch(`/api/token?accountId=${accountId}`)).json();

  const wallet = window.WhopElements().wallet.create({ accountId, accessToken: token });
  wallet.create("balances").create("balance").mount("#balance");
  wallet.create("withdraw").mount("#withdraw");
  wallet.create("activity").mount("#activity");
</script>
```

> [!NOTE]
>
> En iOS, el SDK de wallet incluye `BalanceElement`, `ListElement` y `ActivityElement`. Consulta [Primeros pasos con Elements](https://docs.whop.com/es/elements/latest/getting-started.md) y elige la pestaña Swift.

### Verificación de identidad

Una subcuenta debe verificar su identidad antes de poder retirar fondos. Monta el [element de KYC](https://docs.whop.com/es/elements/latest/verifications/kyc.md) para el flujo completo dentro de la página, que recopila los datos, ejecuta la sesión alojada del proveedor e informa del resultado. O monta el [element RequiredActions](https://docs.whop.com/es/elements/latest/dashboard/required-actions.md) para mostrar todas las acciones pendientes, incluida la verificación, y permitir que el usuario inicie cada una.

```tsx React theme={null}
import { WhopElements, Verifications, KycElement } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function VerifyIdentity({ accountId }: { accountId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			<Verifications
				accountId={accountId}
				getToken={() =>
					fetch(`/api/token?accountId=${accountId}`)
						.then((res) => res.json())
						.then((data) => data.token)
				}
			>
				<KycElement onCompleted={() => console.log("Verified")} />
			</Verifications>
		</WhopElements>
	);
}
```

## Opciones de `Wallet`

| Opción | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `accountId` | `string` | Sí | El ID de la subcuenta, con el prefijo `biz_`. |
| `accessToken` | `string` | Sí, en tu propio dominio | El token de tu servidor. Sin él, las lecturas usan la sesión de whop.com del usuario, que solo funciona en whop.com. |
| `currency` | `string` | No | Código ISO 4217 para los campos de importe. El valor predeterminado es `usd`. |
| `appearance` | `Appearance` | No | Tema y estilos por parte para todos los elements del handle. Consulta [Appearance](https://docs.whop.com/es/elements/latest/appearance.md). |

Todas las opciones, eventos y métodos se enumeran en la [referencia de Wallet](https://docs.whop.com/es/elements/latest/wallet/overview).

### Scopes

Los elements leen con el token que generas, así que concede en ese único token todos los scopes que necesitan:

* [Balances](https://docs.whop.com/es/elements/latest/wallet/balances) y [Activity](https://docs.whop.com/es/elements/latest/wallet/activity.md) leen `company:balance:read`.
* [Withdraw](https://docs.whop.com/es/elements/latest/wallet/withdraw.md) necesita `payout:withdraw_funds`, `payout:destination:read` y `payout:create_destination` para añadir un banco.
* [KYC](https://docs.whop.com/es/elements/latest/verifications/kyc.md) necesita `identity:read` e `identity:write`.

Un token creado sin `scoped_actions` hereda todos los permisos de tu clave de API.

### Renovar el token

Los tokens de acceso caducan después de una hora de forma predeterminada y de tres horas como máximo. Establece uno nuevo en el handle antes de que caduque:

```ts theme={null}
wallet.update({ accessToken: await fetchToken(accountId) });
```

En React, pasa el nuevo valor como la prop `accessToken`.

> [!NOTE]
>
> `accessToken` es un valor que estableces, no un callback al que llama el SDK. `Verifications` es la excepción: acepta un callback `getToken` y lo llama antes de que se monte el element.

## Portal de pagos salientes alojado

En lugar de incrustar el portal de pagos salientes en tu app, puedes redirigir a los usuarios a un portal de pagos salientes alojado por Whop. Es útil cuando no quieres crear una interfaz personalizada o necesitas una integración rápida.

Crea un enlace de cuenta y redirige al usuario a la URL devuelta:

```typescript TypeScript theme={null}
import { WhopClient } from "@whop/sdk";

const client = new WhopClient({
	token: "Account API Key",
});

const accountLink = await client.accountLinks.create({
	account_id: "biz_xxxxxxxxxxxxx",
	use_case: "payouts_portal",
	return_url: "https://yourapp.com/payouts/complete",
	refresh_url: "https://yourapp.com/payouts/refresh",
});

// Redirect the user to the hosted portal
console.log(accountLink.url);
```

```python Python theme={null}
from whop_sdk import Whop

client = Whop(
    token="Account API Key",
)

account_link = client.account_links.create(
    account_id="biz_xxxxxxxxxxxxx",
    use_case="payouts_portal",
    return_url="https://yourapp.com/payouts/complete",
    refresh_url="https://yourapp.com/payouts/refresh",
)

# Redirect the user to the hosted portal
print(account_link.url)
```

```rust Rust theme={null}
use whop_sdk::prelude::*;

let config = ClientConfig {
    token: Some("Account API Key".to_string()),
    ..Default::default()
};
let client = Whop::new(config).expect("Failed to build client");

let account_link = client
    .account_links
    .create(
        &CreateAccountLinksRequest {
            account_id: "biz_xxxxxxxxxxxxx".to_string(),
            use_case: AccountLinkUseCases::PayoutsPortal,
            return_url: "https://yourapp.com/payouts/complete".to_string(),
            refresh_url: "https://yourapp.com/payouts/refresh".to_string(),
        },
        None,
    )
    .await?;

// Redirect the user to the hosted portal
println!("{}", account_link.url);
```

```go Go theme={null}
import (
    "context"
    "fmt"
    "log"

    whopsdk "github.com/whopio/whopsdk-go/v2"
    "github.com/whopio/whopsdk-go/v2/client"
    "github.com/whopio/whopsdk-go/v2/option"
)

client := client.NewWhop(option.WithToken("Account API Key"))

accountLink, err := client.AccountLinks.Create(context.TODO(), &whopsdk.CreateAccountLinksRequest{
    AccountID:  "biz_xxxxxxxxxxxxx",
    UseCase:    whopsdk.AccountLinkUseCasesPayoutsPortal,
    ReturnURL:  "https://yourapp.com/payouts/complete",
    RefreshURL: "https://yourapp.com/payouts/refresh",
})
if err != nil {
    log.Fatal(err)
}

// Redirect the user to the hosted portal
fmt.Println(accountLink.URL)
```

En este ejemplo:

* `account_id` es la plataforma o la subcuenta
* `use_case` especifica el tipo de portal
* `return_url` es adonde Whop redirige al usuario cuando quiere volver a tu sitio
* `refresh_url` es adonde Whop redirige al usuario si la sesión caduca

### Casos de uso disponibles

| Caso de uso | Descripción |
| - | - |
| `account_onboarding` | KYC y verificación de identidad |
| `payouts_portal` | Pagos salientes, métodos de pago saliente, KYC y verificación de identidad |

Después de crear el enlace de cuenta, redirige al usuario a la `url` devuelta en la respuesta. El usuario completa el flujo de pago saliente en el portal alojado por Whop y luego Whop lo redirige a tu `return_url`.

## Recursos relacionados

> [card] [Wallet elements](https://docs.whop.com/es/elements/latest/wallet/overview)
>
> Todas las superficies de wallet con sus opciones, eventos y scopes

> [card] [Pagar a subcuentas](https://docs.whop.com/es/developer/platforms/collect-payments-for-subaccounts.md)
>
> Transfiere fondos a subcuentas


## Related topics

- [Pagos salientes manuales a subcuentas](https://docs.whop.com/es/developer/platforms/manual-payouts.md)
- [Recargos y subvenciones de comisiones](https://docs.whop.com/es/developer/platforms/fee-markups.md)
- [Pagos salientes y movimiento de dinero](https://docs.whop.com/es/developer/payouts/overview.md)
