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

# Kendi düğmenizden bir cüzdan sayfası açın

> Apple Pay veya Google Pay sayfasını kendi oluşturduğunuz bir düğmeden açın, siparişi kendiniz fiyatlandırın ve onay token'ını sunucunuzdan ücretlendirin

Satın alma düğmesini kendiniz işlediğinizde ve siparişi kendiniz fiyatlandırdığınızda ödeme isteği kaynağını kullanın. Tek bir dokunuş Apple Pay veya Google Pay sayfasını açar, sayfa size bir onay belirteci verir ve sunucunuz ücret almak için belirteci Payments API'ye iletir.

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

## Cüzdan düğmenizi 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)

Düğmeyi gösteren sayfaya Whop Elements betiğini yükleyin.

### 1.2 Ödeme isteğini oluşturun

İsteği hesabınız, para birimi ve küçük birim cinsinden tutarla oluşturun. `lineItems`, sayfanın toplamın altında listelediği satırlardır. Hiçbir şey bağlanmaz: kaynak, öğesi olmayan cüzdan sayfasıdır ve düğme size aittir.

Cüzdanlar yalnızca alan adında Apple Pay'in hazır olduğu sayfalarda açılır. Her alan adı için bir kez [Apple Pay ve Google Pay'i etkinleştirme](https://docs.whop.com/tr/payments/apple-pay.md) adımlarını izleyin, sayfayı `https` üzerinden sunun ve cüzdanı kurulu gerçek bir cihazda test edin.

### 1.3 Hangi cüzdanların ödeme yapabileceğini kontrol edin

Bir düğme göstermeden önce `canMakePayment()` sonucunu bekleyin. Bu cihazın, bu hesabın ve bu alan adının hangi cüzdanlarla ödeme yapabileceğini bildirir ve sayfayı daha sonra eşzamanlı olarak açılabilecek şekilde hazırlar. Yalnızca `true` olarak dönen bir cüzdan için düğme işleyin.

Apple ve Google, özel bir düğmede her biri kendi düğme görselini zorunlu tutar. [Apple Pay düğme yönergelerini](https://developer.apple.com/design/human-interface-guidelines/apple-pay) ve [Google Pay marka yönergelerini](https://developers.google.com/pay/api/web/guides/brand-guidelines) izleyin.

### 1.4 Sayfayı açın ve belirteci sunucunuza gönderin

Düğmenin basma işleyicisinde, herhangi bir `await` öncesinde ilk iş olarak `show(type)` çağırın. Apple, bu kullanıcı hareketinin dışında açılan bir sayfayı reddeder; `canMakePayment()` işleminin önceden çalışmasının nedeni budur. Sayfa, `show("apple_pay", \{ email \})` ile bir e-posta geçirmediğiniz sürece alıcının e-postasını ister.

`show`, alıcı yetkilendirdiğinde çözümlenir. `ctok` tek kullanımlık onay belirtecidir, `type` cüzdanı adlandırır ve `payer`, alıcının e-postasını, adını, telefonunu ve fatura ülkesini cüzdanın verdiği şekliyle taşır. Sayfayı kapatan bir alıcı, `show` işlemini `payment_request_cancelled` hatasıyla reddeder. Sayfa, belirteç oluşturulur oluşturulmaz, sunucunuz onaylamadan önce bir onay işaretiyle kapanır; bu yüzden sunucunuzun sonucunu kendi sayfanızda gösterin.

`ctok` değerini kendi sipariş referansınızla birlikte sunucunuza gönderin. Bir teslimat adresi toplamak ve teslimat seçenekleri sunmak için `requestShipping` ayarlayın ve sayfanın değişikliklerine `updateWith` ile yanıt verin. [PaymentRequest başvurusu](https://docs.whop.com/tr/elements/latest/payments/paymentRequest.md) bu işleyicileri ele alır.

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

Sayfanın gösterdiği tutar kadar ücret alın. İsteğin `amount` değeri küçük birim cinsindendir, yani sayfadaki `1000` burada `10.0` değerinde bir `initial_price` olur. Bu fiyat için bir varyant bulmak veya oluşturmak üzere satır içi bir `variant`, ya da önceden oluşturduğunuz bir varyant için `variant_id` geçirin. `return_url` değerini alıcının tam sayfa bir adımdan sonra varması gereken sayfaya ayarlayın ve ödemenin ve webhook'larının taşıması için kendi sipariş kimliğinizi `metadata` içine koyun.

* Satır içi bir `variant`, bu fiyat için varyantı bulur veya oluşturur. Fiyat zaten bir varyant olarak mevcutsa `variant_id` kullanın
* `confirmation_token`, sayfanın yetkilendirdiği cüzdan kartını temsil eder
* `metadata`, ödemeyi kendi siparişinize bağlar
* Fiziksel ürünler için sonucun `shipping.address` değerini belirteçle birlikte gönderin ve `shipping_address` olarak geçirin

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

Ücret başarılı olduğunda 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. Bir cüzdan ödemesi `payment_method_type` içinde `apple_pay` veya `google_pay` bildirir.

Teslimat buraya aittir, başka hiçbir yere değil. Sayfanın onay işareti, tarayıcı ve bir sorgu parametresi, ücret kesinleşmeden ödendi diyebilir. 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 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ı `return_url` 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

Tam sayfa bir adım için ayrılan bir alıcı, orada **ne olursa olsun** `return_url` 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. `handleNextAction` satır içi reddedilmeleri kendisi bildirir, bu yüzden dönüş sayfası, sitenizin başarısız bir site dışı adımı 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 ürüne 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. Düğme işleyicisindeki 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 — `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>}
		</>
	);
}
```

### İ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 — `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>
```

### İ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,
		// 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,
	});
}
```

### 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,
		// 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);
```

### 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"],
            # 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.
```

## Sonraki adımlar

* [PaymentRequest referansı](https://docs.whop.com/tr/elements/latest/payments/paymentRequest.md): gönderim ve fatura bilgisi değişikliği işleyicileri, `updateWith` ve kaynaktaki her seçenek.
* [Hızlı ödeme ekleyin](https://docs.whop.com/tr/developer/guides/express-checkout.md): bir varyant için cüzdan düğmelerini Whop'un oluşturmasına ve ödemeyi sizin yerinize onaylamasına izin verin.
* [Apple Pay ve Google Pay'i etkinleştirin](https://docs.whop.com/tr/payments/apple-pay.md): alan adınıza Apple Pay ekleyin.
* [Webhook'lar](https://docs.whop.com/tr/developer/guides/webhooks.md): uç noktayı oluşturun, imzalama sırrını saklayın ve yeniden denemeleri ele alın.


## Related topics

- [Express Checkout ekleyin](https://docs.whop.com/tr/developer/guides/express-checkout.md)
- [Ödeme Alın](https://docs.whop.com/tr/developer/guides/accept-payments.md)
- [Payment Elements ile ödeme sayfası oluşturun](https://docs.whop.com/tr/developer/guides/payment-elements.md)
