Skip to Content
Docs

Node.js

Call the Pay.com API from Node.js with typed methods, automatic paging, and webhook verification.

@pay-com/node has a typed method for each API operation, named after its resource: pay.charges.create(), pay.holds.capture(), and pay.valueLists.items.create(). Parameters and fields keep the API's own names, in snake_case.

Requirements and install

You need Node.js 20.19 or later. The package is for servers. It won't start in a browser, where anyone could read your secret key.

Terminal

npm install @pay-com/node

It works with import and require.

Set your key

Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:

Terminal

export PAY_COM_API_KEY='sk-pay-com-sandbox-…'

The SDK selects the sandbox or live environment automatically from the key prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written to the SDK's logs or errors.

Create your first charge

Charge a saved payment method. Amounts are integers in minor units (for example, 2000 is $20.00 USD):

charge.mjs

import { Pay } from '@pay-com/node';

const pay = new Pay();

const charge = await pay.charges.create({
  amount: 2000,
  currency: 'usd',
  source: 'pm_card_685125127054035968',
  reference: 'order-6735',
});

console.log(charge.id, charge.status);

The SDK sends a new idempotency key with each POST and DELETE, and the same one when it retries. To use your own, pass it after the parameters: pay.charges.create(params, { idempotencyKey }).

It retries twice by default after a network error, a timeout, 409 request_in_progress, 429, 502, 503, or 504. To decide yourself, pass { maxRetries: 0 }, and set a reference on payments to help you find out what was created.

The SDK retries these only after a 429, or when they never left your server: every PUT and PATCH, webhookEndpoints.create(), and networkTokens.retrieveCryptogram(). If one of these requests receives no response, check whether it succeeded before sending it again.

When you call paymentLinks.update(), pass every field you want to keep, amount and currency included. An update without amount sets the link's amount to 0.

List every item

A list method returns one page when you await it, and every item on every page when you loop over it:

list.mjs

import { Pay } from '@pay-com/node';

const pay = new Pay();

const page = await pay.charges.list({ limit: 10 });
console.log(page.data?.length, page.has_more);

for await (const charge of pay.charges.list({ 'created.greater_than': '2026-11-01T00:00:00Z' })) {
  console.log(charge.id);
}

To collect them, with a limit, use await pay.charges.list().toArray({ limit: 500 }). Lists that use page numbers work the same way.

Catch a decline

A decline throws PaymentMethodError:

decline.mjs

import { InvalidRequestError, Pay, PaymentMethodError } from '@pay-com/node';

const pay = new Pay();

try {
  await pay.charges.create({ amount: 2000, currency: 'usd', source: 'pm_card_685125127054035968' });
} catch (error) {
  if (error instanceof PaymentMethodError) {
    console.log('Declined:', error.declineCode);
  } else if (error instanceof InvalidRequestError) {
    console.log('Fix the request:', error.code, error.message);
  } else {
    throw error;
  }
}

Every error is a PayError, with type, code, statusCode, and the API's body as raw. Include requestId when contacting Pay.com support. It is empty when the API didn't get or couldn't read the request. After retries, cause holds an earlier attempt's error. The error's class tells you what happened:

Error classCause
PaymentMethodErrorPayment declined by the issuer or blocked by a risk rule (400)
InvalidRequestError400 or 422. NotFoundError, for 404, is one too
AuthenticationError401
PermissionError403
IdempotencyErrorAn idempotency key in use, or used for another request
ConflictErrorAny other 409
RateLimitError429
APIError5xx, a redirect (none is followed), or a response the SDK didn't expect
APIConnectionErrorNo complete response. APITimeoutError is one too

See Handle errors for what to do with each.

Verify a webhook

Pass the raw body, the Pay-Signature header, and the endpoint's whole signing secret. Cap the body, since anyone can send to your URL. Return HTTP 400 only when SignatureVerificationError is thrown. Let other errors return 500 so Pay.com retries delivery:

webhooks.mjs

import { createServer } from 'node:http';
import { Pay, SignatureVerificationError } from '@pay-com/node';

const secret = process.env.PAY_COM_WEBHOOK_SECRET;
if (!secret?.trim()) throw new Error('Set PAY_COM_WEBHOOK_SECRET');
const maxBytes = 5 * 1024 * 1024;

createServer(async (request, response) => {
  const chunks = [];
  let size = 0;
  try {
    for await (const chunk of request) {
      size += chunk.length;
      if (size > maxBytes) {
        response.writeHead(413).end();
        return;
      }
      chunks.push(chunk);
    }
  } catch {
    return; // The sender hung up.
  }

  let event;
  try {
    event = Pay.webhooks.constructEvent(Buffer.concat(chunks), request.headers['pay-signature'], secret);
  } catch (error) {
    if (error instanceof SignatureVerificationError) {
      response.writeHead(400).end();
    } else {
      console.error(error);
      response.writeHead(500).end();
    }
    return;
  }

  if (event.type === 'charge.succeeded') console.log('Paid:', event.data.id);
  response.writeHead(200).end();
}).listen(3000);

Skip events whose id you've already handled.

In a runtime without node:crypto, use constructEventAsync(). In your tests, pay.webhooks.generateTestHeaderString({ payload, secret }) makes a valid header.

Options

Pass these to new Pay().

apiKeystring
The secret key.

Default: PAY_COM_API_KEY

environmentstring
sandbox or live, for a key without either prefix.
merchantIdstring
Target merchant ID for multi-workspace API keys.
timeoutnumber
How long each attempt can take, in milliseconds, reading the response included.

Default: 60000

maxRetriesnumber
Maximum number of automatic retry attempts.

Default: 2

baseURLstring
Custom API base URL for local mocks or proxies.
logLevelstring
Log verbosity level (debug, info, warn, error, or off). Also read from PAY_COM_LOG.

Default: warn

merchantId, timeout, maxRetries, and idempotencyKey can also be set for one request, in the method's last argument. The sandbox's simulate endpoints are under pay.testHelpers. pay.documents.upload() takes a Blob with the file's type. See Upload and download files.

Was this page helpful?