npm.io
1.0.11 • Published 20h ago

@whop/sdk

Licence
Version
1.0.11
Deps
0
Size
11.4 MB
Vulns
0
Weekly
0
Stars
16

Whop TypeScript Library

fern shield npm shield

The Whop TypeScript library provides convenient access to the Whop APIs from TypeScript.

Table of Contents

Installation

npm i -s @whop/sdk

Reference

A full reference for this library is available here.

Usage

Instantiate and use the client with the following:

import { WhopClient } from "@whop/sdk";

const client = new WhopClient({ token: "YOUR_TOKEN", apiVersionDate: "2026-08-13", idempotencyKey: "YOUR_IDEMPOTENCY_KEY" });
await client.accessTokens.create();

Handling errors

When the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of APIError will be thrown:

const page = await client.payments.list({ company_id: 'biz_xxxxxxxxxxxxxx' }).catch(async (err) => {
  if (err instanceof Whop.APIError) {
    console.log(err.status); // 400
    console.log(err.name); // BadRequestError
    console.log(err.headers); // {server: 'nginx', ...}
  } else {
    throw err;
  }
});

Error codes are as follows:

Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
>=500 InternalServerError
N/A APIConnectionError
Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default.

You can use the maxRetries option to configure or disable this:

// Configure the default for all requests:
const client = new Whop({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.payments.list({ company_id: 'biz_xxxxxxxxxxxxxx' }, {
  maxRetries: 5,
});
Timeouts

Requests time out after 1 minute by default. You can configure this with a timeout option:

// Configure the default for all requests:
const client = new Whop({
  timeout: 20 * 1000, // 20 seconds (default is 1 minute)
});

// Override per-request:
await client.payments.list({ company_id: 'biz_xxxxxxxxxxxxxx' }, {
  timeout: 5 * 1000,
});

On timeout, an APIConnectionTimeoutError is thrown.

Note that requests which time out will be retried twice by default.

Auto-pagination

List methods in the Whop API are paginated. You can use the for await … of syntax to iterate through items across all pages:

async function fetchAllPaymentListResponses(params) {
  const allPaymentListResponses = [];
  // Automatically fetches more pages as needed.
  for await (const paymentListResponse of client.payments.list({
    company_id: 'biz_xxxxxxxxxxxxxx',
  })) {
    allPaymentListResponses.push(paymentListResponse);
  }
  return allPaymentListResponses;
}

Alternatively, you can request a single page at a time:

let page = await client.payments.list({ company_id: 'biz_xxxxxxxxxxxxxx' });
for (const paymentListResponse of page.data) {
  console.log(paymentListResponse);
}

// Convenience methods are provided for manually paginating:
while (page.hasNextPage()) {
  page = await page.getNextPage();
  // ...
}

Advanced Usage

Accessing raw Response data (e.g., headers)

The "raw" Response returned by fetch() can be accessed through the .asResponse() method on the APIPromise type that all methods return. This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.

You can also use the .withResponse() method to get the raw Response along with the parsed data. Unlike .asResponse() this method consumes the body, returning once it is parsed.

const client = new Whop();

const response = await client.payments.list({ company_id: 'biz_xxxxxxxxxxxxxx' }).asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object

const { data: page, response: raw } = await client.payments
  .list({ company_id: 'biz_xxxxxxxxxxxxxx' })
  .withResponse();
console.log(raw.headers.get('X-My-Header'));
for await (const paymentListResponse of page) {
  console.log(paymentListResponse.id);
}
Logging

All log messages are intended for debugging only. The format and content of log messages may change between releases.

Log levels

The log level can be configured in two ways:

  1. Via the WHOP_LOG environment variable
  2. Using the logLevel client option (overrides the environment variable if set)
import Whop from '@whop/sdk';

const client = new Whop({
  logLevel: 'debug', // Show all log messages
});

Available log levels, from most to least verbose:

  • 'debug' - Show debug messages, info, warnings, and errors
  • 'info' - Show info messages, warnings, and errors
  • 'warn' - Show warnings and errors (default)
  • 'error' - Show only errors
  • 'off' - Disable all logging

At the 'debug' level, all HTTP requests and responses are logged, including headers and bodies. Some authentication-related headers are redacted, but sensitive data in request and response bodies may still be visible.

Custom logger

By default, this library logs to globalThis.console. You can also provide a custom logger. Most logging libraries are supported, including pino, winston, bunyan, consola, signale, and @std/log. If your logger doesn't work, please open an issue.

When providing a custom logger, the logLevel option still controls which messages are emitted, messages below the configured level will not be sent to your logger.

import Whop from '@whop/sdk';
import pino from 'pino';

const logger = pino();

const client = new Whop({
  logger: logger.child({ name: 'Whop' }),
  logLevel: 'debug', // Send all messages to pino, allowing it to filter
});
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.get, client.post, and other HTTP verbs. Options on the client, such as retries, will be respected when making these requests.

await client.post('/some/path', {
  body: { some_prop: 'foo' },
  query: { some_query_arg: 'bar' },
});
Undocumented request params

To make requests using undocumented parameters, you may use // @ts-expect-error on the undocumented parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you send will be sent as-is.

client.payments.list({
  // ...
  // @ts-expect-error baz is not yet public
  baz: 'undocumented option',
});

For requests with the GET verb, any extra params will be in the query, all other requests will send the extra param in the body.

If you want to explicitly send an extra argument, you can do so with the query, body, and headers request options.

Undocumented response properties

To access undocumented response properties, you may access the response object with // @ts-expect-error on the response object, or cast the response object to the requisite type. Like the request params, we do not validate or strip extra properties from the response from the API.

Customizing the fetch client

By default, this library expects a global fetch function is defined.

If you want to use a different fetch function, you can either polyfill the global:

import fetch from 'my-fetch';

globalThis.fetch = fetch;

Or pass it to the client:

import Whop from '@whop/sdk';
import fetch from 'my-fetch';

const client = new Whop({ fetch });
Fetch options

If you want to set custom fetch options without overriding the fetch function, you can provide a fetchOptions object when instantiating the client or making a request. (Request-specific options override client options.)

import Whop from '@whop/sdk';

const client = new Whop({
  fetchOptions: {
    // `RequestInit` options
  },
});
Configuring proxies

To modify proxy behavior, you can provide custom fetchOptions that add runtime-specific proxy options to requests:

Node [docs]

import Whop from '@whop/sdk';
import * as undici from 'undici';

const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
const client = new Whop({
  fetchOptions: {
    dispatcher: proxyAgent,
  },
});

Bun [docs]

import Whop from '@whop/sdk';

const client = new Whop({
  fetchOptions: {
    proxy: 'http://localhost:8888',
  },
});

Deno [docs]

import Whop from 'npm:@whop/sdk';

const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
const client = new Whop({
  fetchOptions: {
    client: httpClient,
  },
});

Frequently Asked Questions

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Requirements

TypeScript >= 4.9 is supported.

The following runtimes are supported:

  • Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)
  • Node.js 20 LTS or later (non-EOL) versions.
  • Deno v1.28.0 or higher.
  • Bun 1.0 or later.
  • Cloudflare Workers.
  • Vercel Edge Runtime.
  • Jest 28 or greater with the "node" environment ("jsdom" is not supported at this time).
  • Nitro v2.6 or greater.

Note that React Native is not supported at this time.

If you are interested in other runtime environments, please open or upvote an issue on GitHub.

Environments

This SDK allows you to configure different environments for API requests.

import { WhopClient, WhopEnvironment } from "@whop/sdk";

const client = new WhopClient({
    environment: WhopEnvironment.Default,
});

Request and Response Types

The SDK exports all request and response types as TypeScript interfaces. Simply import them with the following namespace:

import { Whop } from "@whop/sdk";

const request: Whop.CreateAccessTokensRequest = {
    ...
};

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error will be thrown.

import { WhopError } from "@whop/sdk";

try {
    await client.accessTokens.create(...);
} catch (err) {
    if (err instanceof WhopError) {
        console.log(err.statusCode);
        console.log(err.message);
        console.log(err.body);
        console.log(err.rawResponse);
    }
}

Pagination

List endpoints are paginated. The SDK provides an iterator so that you can simply loop over the items:

import { WhopClient } from "@whop/sdk";

const client = new WhopClient({ token: "YOUR_TOKEN", apiVersionDate: "2026-08-13", idempotencyKey: "YOUR_IDEMPOTENCY_KEY" });
const pageableResponse = await client.accounts.list();
for await (const item of pageableResponse) {
    console.log(item);
}

// Or you can manually iterate page-by-page
let page = await client.accounts.list();
while (page.hasNextPage()) {
    page = page.getNextPage();
}

// You can also access the underlying response
const response = page.response;

Advanced

Subpackage Exports

This SDK supports direct imports of subpackage clients, which allows JavaScript bundlers to tree-shake and include only the imported subpackage code. This results in much smaller bundle sizes.

import { AccessTokensClient } from '@whop/sdk/accessTokens';

const client = new AccessTokensClient({...});
Additional Headers

If you would like to send additional headers as part of the request, use the headers request option.

import { WhopClient } from "@whop/sdk";

const client = new WhopClient({
    ...
    headers: {
        'X-Custom-Header': 'custom value'
    }
});

const response = await client.accessTokens.create(..., {
    headers: {
        'X-Custom-Header': 'custom value'
    }
});
Additional Query String Parameters

If you would like to send additional query string parameters as part of the request, use the queryParams request option.

const response = await client.accessTokens.create(..., {
    queryParams: {
        'customQueryParamKey': 'custom query param value'
    }
});
Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).

Which status codes are retried depends on the retryStatusCodes generator configuration:

legacy (current default): retries on

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (All server errors, including 500)

recommended: retries on

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 502 (Bad Gateway)
  • 503 (Service Unavailable)
  • 504 (Gateway Timeout)

Use the maxRetries request option to configure this behavior.

const response = await client.accessTokens.create(..., {
    maxRetries: 0 // override maxRetries at the request level
});
Timeouts

The SDK defaults to a 60 second timeout. Use the timeoutInSeconds option to configure this behavior.

const response = await client.accessTokens.create(..., {
    timeoutInSeconds: 30 // override timeout to 30s
});
Aborting Requests

The SDK allows users to abort requests at any point by passing in an abort signal.

const controller = new AbortController();
const response = await client.accessTokens.create(..., {
    abortSignal: controller.signal
});
controller.abort(); // aborts the request
Access Raw Response Data

The SDK provides access to raw response data, including headers, through the .withRawResponse() method. The .withRawResponse() method returns a promise that results to an object with a data and a rawResponse property.

const { data, rawResponse } = await client.accessTokens.create(...).withRawResponse();

console.log(data);
console.log(rawResponse.headers['X-My-Header']);
Logging

The SDK supports logging. You can configure the logger by passing in a logging object to the client options.

import { WhopClient, logging } from "@whop/sdk";

const client = new WhopClient({
    ...
    logging: {
        level: logging.LogLevel.Debug, // defaults to logging.LogLevel.Info
        logger: new logging.ConsoleLogger(), // defaults to ConsoleLogger
        silent: false, // defaults to true, set to false to enable logging
    }
});

The logging object can have the following properties:

  • level: The log level to use. Defaults to logging.LogLevel.Info.
  • logger: The logger to use. Defaults to a logging.ConsoleLogger.
  • silent: Whether to silence the logger. Defaults to true.

The level property can be one of the following values:

  • logging.LogLevel.Debug
  • logging.LogLevel.Info
  • logging.LogLevel.Warn
  • logging.LogLevel.Error

To provide a custom logger, you can pass in an object that implements the logging.ILogger interface.

Custom logger examples

Here's an example using the popular winston logging library.

import winston from 'winston';

const winstonLogger = winston.createLogger({...});

const logger: logging.ILogger = {
    debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
    info: (msg, ...args) => winstonLogger.info(msg, ...args),
    warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
    error: (msg, ...args) => winstonLogger.error(msg, ...args),
};

Here's an example using the popular pino logging library.

import pino from 'pino';

const pinoLogger = pino({...});

const logger: logging.ILogger = {
  debug: (msg, ...args) => pinoLogger.debug(args, msg),
  info: (msg, ...args) => pinoLogger.info(args, msg),
  warn: (msg, ...args) => pinoLogger.warn(args, msg),
  error: (msg, ...args) => pinoLogger.error(args, msg),
};
Custom Fetch

The SDK provides a low-level fetch method for making custom HTTP requests while still benefiting from SDK-level configuration like authentication, retries, timeouts, and logging. This is useful for calling API endpoints not yet supported in the SDK.

const response = await client.fetch("/v1/custom/endpoint", {
    method: "GET",
}, {
    timeoutInSeconds: 30,
    maxRetries: 3,
    headers: {
        "X-Custom-Header": "custom-value",
    },
});

const data = await response.json();
Runtime Compatibility

The SDK works in the following runtimes:

  • Node.js 18+
  • Vercel
  • Cloudflare Workers
  • Deno v1.25+
  • Bun 1.0+
  • React Native

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!