Skip to content

About

Official VEXPay Node.js/TypeScript SDK (read-only mirror; npm: @vexpay/node)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

19 Commits

Folders and files

Repository files navigation

VEX Pay Node.js SDK

The official Node.js / TypeScript library for the VEX Pay API: accept Venezuelan payments (Pago Móvil C2P, cards, débito inmediato), pay out to merchants, create checkout sessions, and verify signed webhooks.

  • Fully typed from the VEX Pay OpenAPI contract
  • Safe retries: every POST carries an Idempotency-Key, so a retried charge never charges twice
  • Auto-pagination with for await
  • Webhook signature verification with replay protection
  • Zero runtime dependencies, Node.js 20+, ESM and CommonJS

Install

npm install @vexpay/node

Quickstart

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const quote = await vexpay.quotes.retrieve({ usdAmount: 25 });
console.log(`$25 = Bs ${quote.vesAmount} at BCV ${quote.bcvRate}`);

Keep your API key on the server. Use your test-mode key while you build; it runs against the sandbox provider.

Collect a Pago Móvil C2P payment

C2P is two steps: create an intent (the payer's bank sends them a token by SMS), then charge with the token your customer types in.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const intent = await vexpay.payments.c2p.request({
  usdAmount: 25,
  debtorId: 'V12345678',
  debtorCellPhone: '584141234567',
  debtorBankCode: 102,
  externalRef: 'order-1042',
});

// …the customer reads the token from their bank SMS…
const token = '123456';

const payment = await vexpay.payments.c2p.execute({
  intentId: intent.intentId,
  usdAmount: 25,
  debtorId: 'V12345678',
  debtorCellPhone: '584141234567',
  debtorBankCode: 102,
  token,
});

console.log(payment.status); // "COMPLETED" or "PENDING" — confirm with the payment.* webhook

Checkout sessions (hosted or embedded)

Let VEX Pay collect the payment details. Redirect the buyer to url, or embed the checkout on your own site with @vexpay/js and the one-time clientSecret.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const session = await vexpay.checkout.sessions.create({
  amountUsd: 25,
  reference: 'order-1042',
  description: 'Pedido #1042',
  allowedOrigins: ['https://shop.example'],
  successUrl: 'https://shop.example/gracias',
  metadata: { orderId: '1042' },
});

// Send session.clientSecret to the browser (never log or store it), or redirect:
console.log(session.url);

// Later — fulfil only after checking on the server:
const current = await vexpay.checkout.sessions.retrieve(session.id);
if (current.status === 'paid') {
  // ship order 1042
}

The hosted page lets the buyer pick the currency — bolívares, stablecoins or Colombian pesos — and offers every method your account accepts. Limit it with methods (c2p, vpos, usdt, usdc, cop).

USDT

USDT settles in USDT, into your VEX Pay USDT balance (never converted to VES). It must be enabled on your account — otherwise these calls fail with method_not_allowed (403). Pay-ins cost 2.5 % + 0.50 USDT; payouts cost the network fee listed by crypto.networks.list().

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

// Hosted USDT checkout: the buyer picks a network and gets a deposit address.
const session = await vexpay.checkout.sessions.create({
  amountUsd: 25,
  reference: 'order-1042',
  methods: ['usdt'],
  successUrl: 'https://shop.example/gracias',
});

// Or a static deposit address per customer — every deposit fires payment.completed with this customerRef.
const address = await vexpay.crypto.depositAddresses.create({ customerRef: 'user_123', network: 'BEP20' });

// Test key only: make a deposit "arrive" at that address (same payment, fee and webhook, livemode: false).
await vexpay.crypto.simulateDeposit({ customerRef: 'user_123', network: 'BEP20', amount: '40.00' });

const balance = await vexpay.crypto.balance.retrieve();
const networks = await vexpay.crypto.networks.list({ amountUsdt: '50.00' });

// Pay out from your USDT balance. Same idempotencyKey + same body replays the same payout.
const payout = await vexpay.crypto.payouts.create({
  network: 'POLYGON',
  address: '0x…',
  amountUsdt: '50.00',
  idempotencyKey: 'withdrawal-981',
});

USDT payment.completed events add amountUsdt, feeUsdt, network, txHashes and, for checkout sessions, checkoutSession.reference. Don't fulfil when underpaid is true — less than the order total arrived. Payouts end in payout.completed (with txHash) or payout.failed (amount and fee refunded).

USDC

USDC (Polygon and Base) uses the same calls with currency: 'USDC', has its own balance and must be enabled on your account separately. Without currency, every call stays in USDT.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const usdc = await vexpay.crypto.balance.retrieve({ currency: 'USDC' });
const balances = await vexpay.crypto.balances.list(); // USDT and USDC

await vexpay.crypto.payouts.create({
  currency: 'USDC',
  network: 'BASE',
  address: '0x…',
  amount: '50.00',
  idempotencyKey: 'withdrawal-982',
});

Responses and events include currency, amount and fee for both coins (amountUsdt / feeUsdt stay on USDT only). Credit your customer in the currency the webhook reports.

Convert VES or COP to USDT

Turn available VES or Colombian pesos into your USDT balance. A quote locks the rate (market USDT rate in that currency plus your spread) for 60 seconds; accepting it debits the source at once (conversion.created) and returns a PENDING conversion. VEX Pay then delivers the USDT and sends conversion.completed (or conversion.canceled, with the VES or COP returned). Conversions are on for every account that has USDT enabled (COP also needs COP enabled) — otherwise the calls fail with conversions_not_enabled (403). In test mode they complete immediately. COP amounts are whole pesos.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const quote = await vexpay.conversions.quotes.create({ sourceAmountVes: '10000.00' }); // or { targetAmountUsdt: '50.00' }
console.log(quote.rate, quote.targetAmountUsdt, quote.expiresAt);

const conversion = await vexpay.conversions.create(
  { quoteId: quote.id, reference: 'treasury-2026-10-03' },
  { idempotencyKey: 'convert-2026-10-03' },
);

for await (const c of vexpay.conversions.list({ status: 'PENDING' })) {
  console.log(c.id, c.sourceAmount, c.sourceCurrency, '→', c.targetAmountUsdt);
}
await vexpay.conversions.cancel(conversion.id); // only while PENDING

// Colombian pesos: same flow with sourceCurrency 'COP'.
const copQuote = await vexpay.conversions.quotes.create({ sourceCurrency: 'COP', sourceAmount: '1000000' });

// Auto-convert 50% of each completed COP payment (after the fee) to USDT; 0 turns it off.
await vexpay.conversions.settings.update({ autoConvert: { COP: { percent: 50 } } });

Colombian pesos (COP)

Collect pesos from buyers in Colombia through Bre-B, Nequi or Daviplata. Amounts are whole pesos, payments complete asynchronously (payment.completed / payment.failed), and completed payments go to your COP balance net of the COP fee. COP must be enabled on your account — otherwise the calls fail with method_not_allowed (403).

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

// What your account can use now (Bre-B, Nequi, Daviplata) and what each needs.
const { channels } = await vexpay.cop.channels();

// Bre-B: no buyer data. Show next.qrPngBase64 as an image and next.transferKey as text.
const breb = await vexpay.cop.payments.create(
  { amountCop: 100000, channel: 'breb', reference: 'order-1042' },
  { idempotencyKey: 'order-1042-cop' },
);

// Nequi: the buyer approves a push in the Nequi app.
await vexpay.cop.payments.create({
  amountCop: 50000,
  channel: 'nequi',
  buyer: { email: 'juan@example.com', phone: '3001234567', documentType: 'CC', documentNumber: '1234567890' },
});

// Daviplata: with next.type 'submit_otp' the buyer reads you the SMS code; submit it.
const davi = await vexpay.cop.payments.create({
  amountCop: 50000,
  channel: 'daviplata',
  buyer: { email: 'juan@example.com', phone: '3001234567', documentType: 'CC', documentNumber: '1234567890' },
});
await vexpay.cop.payments.submitOtp(davi.id, { otp: '123456' });

const status = (await vexpay.cop.payments.retrieve(breb.id)).status; // pending | completed | failed | canceled | refunded
const { availableCop } = await vexpay.cop.balance.retrieve();

cancel(id) cancels a pending payment and refund(id) refunds a completed one in full within 96 hours (a payment that can no longer be refunded through the API fails with refund_not_supported). A webhook for a COP payment has data.method === 'COP'; read it as CopPaymentWebhookData.

Test mode (test API keys use a sandbox):

Channel What to use Result
Bre-B No buyer data QR and key from the sandbox. Never send real money to them — sandbox keys are reachable from real banks and the money is not credited.
Nequi Phone 3991111111, any valid document and email Completes on its own within about a minute; 3992222222 is declined
Daviplata Same buyer data (CC, CE or TI only) With submit_otp, OTP 123456, 000000 or 111111 completes it; any other code fails with invalid_otp

Subscriptions

Bill a customer on a recurring USD price. Each period VEX Pay issues an invoice; with send_invoice (default) the customer pays it on a hosted page (hostedInvoiceUrl), with charge_automatically VEX Pay charges their domiciliación. Listen for invoice.paid, invoice.payment_failed and customer.subscription.* webhooks.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const customer = await vexpay.customers.create({ name: 'María Pérez', email: 'maria@example.com' });
const price = await vexpay.prices.create({
  product: 'prod_123',
  unitAmountUsd: 10,
  recurring: { interval: 'month' },
});

const subscription = await vexpay.subscriptions.create(
  { customer: customer.id, price: price.id, methods: ['c2p', 'pago_movil'] },
  { idempotencyKey: `sub-${customer.id}` },
);

for await (const invoice of vexpay.invoices.list({ subscription: subscription.id })) {
  console.log(invoice.number, invoice.status, invoice.amountDueUsd, invoice.hostedInvoiceUrl);
}

// Domiciliación: send the customer a setup link, then charge automatically.
const setup = await vexpay.setupSessions.create({ customer: customer.id });
console.log(setup.url);
for await (const method of vexpay.customers.paymentMethods.list(customer.id)) {
  console.log(method.id, method.status);
}

await vexpay.subscriptions.update(subscription.id, { cancelAtPeriodEnd: true });

subscriptions.cancel(id) cancels at once and voids its open invoices. On an open invoice, invoices.void(id), invoices.markUncollectible(id) (stays payable) and invoices.pay(id, { paidOutOfBand: true }) (paid outside VEX Pay; no money moves). paymentMethods.detach(id) stops a domiciliación from being charged again.

Testing card payments

With a test API key, VPOS test cards return a fixed outcome without reaching the bank: 4242424242424242 succeeds, 4000000000009995 is declined with G51 (insufficient funds), 4000000000000259 completes and is then charged back, and more. A decline fails exactly like a live one (422, the bank code in code and failureCode, a payment.failed webhook). With a live key these numbers are refused with 400 test_card_in_live_mode. Full list: test cards.

Webhooks

VEX Pay signs every delivery with a VexPay-Signature header. Verify it with the raw request body — parsing and re-serializing JSON changes the bytes and breaks the signature.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

// Any Fetch-style handler (Next.js route handlers, Remix, Hono, Workers, …)
export async function POST(request: Request): Promise<Response> {
  const rawBody = await request.text();
  try {
    const event = vexpay.webhooks.constructEvent(
      rawBody,
      request.headers.get('vexpay-signature'),
      process.env.VEXPAY_WEBHOOK_SECRET!,
    );

    if (event.event === 'payment.completed') {
      const { paymentId, externalRef, checkoutSession } = event.data;
      console.log('paid', paymentId, externalRef ?? checkoutSession?.reference);
    }
    return new Response(null, { status: 204 });
  } catch {
    return new Response('invalid signature', { status: 400 });
  }
}

With Express, mount express.raw({ type: 'application/json' }) on the webhook route and pass req.body (a Buffer) and req.headers['vexpay-signature'].

Deliveries older than 5 minutes are rejected as possible replays; pass { toleranceSeconds } to change that. Each delivery also carries a VexPay-Event-Id header you can use to deduplicate. In your own tests, sign fixtures with vexpay.webhooks.generateTestHeader({ payload, secret }).

Reconcile your balance

balance.transactions.list() returns every movement in your VES balance, newest first. The amounts always add up to ledgerNetVes, so you can rebuild your balance and find exactly which movement changed it. Card chargebacks arrive as payment.chargeback events whose ledgerEntryIds match these movements.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

let total = 0;
for await (const movement of vexpay.balance.transactions.list({ limit: 100 })) {
  total += Number(movement.amountVes); // e.g. type 'chargeback', amountVes '-4000.00'
}
const balance = await vexpay.balance.retrieve();
console.log(total.toFixed(2) === balance.ledgerNetVes);

// Only the movements of one payment (e.g. after a payment.chargeback event):
const page = await vexpay.balance.transactions.list({ paymentId: 'pay_…', type: ['chargeback', 'chargeback_fee'] });
console.log(page.items.map((m) => [m.type, m.amountVes]));

Top up your balance

Load your own Bs balance by Pago Móvil — for money that is not a sale (for example advertising income). Send the exact amountVes from payerPhone to the returned receiver before expiresAt (15 minutes); the top-up completes on its own when the transfer arrives, and its fee is charged then. The credit is held like any other credit unless you release it early with instant (for instantFeeVes). Each top-up needs a sourceNote and counts against your monthly limit (topup_cap_exceeded, 422, with remainingUsd/remainingVes in the error body). Top-ups are enabled per account (topups_not_enabled, 403). In balance movements they appear as topup, topup_fee, topup_instant_release and topup_instant_fee.

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const topup = await vexpay.balance.topups.create({
  amountVes: '100000.00',
  payerPhone: '04121234567',
  payerCedula: 'V12345678',
  sourceNote: 'Ingresos publicidad quincena 2',
});
console.log(topup.receiver, topup.expiresAt); // where and until when to send the Pago Móvil

const { data, monthRemainingUsd } = await vexpay.balance.topups.list({ limit: 20 });
console.log(data.length, monthRemainingUsd); // newest first, plus what is left of this month's limit (USD)
const latest = await vexpay.balance.topups.retrieve(topup.id);
if (latest.status === 'completed' && latest.heldVes !== '0.00') {
  await vexpay.balance.topups.instant(topup.id); // idempotent; `not_held` (409) when nothing is held
}
// Test mode only: await vexpay.balance.topups.simulate(topup.id);

Errors

Every error extends VexPayError and carries status, the API code (e.g. insufficient_balance), and the response body.

import VexPay, { VexPayConflictError, VexPayError, VexPayInvalidRequestError } from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

try {
  await vexpay.payouts.create({
    merchantId: '4f0c6f1e-2b7d-4c1a-9e3f-5a6b7c8d9e0f',
    monto: '1523.40',
    concepto: 'Liquidación semana 30',
    externalRef: 'po_2026_30_maria',
  });
} catch (error) {
  if (error instanceof VexPayInvalidRequestError && error.code === 'insufficient_balance') {
    // top up, then retry
  } else if (error instanceof VexPayConflictError) {
    console.error('externalRef reused with a different payload', error.body);
  } else if (error instanceof VexPayError) {
    console.error(error.status, error.code, error.message);
  } else {
    throw error;
  }
}
Class When
VexPayAuthenticationError 401 — missing or invalid API key
VexPayInvalidRequestError 400, 403, 410, 422 — fix the request
VexPayNotFoundError 404
VexPayConflictError 409 — e.g. external_ref_conflict, external_ref_already_paid (body paymentId), idempotency_key_reused
VexPayRateLimitError 429, after retries
VexPayAPIError 5xx, after retries
VexPayConnectionError / VexPayTimeoutError no HTTP answer, after retries
VexPaySignatureVerificationError a webhook did not verify

Retries and idempotency

The SDK retries connection errors, timeouts, 429, 5xx, and 409 idempotency_request_in_progress up to maxNetworkRetries times (default 2) with exponential backoff, honouring Retry-After. Every POST gets a random Idempotency-Key that stays the same across its retries, so VEX Pay executes it at most once. Supply your own key to make retries safe across process restarts too:

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!, { maxNetworkRetries: 3, timeoutMs: 20_000 });

await vexpay.payments.c2p.execute(
  {
    intentId: '00000000-0000-4000-8000-000000000001',
    usdAmount: 25,
    debtorId: 'V12345678',
    debtorCellPhone: '584141234567',
    debtorBankCode: 102,
    token: '123456',
  },
  { idempotencyKey: 'order-1042-charge' },
);

Seller balances

Credit a seller from your platform balance in bolívares, or in dollars converted at the official BCV rate, then read their movements and monthly statement:

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);
const merchantId = '00000000-0000-4000-8000-000000000002';

const balance = await vexpay.merchants.transfer(merchantId, { amountUsd: '100.00', transferKey: 'payroll-2026-11-u1' });
console.log(balance.pendingVes, balance.transfer.amountVes, balance.transfer.rate);

for await (const movement of vexpay.merchants.listTransactions(merchantId, { from: '2026-11-01T00:00:00Z' })) {
  console.log(movement.type, movement.amountVes);
}

const statement = await vexpay.merchants.retrieveStatement(merchantId, { month: '2026-11' });
console.log(statement.openingVes, statement.closingVes, statement.movements.length);

const csv = await vexpay.merchants.retrieveStatementCsv(merchantId, { month: '2026-11' });
console.log(csv.split('\n')[0]);

A transfer with amountUsd fails with rate_unavailable (503) when no BCV rate can be read; nothing is recorded.

Pagination

list() methods on payouts, merchants, products, customers, prices, subscriptions and invoices return the first page when awaited, and every item when iterated:

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!);

const firstPage = await vexpay.merchants.list({ limit: 100 });
console.log(firstPage.items.length, firstPage.nextCursor);

for await (const merchant of vexpay.merchants.list({ status: 'verified', isActive: 'true' })) {
  console.log(merchant.merchantId, merchant.name);
}

const recentPayouts = await vexpay.payouts.list({ limit: 50 }).autoPagingToArray({ limit: 200 });
console.log(recentPayouts.length);

Configuration

import VexPay from '@vexpay/node';

const vexpay = new VexPay(process.env.VEXPAY_API_KEY!, {
  baseUrl: 'http://localhost:3010', // default: https://api.vexpay.app
  timeoutMs: 30_000,
  maxNetworkRetries: 2,
});

console.log(await vexpay.banks.list());

TypeScript

Every request and response type is generated from the API contract:

import type { RequestBody, ResponseBody, Schemas } from '@vexpay/node';

type Receipt = Schemas['PaymentReceiptDto'];
type NewPayout = RequestBody<'Payouts_create'>;
type Session = ResponseBody<'CheckoutSessions_retrieve'>;

const describe = (receipt: Receipt) => `${receipt.paymentId}: ${receipt.status}`;
console.log(describe, {} as NewPayout, {} as Session);

Resources

Namespace Methods
banks list
quotes retrieve
balance retrieve
balance.transactions list
balance.topups create, list, retrieve, instant, simulate
payments retrieve, retrieveByRef, reverse
payments.c2p request, execute
payments.vpos create
payments.pagoMovil verify
payments.debit · credit · operations · dispersals · change débito/crédito inmediato and disbursements (advanced payments)
checkout.sessions create, retrieve
crypto simulateDeposit (Test mode only)
crypto.balance retrieve
crypto.balances list
crypto.depositAddresses create
crypto.networks list
crypto.payouts create, retrieve
conversions create, list, retrieve, cancel
conversions.quotes create
conversions.settings retrieve, update
cop.payments create, retrieve, submitOtp, cancel, refund
cop channels
cop.balance retrieve
merchants create, list, retrieve, retrieveByRef, update, delete, retrieveBalance, transfer, listTransactions, retrieveStatement, retrieveStatementCsv, listAuditEvents, startVerification, confirmVerification
merchants.payoutMethods list, create, setDefault, delete, startVerification, confirmVerification
payouts create, createInstant, createBatch, list, retrieve, retrieveByRef
products create, list, retrieve, update, delete, createLink, listLinks
paymentLinks retrieve, update, delete
tenantPayoutAccount retrieve, upsert, create, startVerification, confirmVerification
webhookEndpoints create, list, update, delete, sendTest
customers create, list, retrieve, update, delete
customers.paymentMethods list
prices create, list, retrieve, update
subscriptions create, list, retrieve, update, cancel
invoices list, retrieve, void, markUncollectible, pay
setupSessions create, retrieve
paymentMethods retrieve, detach
webhooks constructEvent, generateTestHeader (offline)

Full API reference: docs · OpenAPI: /openapi.json.

License

MIT

About

Official VEXPay Node.js/TypeScript SDK (read-only mirror; npm: @vexpay/node)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages