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

# Payment Elements ile ödeme sayfası oluşturun

> Kendi ödeme sayfanızı ödeme öğeleri etrafında tasarlayın: tarayıcıda bir onay token'ı toplayın, sunucunuzdan ücretlendirin ve bir webhook üzerinden siparişi tamamlayın

Kendi ödeme sayfanızı Whop'un ödeme öğeleri etrafında tasarlayın. Öğeler ödeme yöntemini PCI açısından yalıtılmış alanlarda toplar ve size bir onay belirteci verir. Sunucunuz bu belirteci ücret almak için Payments API'ye veya yöntemi kaydetmek için Setup Intents API'ye iletir. Ardından tarayıcı, alıcının hâlâ tamamlaması gereken her adımı bitirir.

**Kod** altındaki dosyalar, aşağıdaki adımlara işaret eden `Step X.Y` yorumları içerir. Bir sunucu uygulaması ve bir istemci uygulaması seçin. Liste, her seçeneğin dosyalarını içerir.

## Ödeme formunu oluşturun

### 1.1 Paketleri kurun (React)

React için Whop Elements paketlerini kurun.

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

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

### 1.1 Script etiketini ekleyin (JavaScript)

Ödeme sayfanızı barındıran sayfaya Whop Elements betiğini yükleyin.

### 1.2 Öğeleri bağlayın

Mevcut `plan` özelliği üzerinden varyant için bir `Payments` tutamacı oluşturun ve altına üç öğe bağlayın. `EmailElement` alıcının e-postasını toplar ve tanınan bir Whop alıcısına kayıtlı ödeme yöntemlerinin kilidini açan bir oturum açma seçeneği sunar. `PaymentElement` varyant ve alıcının ülkesi için kullanılabilen yöntemleri gösterir ve her yöntemin alanlarını barındırılan çerçevelerde toplar; böylece kart numaraları asla sayfanıza ulaşmaz. `BrandingElement`, her ödeme formunun taşıması gereken Whop'un kayıtlı satıcı (merchant-of-record) bildirimini gösterir.

Tutamaç, varyantın para birimini, tutarını ve ödeme yöntemlerini kendi başına çözümler. `returnUrl` değerini `https` üzerinden barındırdığınız bir sayfaya ayarlayın. Banka yönlendirmeleri, finansman başvuruları ve bazı 3D Secure akışları alıcıyı oraya geri getirir. Sipariş kimliği gibi kendi sorgu parametrelerinizi ekleyin. Gidiş-dönüş boyunca korunurlar.

Bir ödeme yöntemini ücret almadan kaydetmek için aynı öğeleri `plan` yerine `mode: "setup"` ve bir `currency` ile bağlayın. [Ödeme yöntemlerini kaydetme](https://docs.whop.com/tr/developer/guides/save-payment-methods.md) kılavuzu bu formu ele alır.

### 1.3 Ödeme düğmesini etkinleştirin

`PaymentElement`, alıcı bir yöntem seçip gerekenleri doldurduğunda `onChange` aracılığıyla `complete: true` bildirir. Ödeme düğmenizi buna göre etkinleştirin. Düğme size aittir: etiketi, konumu ve basıldığında ne olacağı.

### 1.4 Onay belirtecini oluşturun

Basıldığında `createConfirmationToken` çağırın. Bu, öğelerin topladıklarını ödeme yöntemini temsil eden tek kullanımlık bir `ctok_` belirtecine dönüştürür. Belirteç, öğelerin topladığı e-posta ve fatura bilgilerini taşır. Bir cüzdan seçimi bu çağrı sırasında Apple Pay veya Google Pay'i açar ve sayfada hiçbir `BrandingElement` yokken çağrı reddedilir.

Belirteci kendi sipariş referansınızla birlikte sunucunuza gönderin. Belirteç, ödeme yöntemiyle ilgili tarayıcıdan çıkan tek şeydir.

## Sunucunuzdan ücret alın

### 2.1 Whop SDK'sını kurun (Next.js)

Whop SDK'sını kurun ve Hesap API anahtarınızla bir istemci oluşturun. Anahtar sunucuda kalır. Tarayıcı onu asla görmez.

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

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

### 2.1 Whop SDK'sını kurun (Express)

Whop SDK'sını kurun ve Hesap API anahtarınızla bir istemci oluşturun. Anahtar sunucuda kalır. Tarayıcı onu asla görmez.

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

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

### 2.1 Whop SDK'sını kurun (Python)

Whop SDK'sını kurun ve Hesap API anahtarınızla bir istemci oluşturun. Anahtar sunucuda kalır. Tarayıcı onu asla görmez.

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

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

### 2.2 Ödemeyi onay belirtecinden oluşturun

Belirteci Payments API'ye iletin. Whop alıcıyı belirtecin e-postasından çözümler, varyant için ücret alır ve ödemeyi bir `client_secret` ile döndürür. `id`, `status` ve `client_secret` değerlerini tarayıcıya döndürün. `client_secret` yalnızca bu tek ödemenin kilidini açar, bu yüzden açığa çıkarmak güvenlidir.

`return_url` değerini öğelerin döndüğü sayfayla aynı sayfaya ayarlayın. Ödemenin ve webhook'larının taşıması için kendi sipariş kimliğinizi `metadata` içine koyun. Kurulum modundaki bir form için belirteci bunun yerine [Setup Intents API](https://docs.whop.com/tr/api-reference/setup-intents/create-setup-intent.md)'ye iletin. Aynı `client_secret` yapısına sahip bir kurulum amacı (setup intent) döndürür.

* `variant_id`, alıcının satın aldığı varyanttır. Henüz kayıtlı bir varyant olmayan bir tutar için ücret almak istiyorsanız bunun yerine satır içi bir `variant` geçirin
* `confirmation_token`, öğelerin topladığı ödeme yöntemini temsil eder
* `metadata`, ödemeyi kendi siparişinize bağlar

### 2.3 Teslimatı webhook'tan yapın

Ücret başarılı olduğunda, alıcı ister satır içinde ödemiş ister site dışı bir adımdan geri dönmüş olsun, Whop webhook uç noktanıza `payment.succeeded` gönderir. İmzayı SDK yardımcısıyla doğrulayın, ardından teslimat işini yapın: siparişi ödendi olarak işaretleyin, erişim verin ve e-postayı gönderin.

Teslimat buraya aittir, başka hiçbir yere değil. Alıcı, dönüş sayfanız yüklenmeden tarayıcıyı kapatabilir, bir yönlendirme başarısız olabilir ve herkes bir sorgu parametresini elle yazabilir. Webhook'u oluşturmak ve `ws_` gizli anahtarını `WHOP_WEBHOOK_SECRET` olarak saklamak için [Webhook'lar kılavuzunu](https://docs.whop.com/tr/developer/guides/webhooks.md) izleyin.

## Ödemeyi tamamlayın

### 3.1 Sonraki eylemi işleyin

`paid` olarak dönen bir ödeme tamamlanmıştır. Diğer her şey, alıcının 3D Secure veya banka yönlendirmesi gibi hâlâ bir adımı olduğu ya da ücretin hâlâ beklemede olduğu anlamına gelir. `client_secret` değerini `handleNextAction` öğesine geçirin. Bu, satır içi bir adımı bir iletişim kutusunda çalıştırır ve `redirected: false` ile çözümlenir ya da alıcıyı `returnUrl` adresinize gönderir ve `redirected: true` ile çözümlenir.

Döndürdüğü `status` değerine göre dallanın. `succeeded` alıcının ödeme yaptığı, `processing` ücretin hâlâ beklemede olduğu anlamına gelir; diğer her şey yeni bir deneme gerektirir. Bir neden olduğunda `lastPaymentError` bunu taşır. Kapatılan bir iletişim kutusu ödemeyi hatasız olarak `requires_action` durumunda bırakır; bu nedenle hatanın olmaması asla başarı anlamına gelmez.

### 3.2 Sonucu URL'den okuyun

Site dışı bir adım için ayrılan bir alıcı, orada **ne olursa olsun** `returnUrl` adresine gelir. Whop üç sorgu parametresi ekler. `payment`, `pay_` kimliğidir. `status`, alıcı ödeme yaptığında `succeeded`, yapmadığında `failed` veya `canceled`, ücret henüz kesinleşmemişken ise `processing` gibi bekleyen bir durumdur. `client_secret`, bir kararı beklemek isterse sayfanın ödemenin durumunu sorgulamasını sağlar.

`order` gibi kendi parametreleriniz URL'de kalır. Kart reddedilmeleri bu sayfaya asla ulaşmaz, çünkü `handleNextAction` bunları satır içinde bildirir. Dönüş sayfası, sitenizin başarısız bir site dışı ödemeyi gördüğü tek yerdir.

### 3.3 Doğru görünümü gösterin

`status` değerine göre dallanın. `succeeded` teşekkür sayfasını alır. `failed` ve `canceled`, alıcıdan ücret alınmadığını belirten bir mesaj ve ödeme sayfasına geri dönen bir bağlantı alır. Diğer her şey, ücretin hâlâ beklemede olduğu anlamına gelir. Alıcıya e-postayla onaylayacağınızı söyleyin. Formdaki satır içi yollar alıcıyı aynı parametrelerle aynı sayfaya gönderir, böylece tek bir sayfa her sonucu işler.

Sayfayı ödemenin kanıtı olarak değil, sonucun bir gösterimi olarak ele alın. Herkes bir URL'ye `status=succeeded` yazabilir. Erişim, indirmeler ve sipariş teslimatı sunucunuzdaki `payment.succeeded` webhook'undan gelir.

## Kod

### İstemci: React — `PaymentForm.tsx`

```tsx PaymentForm.tsx theme={null}
// Step 1.1: Install the packages
import { useState } from "react";
import {
	BrandingElement,
	EmailElement,
	PaymentElement,
	Payments,
	WhopElements,
	usePayments,
	useWhop,
} from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function CheckoutPage({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			{/* Step 1.2: Mount the elements */}
			<Payments
				accountId="biz_xxxxxxxxxxxxx"
				plan="plan_xxxxxxxxxxxxx"
				returnUrl={`https://yoursite.com/checkout/return?order=${orderId}`}
			>
				<PaymentForm orderId={orderId} />
			</Payments>
		</WhopElements>
	);
}

function PaymentForm({ orderId }: { orderId: string }) {
	const payments = usePayments();
	const whop = useWhop();
	const [ready, setReady] = useState(false);
	const [error, setError] = useState<string | null>(null);

	async function pay() {
		if (!payments || !whop) return;
		setError(null);

		// Step 1.4: Create the confirmation token
		// A single-use ctok_ token that stands in for the payment method. Card data never touches your page.
		const { confirmationToken } = await payments.createConfirmationToken({});

		const response = await fetch("/api/pay", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ confirmationToken, 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 step wasn't completed. Try again.");
	}

	return (
		<>
			{/* Step 1.2: Mount the elements */}
			<EmailElement />
			{/* Step 1.3: Enable the pay button */}
			<PaymentElement onChange={(event) => setReady(event.complete)} />
			{/* Step 1.2: Mount the elements */}
			<BrandingElement />
			{/* Step 1.3: Enable the pay button */}
			<button disabled={!ready} onClick={pay}>
				Pay
			</button>
			{error && <p role="alert">{error}</p>}
		</>
	);
}
```

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

### İstemci: JavaScript — `checkout.html`

```html checkout.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="email"></div>
    <div id="payment"></div>
    <div id="branding"></div>
    <button id="pay" disabled>Pay</button>
    <p id="error" role="alert"></p>

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

      // Step 1.2: Mount the elements
      const whop = window.WhopElements();
      const payments = whop.payments.create({
        accountId: "biz_xxxxxxxxxxxxx",
        plan: "plan_xxxxxxxxxxxxx",
        returnUrl: `https://yoursite.com/checkout/return?order=${orderId}`,
      });

      payments.create("email").mount("#email");
      const payButton = document.querySelector("#pay");
      const errorLine = document.querySelector("#error");

      // Step 1.3: Enable the pay button
      payments
        .create("payment", { onChange: (event) => (payButton.disabled = !event.complete) })
        .mount("#payment");
      // Step 1.2: Mount the elements
      payments.create("branding").mount("#branding");

      payButton.addEventListener("click", async () => {
        errorLine.textContent = "";

        // Step 1.4: Create the confirmation token
        // A single-use ctok_ token that stands in for the payment method. Card data never touches your page.
        const { confirmationToken } = await payments.createConfirmationToken({});

        const response = await fetch("/api/pay", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ confirmationToken, 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 step wasn't completed. Try again.";
      });
    </script>
  </body>
</html>
```

### İstemci: 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>
```

### Sunucu: 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,
		variant_id: "plan_xxxxxxxxxxxxx",
		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,
	});
}
```

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

### Sunucu: 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,
		variant_id: "plan_xxxxxxxxxxxxx",
		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);
```

### Sunucu: 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"],
            "variant_id": "plan_xxxxxxxxxxxxx",
            "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.
```

## Sonraki adımlar

* [Ödeme öğeleri referansı](https://docs.whop.com/tr/elements/latest/payments/overview): Payments tanıtıcısındaki her seçenek, olay ve yöntem.
* [Hızlı ödeme](https://docs.whop.com/tr/developer/guides/express-checkout.md): formun yanına tek dokunuşla Apple Pay ve Google Pay ekleyin.
* [Ödeme yöntemlerini kaydedin](https://docs.whop.com/tr/developer/guides/save-payment-methods.md): bir yöntemi ücretlendirmeden kaydedin, ardından daha sonra sunucunuzdan ücretlendirin.
* [Ödeme sayfası yerleştirin](https://docs.whop.com/tr/developer/guides/embed-checkout.md): formu atlayın ve bunun yerine Whop'un ödeme sayfasının tamamını yerleştirin.


## Related topics

- [Payments](https://docs.whop.com/tr/elements/latest/payments/overview.md)
- [CardElement](https://docs.whop.com/tr/elements/latest/payments/card.md)
- [Elements ile başlarken](https://docs.whop.com/tr/elements/latest/getting-started.md)
