Skip to Content
RunePayDocs

Node.js SDK

Use the first-party TypeScript client for checkout, payments, pagination and signed webhooks.

@runepay/node is RunePay's first-party TypeScript client for Node.js 18 and later. It wraps the merchant API reference with generated types, safe retries, pagination and webhook verification. Use it on your server.

Install from source

Version 0.1.0 is not published to the npm registry yet. The source lives at packages/node in the RunePay repository. If you have a checkout, build and pack that package, then install the archive into your application:

# From your RunePay checkout:
cd packages/node
yarn install --frozen-lockfile
yarn pack --filename runepay-node-0.1.0.tgz

# From your application directory, using the actual checkout path:
yarn add /absolute/path/to/runepay/packages/node/runepay-node-0.1.0.tgz

The package is ESM and includes TypeScript declarations. It uses Node's built-in fetch and has no runtime dependencies.

Initialise the client

Create a test API key (sk_test_…) and set RUNEPAY_KEY on your server. Switch to a live key (sk_live_…) after your account is approved. Test and live data are separate.

import RunePay from '@runepay/node';

const runepay = new RunePay({ apiKey: process.env.RUNEPAY_KEY });
// Or new RunePay(): reads RUNEPAY_KEY, then RUNEPAY_API_KEY.

A key is required. Never put secret keys in browser code. The default API URL is https://runepay.co/api/v1; pass baseUrl to use another server.

Create a checkout session

The Quickstart walks through the full payment flow. Amounts use the smallest currency unit: 1999 is $19.99.

const session = await runepay.checkoutSessions.create({
  line_items: [{
    price_data: {
      currency: 'usd',
      unit_amount: 1999,
      product_data: { name: 'Pro plan, 1 month' },
      tax_code: 'saas',
    },
    quantity: 1,
  }],
  client_reference_id: 'order_1042',
  success_url: 'https://merchant.example/thanks?session={CHECKOUT_SESSION_ID}',
}, { idempotencyKey: 'order_1042' });

// In a server route: redirect the buyer to session.url.
const response = Response.redirect(session.url, 303);

Fulfil the order from a verified checkout.session.completed webhook. The redirect alone does not confirm payment.

Idempotency, retries and errors

POST, PATCH and DELETE calls receive a unique Idempotency-Key automatically. The same key and body are reused on every retry of that call. Pass your order's stable idempotencyKey, as above, when you may repeat the operation across separate SDK calls.

The client retries 429 and 5xx responses twice by default, with exponential backoff starting at 500 ms and honoring Retry-After. deletePreviousSecret is not retried automatically, because the API ignores idempotency keys for that operation and a retry could retire a newer overlap secret. Configure the other defaults in the constructor:

const runepay = new RunePay({ maxRetries: 3, retryDelayMs: 1000 });

Request options also accept signal (an AbortSignal) and requestId (sent as Request-Id). API failures throw RunePayError with the HTTP status and available type, code, param, request_id, doc_url and object_id fields.

import { RunePayError } from '@runepay/node';

try {
  const payment = await runepay.payments.retrieve('pay_example');
  console.log(payment.status);
} catch (error) {
  if (error instanceof RunePayError) {
    console.error(error.status, error.code, error.request_id);
  }
  throw error;
}

List one page or iterate

list() returns a single API list object. autoPagingIterable() fetches subsequent pages lazily using starting_after, the last item id and has_more. Breaking the loop stops further requests.

const page = await runepay.payments.list({ limit: 20 });
console.log(page.data, page.has_more);

for await (const payment of runepay.payments.autoPagingIterable({ limit: 100 })) {
  console.log(payment.id);
}

The client covers checkout sessions, payments, refunds, disputes, payment links, balance, payouts, events and webhook endpoints. Nested lists use checkoutSessions.listLineItems() / lineItemsIterator() and webhookEndpoints.listDeliveries() / deliveriesIterator(). See the API reference for parameters and response fields.

Verify webhooks

Read the exact raw body before parsing JSON. constructEvent checks the RunePay-Signature header against the endpoint secret, accepts any matching v1 during rotation, enforces a five-minute timestamp tolerance, and returns the parsed event. Verification failures throw WebhookSignatureError.

This example uses a server route with the standard Request/Response API:

import { constructEvent, WebhookSignatureError } from '@runepay/node';

export async function POST(request: Request) {
  const secret = process.env.RUNEPAY_WEBHOOK_SECRET;
  if (!secret) throw new Error('RUNEPAY_WEBHOOK_SECRET is required');

  let event;
  try {
    event = constructEvent(
      new Uint8Array(await request.arrayBuffer()),
      request.headers.get('RunePay-Signature') ?? '',
      secret,
    );
  } catch (error) {
    if (error instanceof WebhookSignatureError) {
      return new Response('Invalid webhook', { status: 400 });
    }
    throw error;
  }

  // Durably store event, deduplicate on event.id, and queue fulfilment here.
  // A storage or queue failure should return a non-2xx response so RunePay retries.
  return new Response(null, { status: 200 });
}

You can also call runepay.webhooks.constructEvent(rawBody, header, secret). An optional fourth argument changes the timestamp tolerance in seconds; keep replay protection enabled in production. See Webhooks for endpoint setup, deduplication, delivery retries and rotation.