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

# Añade Express Checkout

> Coloca botones de Apple Pay y Google Pay de un solo toque en tu página con el elemento Express Checkout, directamente desde el navegador, y realiza el fulfillment desde un webhook

Coloca botones de Apple Pay y Google Pay de un solo toque en una página de producto con el elemento Express Checkout. Whop muestra los monederos con los que el dispositivo puede pagar y confirma el pago por ti. Tu servidor solo escucha el webhook.

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.

## Añade los botones 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 los botones.

### 1.2 Monta los botones

Monta `ExpressCheckoutElement` dentro de un handle `Checkout` y pasa la variante mediante la propiedad `plan` existente. El elemento solo muestra los monederos con los que puede pagar el dispositivo del comprador, priorizando el más nativo para el navegador, y no muestra nada cuando no hay ningún monedero disponible. Mantén una opción de checkout normal en la página para esos compradores.

Pasa `metadata`, como tu propio ID de pedido, en el handle. Whop lo copia en el pago y en todos los webhooks relacionados con él. Establece `returnUrl` en una página que alojes con `https`. Una compra finalizada redirige la pestaña allí, al igual que un pago que necesitó un paso a página completa.

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 Elige los monederos y el diseño

`wallets` limita qué monederos pueden mostrarse, por ejemplo `["apple_pay"]`. El elemento nunca muestra un monedero que el dispositivo o la configuración de métodos de pago del checkout no puedan respaldar, así que la lista es un límite máximo, no una garantía.

`layout` organiza los botones. `auto` se adapta al ancho del contenedor, y `horizontal` o `vertical` fuerzan una disposición concreta. `appearance` en el handle aplica el tema a las líneas de resultado y de error del elemento.

### 1.4 Registra la finalización

Al pulsar se abre la hoja del monedero. Cuando el comprador autoriza, Whop confirma el pago en la sesión de checkout, y la marca de verificación de la hoja sigue a esa confirmación. `onComplete` se ejecuta una vez que el resultado es definitivo, antes de cualquier navegación a `returnUrl`. Úsalo para analíticas y píxeles de anuncios.

No gestiones el pedido desde ahí. Un checkout restaurado al recargar la página más tarde lo vuelve a ejecutar con el mismo resultado. Un pago que salió a un paso a página completa se completa en la página de retorno.

## Gestiona la página de retorno

### 2.1 Lee el resultado de la URL

La mayoría de los pagos con monedero se liquidan en línea, y un pago que todavía necesita un paso lo ejecuta en un diálogo cuando el paso cabe en uno. Un paso que solo puede ejecutarse a página completa, como una redirección bancaria, abandona la página y devuelve al comprador a `returnUrl` **pase lo que pase**. Whop añade dos parámetros de consulta. `payment` es el ID `pay_`. `status` es `succeeded` cuando el comprador ha pagado, y `failed` o `canceled` cuando no.

Tus propios parámetros, como `order`, se mantienen en la URL. El propio elemento informa de 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.

### 2.2 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, como `processing`, significa que el cargo sigue pendiente. Indica al comprador que le confirmarás por correo electrónico.

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.

## Gestiona el pedido desde tu servidor

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

El helper de webhooks se incluye en el SDK de Whop. Instálalo en el servidor que recibe el webhook.

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

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

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

El helper de webhooks se incluye en el SDK de Whop. Instálalo en el servidor que recibe el webhook.

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

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

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

El helper de webhooks se incluye en el SDK de Whop. Instálalo en el servidor que recibe el webhook.

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

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

### 3.2 Gestiona el webhook de pago

Whop envía `payment.succeeded` a tu endpoint de webhook una vez que el comprador ha pagado. 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`, y el pago incluye los `metadata` que estableciste en el handle de Checkout.

La gestión del pedido debe hacerse aquí y en ningún otro sitio. El comprador puede cerrar el navegador antes de que cargue tu página de retorno, una redirección puede fallar y cualquiera puede escribir un parámetro de consulta a mano. 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`.

## Código

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

```tsx BuyButton.tsx theme={null}
// Step 1.1: Install the packages
import { Checkout, ExpressCheckoutElement, WhopElements } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function BuyButton({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			{/* Step 1.2: Mount the buttons */}
			<Checkout
				plan="plan_xxxxxxxxxxxxx"
				metadata={{ order_id: orderId }}
				returnUrl={`https://yoursite.com/checkout/return?order=${orderId}`}
				// Step 1.4: Record the completion
				onComplete={(completion) => {
					if (completion.result === "payment") {
						// Fire analytics or ad pixels here. Fulfill from the webhook, not from this callback.
						console.log("Express checkout completed", completion.paymentId);
					}
				}}
			>
				{/* Step 1.3: Pick the wallets and layout */}
				<ExpressCheckoutElement layout="horizontal" wallets={["apple_pay", "google_pay"]} />
			</Checkout>
		</WhopElements>
	);
}
```

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

```tsx CheckoutReturn.tsx theme={null}
export function CheckoutReturn() {
	// Step 2.1: Read the outcome from the URL
	// Whop appends `payment` and `status` 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 2.2: 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>
    <div id="express-checkout"></div>

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

      // Step 1.2: Mount the buttons
      const checkout = window.WhopElements().checkout.create({
        plan: "plan_xxxxxxxxxxxxx",
        metadata: { order_id: orderId },
        returnUrl: `https://yoursite.com/checkout/return?order=${orderId}`,
        // Step 1.4: Record the completion
        onComplete: (completion) => {
          if (completion.result === "payment") {
            // Fire analytics or ad pixels here. Fulfill from the webhook, not from this callback.
            console.log("Express checkout completed", completion.paymentId);
          }
        },
      });
      // Step 1.3: Pick the wallets and layout
      checkout
        .create("expressCheckout", { layout: "horizontal", wallets: ["apple_pay", "google_pay"] })
        .mount("#express-checkout");
    </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 2.1: Read the outcome from the URL
      // Whop appends `payment` and `status` 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 2.2: 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/webhooks/whop/route.ts`

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

export async function POST(request: NextRequest) {
	// Step 3.2: Handle the payment 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 3.2: Handle the payment webhook
	// metadata.order_id is the value you set on the Checkout handle.
	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 3.1: Install the Whop SDK
import { unwrapWebhook } from "@whop/sdk/helpers";
import express from "express";

const app = express();

// Step 3.2: Handle the payment webhook
// Read the raw body on this route: 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 on the Checkout handle.
			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 3.1: Install the Whop SDK
import os

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

app = FastAPI()


# Step 3.2: Handle the payment 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 on the Checkout handle.
    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 del elemento Express Checkout](https://docs.whop.com/es/elements/latest/checkout/expressCheckout.md): todas las opciones, eventos y hooks de estilo del elemento.
* [Abre una hoja de wallet desde tu propio botón](https://docs.whop.com/es/developer/guides/payment-request.md): renderiza el botón tú mismo y fija el precio del pedido tú mismo con el recurso payment request.
* [Activa Apple Pay y Google Pay](https://docs.whop.com/es/payments/apple-pay.md): añade Apple Pay a tu dominio.
* [Integra un checkout](https://docs.whop.com/es/developer/guides/embed-checkout.md): el formulario de checkout completo, que ya muestra los botones de wallet encima.


## Related topics

- [ExpressCheckoutElement](https://docs.whop.com/es/elements/latest/checkout/expressCheckout.md)
- [Checkout](https://docs.whop.com/es/elements/latest/checkout/overview.md)
- [Crea un checkout con Payment Elements](https://docs.whop.com/es/developer/guides/payment-elements.md)
