> ## 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.

# Abre una hoja de billetera desde tu propio botón

> Abre la hoja de Apple Pay o Google Pay desde un botón que tú renderizas, calcula tú mismo el precio del pedido y cobra el token de confirmación desde tu servidor

Usa el recurso payment request cuando muestres tú mismo el botón de compra y fijes tú mismo el precio del pedido. Una sola pulsación abre la hoja de Apple Pay o Google Pay, la hoja te entrega un token de confirmación y tu servidor pasa el token a la Payments API para cobrar.

Los archivos de **Código** incluyen comentarios `Step X.Y` que remiten a los pasos siguientes. Elige una implementación de servidor y una implementación de cliente. La lista incluye los archivos de todas las opciones.

## Crea tu botón de monedero

### 1.1 Instala los paquetes (React)

Instala los paquetes de Whop Elements para React.

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

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

### 1.1 Añade la etiqueta script (JavaScript)

Carga el script de Whop Elements en la página que muestra el botón.

### 1.2 Crea el payment request

Crea la solicitud con tu cuenta, la moneda y el importe en unidades menores. `lineItems` son las filas que la hoja muestra bajo el total. No se monta nada: el recurso es la hoja del monedero sin un elemento, y el botón es tuyo.

Los monederos solo se abren en páginas cuyo dominio tiene Apple Pay preparado. Sigue [Habilitar Apple Pay y Google Pay](https://docs.whop.com/es/payments/apple-pay.md) una vez por dominio, sirve la página con `https` y prueba en un dispositivo real con un monedero configurado.

### 1.3 Comprueba qué monederos pueden pagar

Espera a `canMakePayment()` antes de mostrar un botón. Indica con qué monederos pueden pagar este dispositivo, esta cuenta y este dominio, y prepara la hoja para que pueda abrirse de forma síncrona más tarde. Muestra un botón solo para un monedero que haya devuelto `true`.

Apple y Google exigen cada uno su propio diseño de botón en un botón personalizado. Sigue las [directrices del botón de Apple Pay](https://developer.apple.com/design/human-interface-guidelines/apple-pay) y las [directrices de marca de Google Pay](https://developers.google.com/pay/api/web/guides/brand-guidelines).

### 1.4 Abre la hoja y envía el token a tu servidor

Llama a `show(type)` lo primero en el manejador de pulsación del botón, antes de cualquier `await`. Apple rechaza una hoja abierta fuera de ese gesto del usuario, por eso `canMakePayment()` se ejecutó con antelación. La hoja pide el correo electrónico del comprador, a menos que pases uno con `show("apple_pay", \{ email \})`.

`show` se resuelve en cuanto el comprador autoriza. `ctok` es el token de confirmación de un solo uso, `type` indica el monedero, y `payer` incluye el correo electrónico, el nombre, el teléfono y el país de facturación del comprador tal como los proporcionó el monedero. Si el comprador cierra la hoja, `show` se rechaza con un error `payment_request_cancelled`. La hoja se cierra con una marca de verificación en cuanto se genera el token, antes de que tu servidor confirme, así que muestra el resultado de tu servidor en tu página.

Envía `ctok` a tu servidor junto con tu propia referencia de pedido. Para recopilar una dirección de envío y ofrecer opciones de envío, establece `requestShipping` y responde a los cambios de la hoja con `updateWith`. La [referencia de PaymentRequest](https://docs.whop.com/es/elements/latest/payments/paymentRequest.md) explica esos manejadores.

## Cobra desde tu servidor

### 2.1 Instala el SDK de Whop (Next.js)

Instala el SDK de Whop y crea un cliente con la clave de API de tu cuenta. La clave permanece en el servidor. El navegador nunca la ve.

```bash npm theme={null}
npm install @whop/sdk @vercel/functions
```

```bash pnpm theme={null}
pnpm add @whop/sdk @vercel/functions
```

### 2.1 Instala el SDK de Whop (Express)

Instala el SDK de Whop y crea un cliente con la clave de API de tu cuenta. La clave permanece en el servidor. El navegador nunca la ve.

```bash npm theme={null}
npm install @whop/sdk express
```

```bash pnpm theme={null}
pnpm add @whop/sdk express
```

### 2.1 Instala el SDK de Whop (Python)

Instala el SDK de Whop y crea un cliente con la clave de API de tu cuenta. La clave permanece en el servidor. El navegador nunca la ve.

```bash pip theme={null}
pip install whop-sdk fastapi
```

```bash poetry theme={null}
poetry add whop-sdk fastapi
```

### 2.2 Crea el pago a partir del token de confirmación

Pasa el token a la Payments API. Whop identifica al comprador a partir del correo electrónico del token, cobra la variante y devuelve el pago con un `client_secret`. Devuelve `id`, `status` y `client_secret` al navegador. El `client_secret` solo desbloquea este pago concreto, así que es seguro exponerlo.

Cobra lo que mostró la hoja. El `amount` de la solicitud está en unidades menores, así que `1000` en la hoja equivale a un `initial_price` de `10.0` aquí. Pasa una `variant` en línea para buscar o crear una variante para este precio, o `variant_id` para una variante que ya hayas creado. Establece `return_url` en la página a la que debe llegar el comprador después de un paso a página completa, y pon tu propio ID de pedido en `metadata` para que el pago y sus webhooks lo incluyan.

* Una `variant` en línea busca o crea la variante para este precio. Usa `variant_id` cuando el precio ya existe como variante
* `confirmation_token` representa a la tarjeta del monedero que autorizó la hoja
* `metadata` vincula el pago con tu propio pedido
* Para bienes físicos, envía la `shipping.address` del resultado junto con el token y pásala como `shipping_address`

### 2.3 Gestiona el pedido desde el webhook

Whop envía `payment.succeeded` a tu endpoint de webhook una vez que el cargo se realiza correctamente. Verifica la firma con el helper del SDK y, a continuación, gestiona el pedido: márcalo como pagado, concede el acceso y envía el correo electrónico. Un pago con monedero indica `apple_pay` o `google_pay` en `payment_method_type`.

La gestión del pedido debe hacerse aquí y en ningún otro sitio. La marca de verificación de la hoja, el navegador y un parámetro de consulta pueden indicar que se ha pagado sin que el cargo se haya liquidado. Sigue la [guía de Webhooks](https://docs.whop.com/es/developer/guides/webhooks.md) para crear el webhook y guardar su secreto `ws_` como `WHOP_WEBHOOK_SECRET`.

## Completa el pago

### 3.1 Gestiona la siguiente acción

Un pago que vuelve como `paid` está completo. Cualquier otro valor significa que el comprador todavía tiene un paso pendiente, como 3D Secure, o que el cargo sigue pendiente. Pasa el `client_secret` a `handleNextAction`. Ejecuta un paso en línea en un diálogo y se resuelve con `redirected: false`, o envía al comprador a tu `return_url` y se resuelve con `redirected: true`.

Ramifica según el `status` que devuelve. `succeeded` significa que el comprador ha pagado, `processing` significa que el cargo sigue pendiente, y cualquier otro valor requiere otro intento. `lastPaymentError` incluye el motivo cuando lo hay. Un diálogo cerrado deja el pago en `requires_action` sin error, así que la ausencia de error nunca significa éxito.

### 3.2 Lee el resultado de la URL

Un comprador que salió a un paso a página completa llega a `return_url` **pase lo que pase** allí. Whop añade tres parámetros de consulta. `payment` es el ID `pay_`. `status` es `succeeded` cuando el comprador ha pagado, `failed` o `canceled` cuando no, y un estado pendiente como `processing` mientras el cargo aún no está decidido. `client_secret` permite a la página consultar periódicamente el estado del pago si quiere esperar a una decisión.

Tus propios parámetros, como `order`, se mantienen en la URL. `handleNextAction` notifica por sí mismo los rechazos en línea, así que la página de retorno es el único lugar donde tu sitio ve un paso fuera del sitio fallido.

### 3.3 Muestra la vista adecuada

Ramifica según `status`. `succeeded` muestra la página de agradecimiento. `failed` y `canceled` muestran un mensaje indicando que no se ha cobrado al comprador y un enlace para volver al producto. Cualquier otro valor significa que el cargo sigue pendiente. Indica al comprador que le confirmarás por correo electrónico. Las rutas en línea del manejador del botón envían al comprador a la misma página con los mismos parámetros, así que una sola página gestiona todos los desenlaces.

Trata la página como una visualización del resultado, no como prueba de pago. Cualquiera puede escribir `status=succeeded` en una URL. El acceso, las descargas y la gestión del pedido dependen del webhook `payment.succeeded` en tu servidor.

## Código

### Cliente: React — `WalletButtons.tsx`

```tsx WalletButtons.tsx theme={null}
// Step 1.1: Install the packages
import { useEffect, useRef, useState } from "react";
import { WhopElements, useWhop } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";
import type { PaymentRequestResource } from "@whop/elements/payments";

type Wallet = "apple_pay" | "google_pay";

export function ProductPage({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			<WalletButtons orderId={orderId} />
		</WhopElements>
	);
}

function WalletButtons({ orderId }: { orderId: string }) {
	const whop = useWhop();
	const requestRef = useRef<PaymentRequestResource | null>(null);
	const [wallets, setWallets] = useState<Wallet[]>([]);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		if (!whop) return;
		// Step 1.2: Create the payment request
		// Amounts are in minor units: 1000 is $10.00.
		const paymentRequest = whop.payments.paymentRequest.create({
			accountId: "biz_xxxxxxxxxxxxx",
			currency: "usd",
			amount: 1000,
			lineItems: [{ label: "Pro access", amount: 1000 }],
		});
		requestRef.current = paymentRequest;
		// Step 1.3: Check which wallets can pay
		paymentRequest.canMakePayment().then(({ applePay, googlePay }) => {
			setWallets([
				...(applePay ? (["apple_pay"] as const) : []),
				...(googlePay ? (["google_pay"] as const) : []),
			]);
		});
	}, [whop]);

	async function pay(wallet: Wallet) {
		const paymentRequest = requestRef.current;
		if (!paymentRequest || !whop) return;
		setError(null);

		// Step 1.4: Open the sheet and send the token to your server
		// show() must run inside the press handler, before any await, or Apple refuses the sheet.
		let ctok: string;
		try {
			({ ctok } = await paymentRequest.show(wallet));
		} catch (err) {
			if ((err as Error).message !== "payment_request_cancelled") {
				setError("The wallet sheet couldn't complete. Try again.");
			}
			return;
		}

		const response = await fetch("/api/pay", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ confirmationToken: ctok, orderId }),
		});
		const payment = await response.json();

		// Step 3.1: Handle the next action
		if (payment.status === "paid") {
			window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
			return;
		}

		// Anything but paid means the buyer still has a step, or the charge is still being decided.
		const result = await whop.payments.handleNextAction({
			clientSecret: payment.client_secret,
		});
		// The buyer left for an off-site step; they come back on the return page.
		if (result.redirected) return;

		if (result.status === "succeeded") {
			window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
			return;
		}
		if (result.status === "processing") {
			window.location.assign(`/checkout/return?order=${orderId}&status=processing&payment=${payment.id}`);
			return;
		}
		// A dismissed dialog leaves the payment at requires_action with no error, so a missing error never means success.
		setError(result.lastPaymentError?.message ?? "The payment wasn't completed. Try again.");
	}

	return (
		<>
			{/* Step 1.3: Check which wallets can pay */}
			{wallets.map((wallet) => (
				<button key={wallet} onClick={() => pay(wallet)}>
					{wallet === "apple_pay" ? "Pay with Apple Pay" : "Pay with Google Pay"}
				</button>
			))}
			{error && <p role="alert">{error}</p>}
		</>
	);
}
```

### Cliente: React — `CheckoutReturn.tsx`

```tsx CheckoutReturn.tsx theme={null}
export function CheckoutReturn() {
	// Step 3.2: Read the outcome from the URL
	// Whop appends `payment`, `status`, and `client_secret` to your returnUrl. Your own parameters (here `order`) survive.
	const params = new URLSearchParams(window.location.search);
	const paymentId = params.get("payment");
	const status = params.get("status");
	const orderId = params.get("order");

	// Step 3.3: Show the right face
	if (status === "succeeded") {
		return (
			<section>
				<h1>Thanks for your order</h1>
				<p>Payment {paymentId} is complete. A receipt is on its way to your email.</p>
			</section>
		);
	}

	if (status === "failed" || status === "canceled") {
		return (
			<section>
				<h1>Your payment did not go through</h1>
				<p>No money was taken. You can try again with another payment method.</p>
				<a href={`/checkout?order=${orderId}`}>Back to checkout</a>
			</section>
		);
	}

	return (
		<section>
			<h1>Confirming your payment</h1>
			<p>Your payment is still being processed. We will email you as soon as it is confirmed.</p>
		</section>
	);
}
```

### Cliente: JavaScript — `buy.html`

```html buy.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <!-- Step 1.1: Add the script tag -->
    <script src="https://cdn.whop.com/elements/amber/elements.js" data-whop-elements></script>
  </head>
  <body>
    <button id="apple-pay" hidden>Pay with Apple Pay</button>
    <button id="google-pay" hidden>Pay with Google Pay</button>
    <p id="error" role="alert"></p>

    <script type="module">
      const orderId = new URLSearchParams(window.location.search).get("order");

      // Step 1.2: Create the payment request
      // Amounts are in minor units: 1000 is $10.00.
      const whop = window.WhopElements();
      const paymentRequest = whop.payments.paymentRequest.create({
        accountId: "biz_xxxxxxxxxxxxx",
        currency: "usd",
        amount: 1000,
        lineItems: [{ label: "Pro access", amount: 1000 }],
      });

      // Step 1.3: Check which wallets can pay
      const { applePay, googlePay } = await paymentRequest.canMakePayment();
      document.querySelector("#apple-pay").hidden = !applePay;
      document.querySelector("#google-pay").hidden = !googlePay;

      const errorLine = document.querySelector("#error");

      async function pay(wallet) {
        errorLine.textContent = "";

        // Step 1.4: Open the sheet and send the token to your server
        // show() must run inside the press handler, before any await, or Apple refuses the sheet.
        let ctok;
        try {
          ({ ctok } = await paymentRequest.show(wallet));
        } catch (err) {
          if (err.message !== "payment_request_cancelled") {
            errorLine.textContent = "The wallet sheet couldn't complete. Try again.";
          }
          return;
        }

        const response = await fetch("/api/pay", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ confirmationToken: ctok, orderId }),
        });
        const payment = await response.json();

        // Step 3.1: Handle the next action
        if (payment.status === "paid") {
          window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
          return;
        }

        // Anything but paid means the buyer still has a step, or the charge is still being decided.
        const result = await whop.payments.handleNextAction({
          clientSecret: payment.client_secret,
        });
        // The buyer left for an off-site step; they come back on the return page.
        if (result.redirected) return;

        if (result.status === "succeeded") {
          window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
          return;
        }
        if (result.status === "processing") {
          window.location.assign(`/checkout/return?order=${orderId}&status=processing&payment=${payment.id}`);
          return;
        }
        // A dismissed dialog leaves the payment at requires_action with no error, so a missing error never means success.
        errorLine.textContent = result.lastPaymentError?.message ?? "The payment wasn't completed. Try again.";
      }

      // Step 1.3: Check which wallets can pay
      document.querySelector("#apple-pay").addEventListener("click", () => pay("apple_pay"));
      document.querySelector("#google-pay").addEventListener("click", () => pay("google_pay"));
    </script>
  </body>
</html>
```

### Cliente: JavaScript — `return.html`

```html return.html theme={null}
<!DOCTYPE html>
<html>
  <body>
    <section id="succeeded" hidden>
      <h1>Thanks for your order</h1>
      <p>Payment <span id="payment-id"></span> is complete. A receipt is on its way to your email.</p>
    </section>
    <section id="failed" hidden>
      <h1>Your payment did not go through</h1>
      <p>No money was taken. You can try again with another payment method.</p>
      <a id="retry" href="/checkout">Back to checkout</a>
    </section>
    <section id="pending" hidden>
      <h1>Confirming your payment</h1>
      <p>Your payment is still being processed. We will email you as soon as it is confirmed.</p>
    </section>

    <script type="module">
      // Step 3.2: Read the outcome from the URL
      // Whop appends `payment`, `status`, and `client_secret` to your returnUrl. Your own parameters (here `order`) survive.
      const params = new URLSearchParams(window.location.search);
      const paymentId = params.get("payment");
      const status = params.get("status");
      const orderId = params.get("order");

      // Step 3.3: Show the right face
      if (status === "succeeded") {
        document.querySelector("#payment-id").textContent = paymentId;
        document.querySelector("#succeeded").hidden = false;
      } else if (status === "failed" || status === "canceled") {
        document.querySelector("#retry").href = `/checkout?order=${orderId}`;
        document.querySelector("#failed").hidden = false;
      } else {
        document.querySelector("#pending").hidden = false;
      }
    </script>
  </body>
</html>
```

### Servidor: Next.js — `app/api/pay/route.ts`

```typescript app/api/pay/route.ts theme={null}
// Step 2.1: Install the Whop SDK
import { WhopClient } from "@whop/sdk";

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

export async function POST(request: Request) {
	const { confirmationToken, orderId } = await request.json();

	// Step 2.2: Create the payment from the confirmation token
	const payment = await whop.payments.create({
		account_id: process.env.WHOP_ACCOUNT_ID,
		// Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
		variant: { currency: "usd", initial_price: 10.0, billing_type: "one_time" },
		confirmation_token: confirmationToken,
		return_url: `https://yoursite.com/checkout/return?order=${orderId}`,
		metadata: { order_id: orderId },
	});

	// client_secret is safe to send to the browser. Your API key never is.
	return Response.json({
		id: payment.id,
		status: payment.status,
		client_secret: payment.client_secret,
	});
}
```

### Servidor: Next.js — `app/api/webhooks/whop/route.ts`

```typescript app/api/webhooks/whop/route.ts theme={null}
import { waitUntil } from "@vercel/functions";
import { unwrapWebhook } from "@whop/sdk/helpers";
import type { NextRequest } from "next/server";

export async function POST(request: NextRequest) {
	// Step 2.3: Fulfill from the webhook
	// Give the raw body. Parsing it first changes the bytes and the signature check fails.
	const payload = await request.text();
	const headers = Object.fromEntries(request.headers);

	const event = unwrapWebhook(payload, {
		headers,
		key: process.env.WHOP_WEBHOOK_SECRET!,
	});

	if (event.type === "payment.succeeded") {
		waitUntil(fulfillOrder(event.data));
	}

	// Respond in less than 5 seconds, or Whop retries.
	return new Response("OK", { status: 200 });
}

async function fulfillOrder(payment: Record<string, any>) {
	// Step 2.3: Fulfill from the webhook
	// metadata.order_id is the value you set when you created the payment.
	const orderId = payment.metadata?.order_id;
	console.log(`[PAYMENT SUCCEEDED] ${payment.id} for order ${orderId}`);
	// Mark the order paid in your database and grant access here.
}
```

### Servidor: Express — `server.ts`

```typescript server.ts theme={null}
// Step 2.1: Install the Whop SDK
import { WhopClient } from "@whop/sdk";
import { unwrapWebhook } from "@whop/sdk/helpers";
import express from "express";

const app = express();

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

app.post("/api/pay", express.json(), async (req, res) => {
	const { confirmationToken, orderId } = req.body;

	// Step 2.2: Create the payment from the confirmation token
	const payment = await whop.payments.create({
		account_id: process.env.WHOP_ACCOUNT_ID,
		// Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
		variant: { currency: "usd", initial_price: 10.0, billing_type: "one_time" },
		confirmation_token: confirmationToken,
		return_url: `https://yoursite.com/checkout/return?order=${orderId}`,
		metadata: { order_id: orderId },
	});

	// client_secret is safe to send to the browser. Your API key never is.
	res.json({
		id: payment.id,
		status: payment.status,
		client_secret: payment.client_secret,
	});
});

// Step 2.3: Fulfill from the webhook
// Read the raw body on this route only: parsing it first changes the bytes and the signature check fails.
app.post(
	"/api/webhooks/whop",
	express.raw({ type: "application/json" }),
	(req, res) => {
		const event = unwrapWebhook(req.body.toString("utf8"), {
			headers: req.headers,
			key: process.env.WHOP_WEBHOOK_SECRET!,
		});

		if (event.type === "payment.succeeded") {
			// metadata.order_id is the value you set when you created the payment.
			const orderId = event.data.metadata?.order_id;
			console.log(`[PAYMENT SUCCEEDED] ${event.data.id} for order ${orderId}`);
			// Mark the order paid in your database and grant access here.
		}

		// Respond in less than 5 seconds, or Whop retries.
		res.sendStatus(200);
	},
);

app.listen(3000);
```

### Servidor: Python — `server.py`

```python server.py theme={null}
# Step 2.1: Install the Whop SDK
import os

from fastapi import BackgroundTasks, FastAPI, Request, Response
from whop_sdk import Whop
from whop_sdk.lib.verify_webhook import unwrap

app = FastAPI()
client = Whop(token=os.environ["WHOP_API_KEY"])


@app.post("/api/pay")
async def pay(request: Request):
    body = await request.json()

    # Step 2.2: Create the payment from the confirmation token
    payment = client.payments.create(
        request={
            "account_id": os.environ["WHOP_ACCOUNT_ID"],
            # Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
            "variant": {"currency": "usd", "initial_price": 10.0, "billing_type": "one_time"},
            "confirmation_token": body["confirmationToken"],
            "return_url": f"https://yoursite.com/checkout/return?order={body['orderId']}",
            "metadata": {"order_id": body["orderId"]},
        },
    )

    # client_secret is safe to send to the browser. Your API key never is.
    return {
        "id": payment.id,
        "status": payment.status,
        "client_secret": payment.client_secret,
    }


# Step 2.3: Fulfill from the webhook
@app.post("/api/webhooks/whop")
async def whop_webhook(request: Request, background: BackgroundTasks):
    # Give the raw body. Parsing it first changes the bytes and the signature check fails.
    payload = await request.body()

    event = unwrap(payload, dict(request.headers), os.environ["WHOP_WEBHOOK_SECRET"])

    if event["type"] == "payment.succeeded":
        background.add_task(fulfill_order, event["data"])

    # Respond in less than 5 seconds, or Whop retries.
    return Response(status_code=200)


def fulfill_order(payment):
    # metadata.order_id is the value you set when you created the payment.
    order_id = (payment.get("metadata") or {}).get("order_id")
    print(f"[PAYMENT SUCCEEDED] {payment['id']} for order {order_id}")
    # Mark the order paid in your database and grant access here.
```

## Próximos pasos

* [Referencia de PaymentRequest](https://docs.whop.com/es/elements/latest/payments/paymentRequest.md): handlers de cambios de envío y facturación, `updateWith` y cada opción del recurso.
* [Añadir express checkout](https://docs.whop.com/es/developer/guides/express-checkout.md): deja que Whop renderice los botones de billetera para una variante y confirme el pago por ti.
* [Habilitar Apple Pay y Google Pay](https://docs.whop.com/es/payments/apple-pay.md): añade Apple Pay a tu dominio.
* [Webhooks](https://docs.whop.com/es/developer/guides/webhooks.md): crea el endpoint, guarda el secreto de firma y gestiona los reintentos.


## Related topics

- [Añade Express Checkout](https://docs.whop.com/es/developer/guides/express-checkout.md)
- [Aceptar pagos](https://docs.whop.com/es/developer/guides/accept-payments.md)
- [Payments](https://docs.whop.com/es/elements/latest/payments/overview.md)
