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

# OAuth

> Voeg "Sign in with Whop" toe aan je site met OAuth 2.1 en Proof Key for Code Exchange (PKCE).

Gebruik OAuth 2.1 + PKCE met OpenID Connect (OIDC) om gebruikers met Whop te laten inloggen op je website of in je app. Met de teruggegeven access tokens kun je gegevens benaderen en namens die gebruikers handelen.

> [!NOTE]
>
> OAuth-endpoints staan op `https://api.whop.com/oauth/`.

## Stap 1: Maak je OAuth-app aan

> [!WARNING]
>
> Het `App`-object dat `apps.create` in de huidige `@whop/sdk` teruggeeft, bevat geen `client_secret`-veld. Kopieer de client secret in plaats daarvan via het tabblad Dashboard.

> [tab] API
>
> Gebruik het endpoint [Create App](https://docs.whop.com/nl/api-reference/apps/create-app.md) om programmatisch een OAuth-app aan te maken:
>
> ```typescript theme={null}
> import { WhopClient } from "@whop/sdk";
>
> const client = new WhopClient({ token: process.env.WHOP_API_KEY });
>
> const app = await client.apps.create({
>   name: "My App",
>   redirect_uris: [
>     "http://localhost:3000/api/auth/callback/whop",
>     "https://myapp.com/api/auth/callback/whop"
>   ],
> });
>
> console.log(app.id);            // NEXT_PUBLIC_WHOP_APP_ID
> console.log(app.client_secret); // WHOP_CLIENT_SECRET
> ```
>
> Werk redirect-URI's later bij met het endpoint [Update App](https://docs.whop.com/nl/api-reference/apps/update-app.md).

> [tab] Dashboard
>
> **1. Maak of selecteer je app**
>
> Ga naar het [Developer-dashboard](https://whop.com/dashboard/developer) en maak een nieuwe app aan of selecteer een bestaande.
>
> **2. Voeg redirect-URI's toe**
>
> Voeg in de OAuth-sectie elke redirect-URI toe die je wilt gebruiken (exacte overeenkomst vereist).
>
> **3. Kopieer de credentials**
>
> Kopieer je `client_id` (ziet eruit als `app_xxxxx`) en `client_secret`.
>
> **4. Selecteer je scopes**
>
> Bekijk je beschikbare OAuth-scopes via de knop "View available scopes" en selecteer alleen de scopes die je nodig hebt.

## Stap 2: Stuur gebruikers door om te autoriseren

Gebruik in je web- of mobiele client PKCE om gebruikers veilig door te sturen naar de OAuth-flow van Whop.

```typescript expandable theme={null}
const STORAGE_KEY = "whop_oauth_pkce";

function base64url(bytes: Uint8Array) {
	return btoa(String.fromCharCode(...bytes)).replace(
		/[+/=]/g,
		(c) => ({ "+": "-", "/": "_", "=": "" })[c]!,
	);
}

function randomString(len: number) {
	return base64url(crypto.getRandomValues(new Uint8Array(len)));
}

async function sha256(str: string) {
	return base64url(
		new Uint8Array(
			await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)),
		),
	);
}

async function startWhopOAuth(
	clientId: string,
	redirectUri: string,
	scope = "openid profile email",
	accountId?: string,
) {
	const pkce = {
		codeVerifier: randomString(32),
		state: randomString(16),
		nonce: randomString(16),
	};
	sessionStorage.setItem(STORAGE_KEY, JSON.stringify(pkce));

	const params = new URLSearchParams({
		response_type: "code",
		client_id: clientId,
		redirect_uri: redirectUri,
		scope,
		state: pkce.state,
		nonce: pkce.nonce,
		code_challenge: await sha256(pkce.codeVerifier),
		code_challenge_method: "S256",
		...(accountId && { company_id: accountId }),
	});

	window.location.href = `https://api.whop.com/oauth/authorize?${params}`;
}
```

Roep `startWhopOAuth` aan om de gebruiker door te sturen:

```typescript theme={null}
await startWhopOAuth(
	"app_xxxxxxxxx",
	"https://yourapp.com/oauth/callback",
	"openid profile email", // optionally specify more custom scopes here
	"biz_xxxxx", // optionally specify a scoped account id here
);
```

Als de gebruiker niet is ingelogd, vraagt Whop eerst om in te loggen en toont daarna het toestemmingsscherm.
Als de gebruiker je applicatie al heeft goedgekeurd voor de gevraagde scopes,
wordt hij automatisch teruggestuurd zonder twee keer te hoeven bevestigen.

> [!NOTE]
>
> Als je een account-ID meegeeft als `company_id`, worden tokens voor de gebruiker
> beperkt tot dat account. Je hebt dan alleen toegang tot de resources die de gebruiker
> op dat Whop-account kan beheren.

## Stap 3: Verwerk de callback en wissel de code in

Whop stuurt terug naar je `redirect_uri` met `code` en `state`. Gebruik deze functie om de state te verifiëren, de code in te wisselen voor tokens en credentials op te halen:

```typescript expandable theme={null}
const STORAGE_KEY = "whop_oauth_pkce";

interface WhopTokens {
	access_token: string;
	refresh_token: string;
	id_token?: string; // only present if "openid" scope was requested
	token_type: string;
	expires_in: number;
	obtained_at: number; // we add this client-side for refresh logic
}

async function handleWhopCallback(
	clientId: string,
	redirectUri: string,
): Promise<WhopTokens> {
	const params = new URLSearchParams(window.location.search);
	const [code, returnedState, error] = [
		params.get("code"),
		params.get("state"),
		params.get("error"),
	];
	if (error)
		throw new Error(
			`OAuth error: ${error} - ${params.get("error_description") || ""}`,
		);

	const stored = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || "null");
	sessionStorage.removeItem(STORAGE_KEY);
	if (!stored || returnedState !== stored.state)
		throw new Error("Invalid state - possible CSRF");

	const res = await fetch("https://api.whop.com/oauth/token", {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			grant_type: "authorization_code",
			code,
			redirect_uri: redirectUri,
			client_id: clientId,
			code_verifier: stored.codeVerifier,
		}),
	});

	if (!res.ok) {
		const err = await res.json().catch(() => ({}));
		throw new Error(
			`Token exchange failed: ${err.error_description || res.status}`,
		);
	}

	const tokens = await res.json();
	return { ...tokens, obtained_at: Date.now() };
}

function storeTokens(tokens: WhopTokens) {
	document.cookie = `whop_tokens=${encodeURIComponent(JSON.stringify(tokens))}; path=/; max-age=${60 * 60 * 24 * 30}; secure; samesite=strict`;
}

function getTokens(): WhopTokens | null {
	const match = document.cookie.match(/whop_tokens=([^;]+)/);
	return match ? JSON.parse(decodeURIComponent(match[1])) : null;
}

function clearTokens() {
	document.cookie = "whop_tokens=; path=/; max-age=0";
}
```

Op je callbackpagina:

```typescript theme={null}
const tokens = await handleWhopCallback(
	"app_xxxxxxxxx",
	"https://yourapp.com/oauth/callback",
);
storeTokens(tokens);
```

## Stap 4: Gebruik de tokens

Initialiseer de Whop SDK met het access token van de gebruiker:

```typescript theme={null}
import { WhopClient } from "@whop/sdk";

const tokens = getTokens();

const client = new WhopClient({
	token: tokens.access_token,
});
```

Bekijk de [API-referentie](https://docs.whop.com/nl/api-reference/overview.md) voor alle beschikbare endpoints.

## Stap 5: Tokens vernieuwen

Access tokens verlopen na 1 uur. Gebruik het refresh token om nieuwe credentials te krijgen:

```typescript expandable theme={null}
async function refreshTokens(
	clientId: string,
	accountId?: string,
): Promise<WhopTokens> {
	const tokens = getTokens();
	if (!tokens?.refresh_token) throw new Error("No refresh token available");

	const res = await fetch("https://api.whop.com/oauth/token", {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			grant_type: "refresh_token",
			refresh_token: tokens.refresh_token,
			client_id: clientId,
			...(accountId && { company_id: accountId }),
		}),
	});

	if (!res.ok) {
		const error = await res.json().catch(() => ({}));
		if (res.status === 401 || error.error === "invalid_grant") {
			clearTokens();
			throw new Error("Session expired - please log in again");
		}
		throw new Error(
			`Token refresh failed: ${error.error_description || res.status}`,
		);
	}

	const newTokens = await res.json();
	const stored = { ...newTokens, obtained_at: Date.now() };
	storeTokens(stored);
	return stored;
}

async function getValidAccessToken(clientId: string): Promise<string> {
	const tokens = getTokens();
	if (!tokens) throw new Error("Not logged in");

	const expiresAt = tokens.obtained_at + tokens.expires_in * 1000;
	const needsRefresh = Date.now() > expiresAt - 5 * 60 * 1000; // 5 min buffer

	if (needsRefresh) {
		const refreshed = await refreshTokens(clientId);
		return refreshed.access_token;
	}

	return tokens.access_token;
}
```

Gebruik:

```typescript theme={null}
const accessToken = await getValidAccessToken("app_xxxxxxxxx");
```

> [!NOTE]
>
> Refresh tokens roteren bij elk gebruik. Sla altijd de nieuwe tokens op die het
> refresh-endpoint teruggeeft. Als je tijdens de autorisatie `company_id` hebt meegegeven,
> moet je bij het vernieuwen dezelfde `company_id` meegeven.

## Stap 6: Userinfo en intrekken

### Gebruikersinformatie ophalen

Haal het profiel van de geauthenticeerde gebruiker op via het userinfo-endpoint:

```typescript theme={null}
interface WhopUserInfo {
	sub: string; // user tag (e.g. "user_xxxxx")
	name?: string; // requires "profile" scope
	preferred_username?: string; // requires "profile" scope
	picture?: string; // requires "profile" scope
	email?: string; // requires "email" scope
	email_verified?: boolean; // requires "email" scope
}

async function getUserInfo(accessToken: string): Promise<WhopUserInfo> {
	const res = await fetch("https://api.whop.com/oauth/userinfo", {
		headers: { Authorization: `Bearer ${accessToken}` },
	});
	if (!res.ok) throw new Error(`Failed to fetch user info: ${res.status}`);
	return res.json();
}
```

> [!NOTE]
>
> Welke velden worden teruggegeven, hangt af van de verleende scopes. `openid` is vereist,
> `profile` voegt naam/gebruikersnaam/afbeelding toe, `email` voegt e-mailvelden toe.

### Tokens intrekken bij uitloggen

Trek het refresh token van een gebruiker in wanneer die uitlogt. Access tokens verlopen na 1 uur en kunnen niet server-side worden ingetrokken.

```typescript theme={null}
async function logout(clientId: string) {
	const tokens = getTokens();
	if (tokens?.refresh_token) {
		await fetch("https://api.whop.com/oauth/revoke", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				token: tokens.refresh_token,
				client_id: clientId,
			}),
		});
	}
	clearTokens();
}
```

> [!WARNING]
>
> Trek tokens altijd in wanneer gebruikers uitloggen. Dit maakt het refresh token
> direct ongeldig en voorkomt ongeautoriseerde toegang, zelfs als het token is gecompromitteerd.

## Foutafhandeling

OAuth-fouten volgen het standaardformaat:

```json theme={null}
{
	"error": "invalid_grant",
	"error_description": "Authorization code has expired"
}
```

Veelvoorkomende foutcodes:

* `invalid_request`: ontbrekende of ongeldige parameter.
* `invalid_grant`: code of token verlopen of ingetrokken.
* `invalid_client`: onbekende `client_id`.
* `insufficient_scope`: token heeft niet de vereiste scope.
* `rate_limit_exceeded`: te veel requests (controleer de `Retry-After`-header).

## Volgende stappen

> [card] [API-referentie](https://docs.whop.com/nl/api-reference.md)
>
> Elk endpoint dat een verleend access token kan aanroepen.

> [card] [Betalingen accepteren](https://docs.whop.com/nl/developer/guides/accept-payments.md)
>
> Combineer inloggen met checkout voor complete aankoopflows.

> [card] [Luisteren naar webhooks](https://docs.whop.com/nl/developer/guides/webhooks.md)
>
> Reageer server-side op betalings-, lidmaatschaps- en entry-events.

> [card] [Machtigingen aanvragen](https://docs.whop.com/nl/developer/guides/permissions.md)
>
> Configureer de OAuth-scopes die je app daadwerkelijk nodig heeft.


## Related topics

- [Chatauthenticatie](https://docs.whop.com/nl/developer/guides/chat/authentication.md)
- [Chat-OAuth](https://docs.whop.com/nl/developer/guides/chat/oauth.md)
- [List OAuth Grants](https://docs.whop.com/nl/api-reference/users/list-oauth-grants.md)
