> Index of every page: https://docs.merchantservicedepot.com/llms.txt

# @myela/payments

> The typed server client for every Payments resource.

`@myela/payments` is the server client for the Payments API. Every resource sits under `myela.gateway`, every method is typed, and retries, idempotency keys, and webhook verification are built in. Keep it on your server: it takes your secret key.

## Install

The package needs Node 20 or later. It has no runtime dependencies and ships both ES modules and CommonJS.

```bash title="terminal"
npm install @myela/payments
```

`@myela/payments` and `@myela/elements` are proprietary. Anyone can install them from npm and read the code, but using them in production needs a written agreement with Myela.

## Configure the client

`apiKey` and `baseUrl` are both required. There is no default host, so a client can't reach the wrong environment because a variable was unset. Use `https://payments-api-sandbox.merchantservicedepot.com` with a test key. The live host comes with your live key.

```ts title="server.ts"
new Myela({
  apiKey: process.env.MYELA_API_KEY!, // required
  baseUrl: process.env.MYELA_API_BASE_URL!, // required
  signingSecret: process.env.MYELA_SIGNING_SECRET, // always pass it
  timeoutMs: 30_000, // default
  maxRetries: 2, // default; 5xx, 429, and network failures only
  appInfo: 'acme-store/1.4.0', // appended to the User-Agent
  fetch: customFetch, // for tests, or to route through a proxy agent
});
```

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `apiKey` | `string` | Required | Your secret key, sent as a bearer token. A missing key throws MyelaAuthenticationError when you construct the client. |
| `baseUrl` | `string` | Required | The API host. There is no default. A blank, relative, or non-http(s) value throws MyelaValidationError. A trailing slash is removed. |
| `signingSecret` | `string` | None | When set, the SDK adds a Myela-Signature header to every attempt. The SDK docs say to pass it unconditionally. |
| `timeoutMs` | `number` | 30000 | Timeout for each attempt, for every call this client makes. |
| `maxRetries` | `number` | 2 | Retries after the first attempt, so three attempts at most by default. |
| `fetch` | `typeof fetch` | globalThis.fetch | Swap in your own fetch, for tests or to route through a proxy agent. |
| `appInfo` | `string` | None | Appended to the User-Agent as myela-node/\<version\> (\<appInfo\>). |

The SDK reads no environment variables itself. The names in the examples, `MYELA_API_KEY`, `MYELA_API_BASE_URL`, and `MYELA_SIGNING_SECRET`, are a convention you wire up. For how live requests are signed, see [Authentication and request signing](https://docs.merchantservicedepot.com/docs/platform/authentication/).

### Per-call options

Every method takes an optional last argument:

| Field | Type | What it does |
| --- | --- | --- |
| `idempotencyKey` | `string` | Replaces the automatic key on a mutating call. |
| `signal` | `AbortSignal` | Cancels the call. A call you abort is never retried and throws MyelaConnectionError. |

Timeouts are set on the client only. There is no per-call timeout.

## Methods

The client has one namespace, `myela.gateway`, with a property per resource. Updates use `POST`, not `PATCH`. Deletes are named `del`, not `delete`. Amounts are integers in minor units everywhere.

### `myela.gateway.payments`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/payments` | Returns a Payment. |
| `retrieve(id)` | `GET /v1/payments/{id}` |  |
| `list(params?)` | `GET /v1/payments` | Filters: limit, startingAfter, customerId, days (1 to 365). |
| `capture(id, params?)` | `POST /v1/payments/{id}/capture` | Omit params to capture in full. |
| `void(id)` | `POST /v1/payments/{id}/void` |  |
| `refund(id, params?)` | `POST /v1/payments/{id}/refund` | Omit the amount to refund what's left. |

### `myela.gateway.customers`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/customers` |  |
| `retrieve(id)` | `GET /v1/customers/{id}` |  |
| `update(id, params)` | `POST /v1/customers/{id}` |  |
| `list(params?)` | `GET /v1/customers` | Filters: limit, startingAfter, q, externalId. |
| `del(id)` | `DELETE /v1/customers/{id}` |  |

### `myela.gateway.addresses`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/addresses` |  |
| `retrieve(id)` | `GET /v1/addresses/{id}` |  |
| `list({ customerId })` | `GET /v1/addresses` | customerId is required. Returns every address at once. |
| `update(id, params)` | `POST /v1/addresses/{id}` |  |
| `del(id)` | `DELETE /v1/addresses/{id}` |  |
| `setDefault(id, kind)` | `POST /v1/addresses/{id}/default` | kind is 'billing' or 'shipping'. |

### `myela.gateway.paymentMethods`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/payment_methods` |  |
| `retrieve(id)` | `GET /v1/payment_methods/{id}` | One saved card. 404 `STORED_CARD_NOT_FOUND` when deleted or not yours. |
| `list({ customerId })` | `GET /v1/payment_methods` |  |
| `del(id)` | `DELETE /v1/payment_methods/{id}` | The API reference lists this route as not enabled. |
| `setDefault(id)` | `POST /v1/payment_methods/{id}/default` |  |

### `myela.gateway.paymentLinks`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/payment_links` |  |
| `retrieve(id)` | `GET /v1/payment_links/{id}` |  |
| `list(params?)` | `GET /v1/payment_links` |  |
| `cancel(id)` | `POST /v1/payment_links/{id}/cancel` |  |

### `myela.gateway.plans`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/plans` |  |
| `retrieve(id)` | `GET /v1/plans/{id}` |  |
| `list(params?)` | `GET /v1/plans` |  |

### `myela.gateway.subscriptions`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/subscriptions` |  |
| `retrieve(id)` | `GET /v1/subscriptions/{id}` |  |
| `list(params?)` | `GET /v1/subscriptions` |  |
| `cancel(id)` | `POST /v1/subscriptions/{id}/cancel` |  |

### `myela.gateway.invoices`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/invoices` |  |
| `retrieve(id)` | `GET /v1/invoices/{id}` |  |
| `list(params?)` | `GET /v1/invoices` |  |
| `void(id)` | `POST /v1/invoices/{id}/void` |  |
| `schedule(id, params)` | `POST /v1/invoices/{id}/schedule` | Always check the result for a warning. |
| `cancelSchedule(id)` | `POST /v1/invoices/{id}/cancel_schedule` |  |
| `attempts(id)` | `GET /v1/invoices/{id}/attempts` | Returns every charge attempt at once. |

### `myela.gateway.recurringInvoices`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/recurring_invoices` |  |
| `retrieve(id)` | `GET /v1/recurring_invoices/{id}` |  |
| `list(params?)` | `GET /v1/recurring_invoices` |  |
| `update(id, params)` | `POST /v1/recurring_invoices/{id}` |  |
| `pause(id)` | `POST /v1/recurring_invoices/{id}/pause` |  |
| `resume(id)` | `POST /v1/recurring_invoices/{id}/resume` |  |
| `cancel(id)` | `POST /v1/recurring_invoices/{id}/cancel` | Safe to retry. Cancelling an already-cancelled schedule returns it. |

### `myela.gateway.webhookEndpoints`

| Method | Request | Notes |
| --- | --- | --- |
| `create(params)` | `POST /v1/webhook_endpoints` | The response carries the endpoint's secret. It is shown this one time. |
| `list()` | `GET /v1/webhook_endpoints` | No params. Returns every endpoint at once. |
| `retrieve(id)` | `GET /v1/webhook_endpoints/{id}` |  |
| `update(id, params)` | `POST /v1/webhook_endpoints/{id}` |  |
| `del(id)` | `DELETE /v1/webhook_endpoints/{id}` |  |

### `myela.gateway.webhookDeliveries`

| Method | Request | Notes |
| --- | --- | --- |
| `list(params?)` | `GET /v1/webhook_deliveries` | Filters: endpointId, status, limit, startingAfter. |
| `retrieve(id)` | `GET /v1/webhook_deliveries/{id}` |  |
| `replay(id)` | `POST /v1/webhook_deliveries/{id}/replay` |  |

### `myela.gateway.capabilities`

| Method | Request | Notes |
| --- | --- | --- |
| `list()` | `GET /v1/capabilities` | Returns a CapabilityMap. |
| `supports(capability)` |  | Returns a boolean: true only when the capability's status is active. |

Each capability on your account is in one of three states. `active` is callable now. `unavailable` is switched off but possible; contact Myela. `unsupported` is permanently unavailable on this account, so design it out rather than retrying. The map is partial, so index it with `?.`.

Bulk jobs have no method in this version. Their routes exist on the API, so call them over HTTP; see [Bulk jobs](https://docs.merchantservicedepot.com/docs/payments/bulk-jobs/). Checkout sessions and card tokens aren't on the server client either. They belong to [Elements](https://docs.merchantservicedepot.com/docs/sdks/elements/), in the browser.

## Retries

The SDK retries failures that might succeed on a second try, with a random backoff so many clients don't retry in lockstep. A `4xx` other than `429` fails the same way every time, so it is never retried.

| Aspect | Behavior |
| --- | --- |
| Retried | 429, any 5xx except 501, network failures, and client timeouts. |
| Not retried | Any other 4xx, 501, and calls you abort yourself. |
| Attempts | 1 + maxRetries. Three by default. |
| Backoff | Full jitter: a random wait up to 250 ms × 2^attempt, capped at 8 seconds. |
| Retry-After | Read into MyelaRateLimitError.retryAfter (seconds), but the built-in backoff doesn't use it. |
| Idempotency-Key | The same key on every attempt. |

A `MyelaTimeoutError` means the client gave up, not that nothing happened. The request may have been processed. Automatic retries apply to every mutating call, including void and refund, and the API doesn't accept an idempotency key on those two yet. If a void or refund fails in a way you can't read, retrieve the payment before you try again. More in [Capture, void, and refund](https://docs.merchantservicedepot.com/docs/payments/capture-void-refund/).

## Idempotency

Every non-GET request carries an `Idempotency-Key` automatically, a `myela_` prefix and a random UUID, and the same key goes out on every retry. A retry after a network failure returns the original result instead of charging twice. Pass your own key to make your own retries safe too:

```ts title="server.ts"
await myela.gateway.payments.create(params, { idempotencyKey: `order-${orderId}` });
```

Reusing a key with different parameters is the most common cause of a `MyelaConflictError`. More in [Idempotency and retries](https://docs.merchantservicedepot.com/docs/platform/idempotency/).

## Errors

Every error extends `MyelaError`. Branch on `code` and `detailCode`, never on `message`. A decline is not an error: it comes back as a `200` with `status: 'declined'`.

| Class | Status | code | Retryable |
| --- | --- | --- | --- |
| `MyelaValidationError` | 400, 422 | `invalid_request` | No |
| `MyelaAuthenticationError` | 401 | `authentication_failed` | No |
| `MyelaCapabilityError` | 403 | `capability_not_enabled` | No |
| `MyelaPermissionError` | 403 | `permission_denied` | No |
| `MyelaNotFoundError` | 404 | `not_found` | No |
| `MyelaConflictError` | 409 | `conflict` | No |
| `MyelaRateLimitError` | 429 | `rate_limited` | Yes |
| `MyelaCapabilityError` | 501 | `capability_not_supported` | No |
| `MyelaApiError` | 5xx | `api_error` | Yes |
| `MyelaConnectionError` | No response | `connection_failed` | Yes |
| `MyelaTimeoutError` | No response | `timeout` | Yes |

```ts title="server.ts"
import { MyelaError, MyelaCapabilityError } from '@myela/payments';

try {
  await myela.gateway.payments.refund(id, { amount: 500 });
} catch (err) {
  if (err instanceof MyelaCapabilityError && err.permanent) {
    // `unsupported` — never going to work on this account. Design it out.
  } else if (err instanceof MyelaCapabilityError) {
    // `unavailable` — switched off, but possible. Ask Myela to enable it.
  } else if (err instanceof MyelaError && err.retryable) {
    // Safe to retry — reuse the same idempotency key.
  }
}
```

Each error has `code`, `status`, `retryable`, `permanent` (the opposite of `retryable`), and, when the API sends one, `detailCode`. `MyelaRateLimitError` adds `retryAfter` in seconds, and `MyelaCapabilityError` adds `capability`; its `permanent` is true only for `capability_not_supported`. The list of detail codes is open, so handle ones you don't recognize. There is no request id and no per-field error map. The full list is in [Errors](https://docs.merchantservicedepot.com/docs/platform/errors/).

## Verify webhooks

`constructEvent` checks a delivery's signature and returns the parsed event. It uses Web Crypto, so it runs on Node, Bun, Deno, and edge runtimes. Pass it the raw body: parsing and re-serializing JSON changes the bytes the signature covers.

```ts title="webhooks.ts"
import express from 'express';
import { constructEvent } from '@myela/payments';

// The RAW body is required. The signature covers the exact bytes we sent, and
// JSON.parse -> JSON.stringify does not round-trip them.
app.post('/webhooks/myela', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = await constructEvent({
      payload: req.body,
      signature: req.header('Myela-Webhook-Signature')!,
      secret: process.env.MYELA_WEBHOOK_SECRET!,
    });
  } catch {
    return res.sendStatus(400);
  }

  res.sendStatus(200); // acknowledge FIRST, then work — slow handlers get retried

  // Dedupe on event.id — you WILL receive the same event twice.
  switch (event.type) {
    case 'invoice.paid':
      await markPaid(event.data);
      break;
  }
});
```

| Option | Type | What it is |
| --- | --- | --- |
| `payload` | `string \| Uint8Array` | The raw request body, exactly as received. |
| `signature` | `string` | The value of the Myela-Webhook-Signature header. |
| `secret` | `string` | The endpoint's secret (whsec_…), shown once when you create the endpoint. |
| `toleranceSeconds` | `number` | How old a delivery may be. Defaults to 300. 0 turns the check off, for tests only. |

Any failure, a missing or malformed header, a delivery outside the tolerance, or a signature that doesn't match, throws `MyelaValidationError`. The header can carry more than one signature while you rotate a secret, and any match passes. The event is `{ id, type, created, data }`, with `created` in Unix seconds.

`WebhookEventType` covers `invoice.paid`, `invoice.payment_failed`, `invoice.overdue`, `payment.settled`, and `payment.refunded`. The two payment events don't fire on every account yet. More in [Webhooks](https://docs.merchantservicedepot.com/docs/payments/webhooks/).

## Pagination

A `list()` call returns one page: `{ object: 'list', data, hasMore, nextCursor? }`. Pass `limit` (1 to 100, default 10) and `startingAfter`, the cursor from the previous page. The SDK has no auto-pagination helper, so loop until `nextCursor` is empty, and use `limit: 100` for large collections:

```ts title="server.ts"
let cursor: string | undefined;
do {
  // Spread rather than `startingAfter: cursor`: under
  // `exactOptionalPropertyTypes` an explicit `undefined` is not the same as an
  // absent key, and the first page has no cursor.
  const page = await myela.gateway.customers.list({
    limit: 100,
    ...(cursor ? { startingAfter: cursor } : {}),
  });
  handle(page.data);
  cursor = page.nextCursor;
} while (cursor);
```

A stale cursor returns `422` with `detailCode: 'UNKNOWN_CURSOR'`. `addresses.list()`, `invoices.attempts()`, and `webhookEndpoints.list()` return everything in one page. More in [Pagination](https://docs.merchantservicedepot.com/docs/platform/pagination/).

## Types

Every request and response type is exported from the package root, alongside the `Myela` class and the eleven error classes.

| Group | Types |
| --- | --- |
| Objects | Payment, Customer, Address, PaymentMethod, PaymentLink, Plan, Subscription, Invoice, RecurringInvoice, WebhookEndpoint, WebhookDelivery, and the rest of the response shapes. |
| Lists | Page\<T\> and ListParams. |
| Client | MyelaConfig, HttpConfig, RequestOptions. |
| Capabilities | Capability (a union of operation names), CapabilityMap, CapabilityState, CapabilityStatus. |
| Errors | MyelaErrorCode, MyelaDetailCode. |
| Webhooks | VerifyOptions, WebhookEvent\<T\>, WebhookEventType. |

Source: https://docs.merchantservicedepot.com/docs/sdks/node/
