> For the complete documentation index, see [llms.txt](https://docs.loomgate.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.loomgate.io/en/integrations/node-server.md).

# Node.js server

Call the API and verify webhooks from a Node.js server with @loompay/loomgate-js-sdk/server.

`@loompay/loomgate-js-sdk/server` (Node.js ≥ 18) includes an API client that uses your secret key, and a webhook verification function.

```bash
pnpm add @loompay/loomgate-js-sdk
```

```js
import { createLoomgateServerClient, LoomgateApiError } from '@loompay/loomgate-js-sdk/server';

const loomgate = createLoomgateServerClient(process.env.LOOMGATE_SECRET_KEY, {
  apiBaseUrl: 'https://api.loomgate.io',
  timeoutMs: 60_000, // default
});
```

## Functions

Parameters and results keep the API's snake\_case JSON.

| Group                | Functions                                                                                                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `paymentIntents`     | `create(params, { idempotencyKey? })`, `retrieve(id)`, `update(id, params)`, `confirm(id, params)`, `release(id)`, `list({ limit?, starting_after?, order_reference? })` |
| `feeQuotes`          | `create({ amount, currency })`                                                                                                                                           |
| `refunds`            | `create({ payment_intent, amount?, reason? }, { idempotencyKey? })`, `retrieve(id)`                                                                                      |
| `balance`            | `retrieve()`                                                                                                                                                             |
| `webhookSigningKeys` | `list()`                                                                                                                                                                 |

```js
// Create a payment for order 1042
const intent = await loomgate.paymentIntents.create(
  {
    amount: 10000,
    currency: 'usd',
    items: [{ name: 'T-shirt', quantity: 2, unit_amount: 4500 }],
    shipping_amount: 1000,
    metadata: { order_id: '1042' },
  },
  { idempotencyKey: 'order-1042' },
);

// Before the buyer pays: add the buyer, order reference and shipping address
await loomgate.paymentIntents.update(intent.id, {
  order_reference: '1042',
  buyer: { name: 'Jane Doe' },
  shipping_details: {
    name: 'Jane Doe',
    address: { line1: '1 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US' },
  },
});

// Partial refund: one key per refund, stored before the call
const refund = await loomgate.refunds.create(
  { payment_intent: intent.id, amount: 2500, reason: 'requested_by_customer' },
  { idempotencyKey: 'refund-1042-1' },
);
```

## Errors

API errors are thrown as `LoomgateApiError` with `type`, `code`, `message`, `status` (HTTP; `0` when the server could not be reached), `param?`, `declineCode?`. The secret key never appears in the message.

```js
try {
  await loomgate.paymentIntents.confirm(id, { confirmation_token, billing_details });
} catch (err) {
  if (err instanceof LoomgateApiError && err.type === 'card_error') {
    await loomgate.paymentIntents.release(id); // let the buyer try another card
  }
  throw err;
}
```

## Timeouts

Each call is aborted after `timeoutMs` (default 60 seconds; `confirm` waits at least 180 seconds) and throws `api_error` / `request_timeout` with `status: 0`. The outcome is then **unknown**: read it back with `retrieve`, or send the request again with the same `idempotencyKey`. After a `confirm` timeout, don't release.

## Idempotency-Key

Pass `{ idempotencyKey }` to `paymentIntents.create` and `refunds.create`. The SDK only accepts keys of 1–255 printable ASCII characters with no leading or trailing whitespace; otherwise it rejects with `validation_error` without sending the request. See the Idempotency section of the [API reference](/en/api-reference.md).

## Verify webhooks

```js
import { verifyWebhook } from '@loompay/loomgate-js-sdk/server';

const result = verifyWebhook(rawBody, signatureHeader, {
  endpointId: 'we_…',
  publicKeys: { [kid]: publicKeyPem }, // from loomgate.webhookSigningKeys.list()
  toleranceSeconds: 300, // default
});
// { ok: true } | { ok: false, code }
```

See the full example in [Verify signatures](/en/webhooks/verify-signatures.md).

Every SDK request sends `User-Agent: loomgate-js-sdk/<version> (node/<version>)`.

## Example server

[`examples/js/worker/index.ts`](https://github.com/loomgroup/loomgate-examples/blob/main/examples/js/worker/index.ts) in the [loomgate-examples repository](https://github.com/loomgroup/loomgate-examples) is a small Hono server: it prices the cart, creates the payment with the server SDK and returns its `client_secret` to the browser, then reads the order status. It runs as a Cloudflare Worker and also runs on Node.js. Every example in the repository has a similar server part in `worker/index.ts`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.loomgate.io/en/integrations/node-server.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
