> ## Documentation Index
> Fetch the complete documentation index at: https://alguna.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Official TypeScript SDK for the Alguna Public API: installation, authentication, resources, pagination, and error handling.

`@alguna/sdk` is the official TypeScript client for the Alguna Public API. It exposes one typed method per endpoint — customers, products and plans, subscriptions and versions, usage events and metrics, credits and wallets, invoices, payments, checkout and portal sessions — with request and response types generated from the versioned OpenAPI spec. Use it from Node services where you would otherwise hand-write HTTP calls; it sets the `Authorization` and `Alguna-Version` headers, maps failed responses to typed errors, sends an idempotency key on writes that use one, and retries transient failures only when a retry is safe. The objects it manipulates are described in [How Alguna works](https://alguna.com/docs/concepts/how-alguna-works.md).

> [!NOTE]
>
> The SDK is server-side only. API keys are secret — never ship them to a browser. For embedding a purchase flow in your frontend, use [Embedded Checkout](https://alguna.com/docs/hosted/embedded-checkout.md) (`@alguna/checkout-sdk`) instead: your server mints the session with this SDK's API key, your frontend mounts it.

***

## How it works

1. **Create an API key** under **Settings → Connections → Developers → API Keys**. A key looks like `<key_id>.<key_secret>` and is a server secret.
2. **Instantiate the client** with the key. Every request it makes carries `Authorization: Bearer` and pins the API version via the `Alguna-Version` header.
3. **Call resources** (`alguna.customers`, `alguna.subscriptions`, …). Methods return typed response objects; failed requests throw typed errors.

## Installation

```bash theme={null}
npm install @alguna/sdk
# or
pnpm add @alguna/sdk
```

Requires Node.js 20 or later. The package is [`@alguna/sdk` on npm](https://www.npmjs.com/package/@alguna/sdk), and its source is [alguna-io/alguna-ts](https://github.com/alguna-io/alguna-ts) on GitHub.

```typescript theme={null}
import { Alguna } from "@alguna/sdk";

// Reads the API key from ALGUNA_API_KEY when you do not pass apiKey.
const alguna = new Alguna({
  apiVersion: "2026-04-01", // recommended — pin the version you integrate against
});
```

***

## Quick start: customer → subscription → portal session

```typescript theme={null}
// 1. Create a customer
const customer = await alguna.customers.create({
  name: "Acme Corp",
  currency: "USD",
  contacts: [{ email: "billing@acme.com", is_primary: true }],
});

// 2. Create a product and start a subscription
const product = await alguna.products.create({
  name: "Platform Fee",
  fee_type: "fixed",
  billing_frequency: "recurring",
  payment_terms: "advance",
});

const subscription = await alguna.subscriptions.create({
  customer_id: customer.id,
  currency: "USD",
  items: [
    {
      product_id: product.id,
      price: {
        type: "fixed",
        fee_type: "fixed",
        billing_direction: "advance",
        billing_frequency: "recurring",
        billing_interval: "monthly",
        fixed_pricing_model: { price_per_unit: "99.00", units: 1 },
      },
    },
  ],
  contract: { period_type: "fixed", duration_months: 12, start_date: "2026-07-01" },
  auto_activate: true,
});

// 3. Issue a one-off invoice
const invoice = await alguna.invoices.create({
  customer_id: customer.id,
  currency: "USD",
  line_items: [{ description: "Onboarding", unit_price: "500.00", quantity: "1" }],
});

// 4. Open a customer portal session so the customer can pay and manage billing
const session = await alguna.portal.createSession({ customer_id: customer.id });
console.log(session.url); // redirect the customer here; the session expires after 1 hour
```

> [!NOTE]
>
> Subscriptions are created in `draft` status. Pass `auto_activate: true` (as above) or call `alguna.subscriptions.activate(id)` when you are ready to go live. See [Creating a Subscription](https://alguna.com/docs/api-reference/examples/creating-a-subscription.md) for the full set of patterns — plans, overrides, and bundles all work the same way through the SDK.

***

## Resources

The SDK exposes one field per API resource. The client is generated from the versioned spec, so every public operation has a method. Highlights:

| Resource | Methods |
| - | - |
| `alguna.customers` | `create`, `get`, `list`, `update`, entitlements, connected accounts |
| `alguna.subscriptions` | `create`, `get`, `list`, `update`, `activate`, `cancel`, `delete`, credits, entitlements, revenue |
| `alguna.subscriptionVersions` | `create`, `get`, `list`, `publish`, `replace`, `delete` |
| `alguna.invoices` | `create`, `get`, `list`, `update`, `markAsPaid`, `void`, `generatePdf`, line items |
| `alguna.subscriptionChanges` | `create`, `preview` — the delta-based path for changing an active subscription |
| `alguna.portal` / `alguna.checkoutSessions` | `createSession` for the [customer portal](https://alguna.com/docs/hosted/customer-portal.md); `create`, `get` for [checkout sessions](https://alguna.com/docs/hosted/checkout.md) |
| `alguna.events` / `alguna.metrics` | `ingest` usage events; `create`, `get`, `list` [billable metrics](https://alguna.com/docs/billable-metrics/define-metrics.md) |
| `alguna.credits` / `alguna.wallets` / `alguna.walletGrants` | `check`, `track`, `getReservation`; wallet CRUD, `credit`, `debit`, `getBalance` — see [Credits & wallets](https://alguna.com/docs/credits/overview.md) |

Plus `products`, `plans`, `bundles`, `creditNotes`, `payments`, `refunds`, `integrations`, `insights`, `quotes`, `revenueSchedules`, `merchants`, `tags` and `tax`. Every method name follows the operation it wraps; the full list is in the generated [API reference](https://alguna.com/docs/api-reference/overview.md).

Request and response types are exported from the package root, and under the `AlgunaApi` namespace:

```typescript theme={null}
import type { CreateCustomerRequest, InvoiceResponse } from "@alguna/sdk";
```

Every method takes an optional last argument for per-request options: `idempotencyKey` (writes that accept one), `timeoutInSeconds`, `maxRetries`, `headers` and `abortSignal`.

## Pagination & filtering

List endpoints accept `limit`, `offset`, `sort` (in `field:order` format), and the same filter parameters as the [HTTP API](https://alguna.com/docs/api-reference/overview.md#filtering-and-sorting). They return a `Page`: `data` holds the items of the current page, and `response` holds the full response body, including `pagination`:

```typescript theme={null}
const page = await alguna.customers.list({ limit: 50, offset: 0, sort: "name:asc" });
page.data; // CustomerResponse[]
page.response.pagination; // { per_page, total_pages }
```

To walk every item, iterate the page. The SDK requests the next page as you go:

```typescript theme={null}
for await (const customer of await alguna.customers.list({ limit: 100 })) {
  console.log(customer.id);
}
```

The API sends at most the operation's `limit` maximum per page (100 for every list today). Iteration stops at the first page that holds fewer items than `limit`, or than that maximum when `limit` is larger. When the last page is exactly full, the SDK makes one more request, which returns an empty page. Use `page.hasNextPage()` and `page.getNextPage()` to page by hand.

## PDF downloads

`invoices.generatePdf`, `quotes.getPdf` and `subscriptions.downloadPdf` return a `BinaryResponse`. Read it with `arrayBuffer()`, `blob()` or `stream()`:

```typescript theme={null}
const pdf = await alguna.invoices.generatePdf(invoice.id);
await writeFile("invoice.pdf", Buffer.from(await pdf.arrayBuffer()));
```

***

## Error handling

Failed requests throw typed errors, all extending `AlgunaError`:

```typescript theme={null}
import { NotFoundError, RateLimitError, ValidationError } from "@alguna/sdk";

try {
  await alguna.customers.get("nope");
} catch (error) {
  if (error instanceof NotFoundError) {
    // error.message, error.statusCode, error.requestId
  } else if (error instanceof ValidationError) {
    // error.message — the API's explanation of what is wrong
  } else if (error instanceof RateLimitError) {
    // only the credit check/track endpoints send 429
  }
}
```

| Error | Status |
| - | - |
| `ValidationError` | 400 |
| `UnprocessableEntityError` | 422 (extends `ValidationError`) |
| `AuthenticationError` | 401 |
| `PermissionDeniedError` | 403 |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `RateLimitError` | 429 |
| `InternalServerError` | any 5xx |
| `ApiError` | any other status |
| `ConnectionError` | no response arrived |
| `TimeoutError` | the request timed out (extends `ConnectionError`) |
| `AbortError` | you aborted the request |

All errors expose `message` (the body's `detail`, else `title`, else `message`, else the HTTP status text), `statusCode`, `requestId` (the `X-Request-Id` of the failed response), `code` (when the body carries one), `body` and `headers`. Include the `requestId` when contacting support about a failed call. Status meanings and retry guidance are on the [Errors](https://alguna.com/docs/api-reference/errors.md) page.

***

## Idempotency and retries

Every request that is not a GET sends an `Idempotency-Key`: pass your own `idempotencyKey`, or the SDK generates a UUID v4 per call. The API then returns the original result instead of repeating the action (see [Idempotency](https://alguna.com/docs/api-reference/idempotency.md)). `events.ingest`, `credits.track` and `credits.check` are the exceptions. The events in the request body identify the work, so the SDK generates no key for these calls and sends only one that you pass (see [Writes identified by their events](https://alguna.com/docs/api-reference/idempotency.md#writes-identified-by-their-events)). Pass your own key when you retry a call yourself, for example after a restart:

```typescript theme={null}
await alguna.subscriptions.create(
  { customer_id: customer.id, plan_id: "plan_abc123", auto_activate: true },
  { idempotencyKey: "order_1234" },
);
```

The SDK retries a failed attempt 2 times by default (3 attempts in total) when:

* the status is `408`, `429`, `502`, `503` or `504`;
* the status is `409` with `Retry-After`. The API sends this only while a request with the same key is still running. A `409` without `Retry-After` is a real conflict and is not retried;
* no response arrived: the connection was refused, reset or closed, or the attempt timed out.

The SDK never retries after you abort a call through `abortSignal`. Between attempts it waits 1 s, then 2 s, with jitter. When the response has `Retry-After`, it waits that long instead, at most 60 s. Each retry reuses the call's key, so a retry never applies a write twice. `events.ingest`, `credits.track` and `credits.check` are retried without a key unless you pass one: the API identifies their events by `unique_id`, so a resent batch is applied once. Set `maxRetries` on the client or per call to change the count; `0` turns retries off.

Each attempt times out after 60 s. Set `timeout` (milliseconds) on the client or `timeoutInSeconds` per call. To limit a whole call, retries included, pass an `abortSignal`; when it aborts, the SDK throws `AbortError`.

***

## Configuration

```typescript theme={null}
const alguna = new Alguna({
  apiKey: "key_id.key_secret",           // optional — defaults to ALGUNA_API_KEY
  apiVersion: "2026-04-01",              // optional — defaults to the version this package was built for
  baseUrl: "https://api.alguna.io", // optional — the default
  timeout: 60_000,                       // optional — timeout of each attempt in ms
  maxRetries: 2,                         // optional — see Idempotency and retries
});
```

Pass `apiVersion` to pin the version your integration is written against. Without it, the SDK sends the version its types were generated from, so upgrading the package can move you to a newer API version — see [Versioning](https://alguna.com/docs/api-reference/overview.md#versioning).

***

## FAQ

**Can I use the SDK in the browser?**
No. It authenticates with your secret API key. For browser purchase flows, mint a checkout session server-side and mount it with [Embedded Checkout](https://alguna.com/docs/hosted/embedded-checkout.md).

**Does the SDK cover every endpoint?**
Yes. The client is generated from the versioned OpenAPI spec, so every operation in the [API reference](https://alguna.com/docs/api-reference/overview.md) has a method.

**Are there types for webhook payloads?**
Yes. `AlgunaWebhookEvent` is a union of every webhook body; narrow on `type` to get a typed `data`. The types come from the same spec as the [Webhooks](https://alguna.com/docs/api-reference/webhooks.md) page. The SDK does not verify signatures: before you trust a payload, verify its `svix-id`, `svix-timestamp` and `svix-signature` headers with the Svix library, as [Verifying signatures](https://alguna.com/docs/api-reference/webhooks.md#verifying-signatures) shows.

**Which version am I on, and how does it relate to the API version?**
Two different things, deliberately decoupled. The **package version** is the npm release of `@alguna/sdk` — read it from your lockfile, `npm ls @alguna/sdk`, or `npm view @alguna/sdk version` for the latest published. The **API version** is the date sent as `Alguna-Version`, and it is the only thing that decides request and response shapes. When you pass `apiVersion`, upgrading the package never moves you to a different API version: a newer SDK still speaks the date you pinned. When you do not, the SDK sends the version it was built for. Upgrade the package to pick up new endpoints, types and fixes; change `apiVersion` deliberately, as its own change, following [Versioning](https://alguna.com/docs/api-reference/overview.md#versioning).

**Is `@alguna/checkout-sdk` the same package?**
No. `@alguna/sdk` is the server-side API client; [`@alguna/checkout-sdk`](https://alguna.com/docs/hosted/embedded-checkout) is the browser package that mounts a checkout session in your page. They version independently and are installed separately.

**How do I point it at a sandbox or local environment?**
Pass `baseUrl` to use another host — for example the sandbox host `api.sandbox.alguna.io` with a sandbox API key. Everything else works identically. Sandbox and production are separate environments with separate keys; see [Base URLs](https://alguna.com/docs/api-reference/overview.md#base-urls).

**Is there an SDK for another language?**
Yes. There are [Python](https://alguna.com/docs/api-reference/sdks/python.md), [Go](https://alguna.com/docs/api-reference/sdks/go.md) and [Rust](https://alguna.com/docs/api-reference/sdks/rust.md) SDKs and an [`alguna` CLI](https://alguna.com/docs/api-reference/sdks/cli). They are generated from the same API spec as this SDK and behave the same way. See [SDKs and CLI](https://alguna.com/docs/api-reference/sdks/overview.md).

**What happens on rate limits?**
Only `credits.check` and `credits.track` get a `429`: the credit gate is busy, or the credit ledger has too many open holds. The SDK retries it twice, waiting for `Retry-After` when the response has one, then throws `RateLimitError`. Insufficient credit is not a `429`: those calls return `allowed: false`. See [Errors](https://alguna.com/docs/api-reference/errors.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.