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

# Open een wallet-sheet vanuit je eigen knop

> Open de Apple Pay- of Google Pay-sheet vanuit een knop die je zelf rendert, bepaal zelf de prijs van de bestelling en belast het confirmation token vanaf je server

Gebruik de payment request-resource wanneer je de koopknop zelf rendert en de prijs van de bestelling zelf bepaalt. Eén druk opent het Apple Pay- of Google Pay-venster, het venster geeft je een bevestigingstoken, en je server geeft het token door aan de Payments API om af te rekenen.

De bestanden onder **Code** bevatten `Step X.Y`-opmerkingen die verwijzen naar de stappen hieronder. Kies één serverimplementatie en één clientimplementatie. De lijst bevat de bestanden voor elke optie.

## Je walletknop bouwen

### 1.1 De pakketten installeren (React)

Installeer de Whop Elements-pakketten voor 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 De scripttag toevoegen (JavaScript)

Laad het Whop Elements-script op de pagina waarop de knop staat.

### 1.2 Het payment request aanmaken

Maak het request aan met je account, de valuta en het bedrag in kleinste eenheden. `lineItems` zijn de regels die het venster onder het totaal toont. Er wordt niets gekoppeld: de resource is het walletvenster zonder element, en de knop is van jou.

Wallets openen alleen op pagina's waarvan het domein klaar is voor Apple Pay. Volg [Apple Pay en Google Pay inschakelen](https://docs.whop.com/nl/payments/apple-pay.md) eenmaal per domein, lever de pagina via `https` en test op een echt apparaat waarop een wallet is ingesteld.

### 1.3 Controleren welke wallets kunnen betalen

Wacht op `canMakePayment()` voordat je een knop toont. Die meldt met welke wallets dit apparaat, dit account en dit domein kunnen betalen, en bereidt het venster voor zodat het later synchroon kan openen. Render alleen een knop voor een wallet die `true` teruggaf.

Apple en Google vereisen elk hun eigen knopafbeelding op een aangepaste knop. Volg de [Apple Pay-knoprichtlijnen](https://developer.apple.com/design/human-interface-guidelines/apple-pay) en de [Google Pay-merkrichtlijnen](https://developers.google.com/pay/api/web/guides/brand-guidelines).

### 1.4 Het venster openen en het token naar je server sturen

Roep `show(type)` als allereerste aan in de drukhandler van de knop, vóór een eventuele `await`. Apple weigert een venster dat buiten die gebruikersactie wordt geopend, en daarom is `canMakePayment()` al eerder uitgevoerd. Het venster vraagt om het e-mailadres van de koper, tenzij je er een meegeeft met `show("apple_pay", \{ email \})`.

`show` wordt afgerond zodra de koper autoriseert. `ctok` is het bevestigingstoken voor eenmalig gebruik, `type` noemt de wallet, en `payer` bevat het e-mailadres, de naam, het telefoonnummer en het factuurland van de koper zoals de wallet die heeft doorgegeven. Als een koper het venster sluit, wordt `show` afgewezen met een `payment_request_cancelled`-fout. Het venster sluit met een vinkje zodra het token is aangemaakt, nog voordat je server bevestigt, dus toon het resultaat van je server op je pagina.

Stuur `ctok` samen met je eigen bestelreferentie naar je server. Om een verzendadres te verzamelen en verzendopties aan te bieden, stel je `requestShipping` in en beantwoord je de wijzigingen in het venster met `updateWith`. De [PaymentRequest-referentie](https://docs.whop.com/nl/elements/latest/payments/paymentRequest.md) behandelt die handlers.

## Afrekenen vanaf je server

### 2.1 De Whop SDK installeren (Next.js)

Installeer de Whop SDK en maak een client aan met je Account API-sleutel. De sleutel blijft op de server. De browser ziet hem nooit.

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

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

### 2.1 De Whop SDK installeren (Express)

Installeer de Whop SDK en maak een client aan met je Account API-sleutel. De sleutel blijft op de server. De browser ziet hem nooit.

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

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

### 2.1 De Whop SDK installeren (Python)

Installeer de Whop SDK en maak een client aan met je Account API-sleutel. De sleutel blijft op de server. De browser ziet hem nooit.

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

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

### 2.2 De betaling aanmaken vanuit het bevestigingstoken

Geef het token door aan de Payments API. Whop bepaalt de koper aan de hand van het e-mailadres in het token, rekent de variant af en retourneert de betaling met een `client_secret`. Stuur `id`, `status` en `client_secret` terug naar de browser. De `client_secret` ontgrendelt alleen deze ene betaling, dus je kunt hem veilig blootstellen.

Reken af wat het venster toonde. Het `amount` van het request staat in kleinste eenheden, dus `1000` in het venster is hier een `initial_price` van `10.0`. Geef een inline `variant` mee om een variant voor deze prijs te vinden of aan te maken, of `variant_id` voor een variant die je al hebt aangemaakt. Stel `return_url` in op de pagina waarop de koper moet terechtkomen na een stap op een volledige pagina, en zet je eigen bestel-ID in `metadata` zodat de betaling en de bijbehorende webhooks die bevatten.

* Een inline `variant` vindt of maakt de variant voor deze prijs. Gebruik `variant_id` wanneer de prijs al als variant bestaat
* `confirmation_token` vertegenwoordigt de walletkaart die het venster heeft geautoriseerd
* `metadata` koppelt de betaling terug aan je eigen bestelling
* Stuur voor fysieke goederen het `shipping.address` uit het resultaat mee met het token en geef het door als `shipping_address`

### 2.3 Uitleveren vanuit de webhook

Whop stuurt `payment.succeeded` naar je webhookendpoint zodra de betaling slaagt. Verifieer de handtekening met de SDK-helper en voer daarna het uitleverwerk uit: markeer de bestelling als betaald, verleen toegang en verstuur de e-mail. Een walletbetaling meldt `apple_pay` of `google_pay` in `payment_method_type`.

Uitlevering hoort hier thuis en nergens anders. Het vinkje in het venster, de browser en een queryparameter kunnen allemaal "betaald" zeggen zonder dat de betaling is afgewikkeld. Volg de [Webhooks-gids](https://docs.whop.com/nl/developer/guides/webhooks.md) om de webhook aan te maken en het `ws_`-geheim op te slaan als `WHOP_WEBHOOK_SECRET`.

## De betaling voltooien

### 3.1 De volgende actie afhandelen

Een betaling die terugkomt met `paid` is voltooid. Al het andere betekent dat de koper nog een stap moet doen, zoals 3D Secure, of dat de betaling nog in behandeling is. Geef de `client_secret` door aan `handleNextAction`. Die voert een inline stap uit in een dialoogvenster en wordt afgerond met `redirected: false`, of stuurt de koper naar je `return_url` en wordt afgerond met `redirected: true`.

Vertak op de `status` die wordt geretourneerd. `succeeded` betekent dat de koper heeft betaald, `processing` betekent dat de betaling nog in behandeling is, en al het andere vereist een nieuwe poging. `lastPaymentError` bevat de reden als die er is. Een gesloten dialoogvenster laat de betaling op `requires_action` staan zonder fout, dus een ontbrekende fout betekent nooit dat de betaling is geslaagd.

### 3.2 De uitkomst uit de URL lezen

Een koper die is vertrokken voor een stap op een volledige pagina, komt op `return_url` terecht, **wat er daar ook gebeurde**. Whop voegt drie queryparameters toe. `payment` is de `pay_`-ID. `status` is `succeeded` wanneer de koper heeft betaald, `failed` of `canceled` wanneer dat niet zo is, en een status in behandeling zoals `processing` zolang er over de betaling nog niet is beslist. Met `client_secret` kan de pagina de status van de betaling pollen als die op een beslissing wil wachten.

Je eigen parameters, zoals `order`, blijven in de URL staan. `handleNextAction` meldt inline weigeringen zelf, dus de retourpagina is de enige plek waar je site een mislukte stap buiten de site ziet.

### 3.3 De juiste weergave tonen

Vertak op `status`. `succeeded` krijgt de bedankpagina. `failed` en `canceled` krijgen een melding dat de koper niets in rekening is gebracht, plus een link terug naar het product. Al het andere betekent dat de betaling nog in behandeling is. Laat de koper weten dat je per e-mail bevestigt. De inline routes in de knophandler sturen de koper naar dezelfde pagina met dezelfde parameters, dus één pagina handelt elke afloop af.

Behandel de pagina als een weergave van de uitkomst, niet als betalingsbewijs. Iedereen kan `status=succeeded` in een URL typen. Toegang, downloads en de afhandeling van bestellingen komen voort uit de webhook `payment.succeeded` op je server.

## Code

### Client: 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>}
		</>
	);
}
```

### Client: 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>
	);
}
```

### Client: 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>
```

### Client: 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>
```

### Server: 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,
	});
}
```

### Server: 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.
}
```

### Server: 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);
```

### Server: 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.
```

## Volgende stappen

* [PaymentRequest-referentie](https://docs.whop.com/nl/elements/latest/payments/paymentRequest.md): handlers voor wijzigingen in verzend- en factuurgegevens, `updateWith` en elke optie op de resource.
* [Express checkout toevoegen](https://docs.whop.com/nl/developer/guides/express-checkout.md): laat Whop de wallet-knoppen voor een variant renderen en de betaling voor je bevestigen.
* [Apple Pay en Google Pay inschakelen](https://docs.whop.com/nl/payments/apple-pay.md): voeg Apple Pay toe aan je domein.
* [Webhooks](https://docs.whop.com/nl/developer/guides/webhooks.md): maak het endpoint aan, bewaar het signing secret en handel retries af.


## Related topics

- [Express Checkout toevoegen](https://docs.whop.com/nl/developer/guides/express-checkout.md)
- [Betalingen accepteren](https://docs.whop.com/nl/developer/guides/accept-payments.md)
- [Wallet](https://docs.whop.com/nl/elements/latest/wallet/overview.md)
