Skip to main content

@vonpay/checkout-node — Node.js SDK

Typed TypeScript/JavaScript client for the Von Payments Checkout API. Zero runtime dependencies, Node 20+.

Install​

npm install @vonpay/checkout-node

The package is an ES module. From 3.3.0, CommonJS code can load it with require("@vonpay/checkout-node") on Node 20.19+ or 22.12+, and gets the same module import returns. On older Node, use await import("@vonpay/checkout-node"). A TypeScript project that compiles to CommonJS needs "module": "nodenext" (TypeScript 5.8+), "module": "node20" (TypeScript 5.9+) or "moduleResolution": "bundler"; with "module": "node16" the type check reports TS1479 even though the code runs.

Pin the major you tested against: minor and patch releases are additive under semver, though a minor bump may add options or change defaults. A major bump is breaking and comes with an upgrade section: see Upgrading to 3.0.0.

Initialize​

import { VonPayCheckout, VonPayError } from "@vonpay/checkout-node";

// Simple — pass API key as a string
const vonpay = new VonPayCheckout("vp_sk_live_xxx");

// With options — pass a config object
const vonpay = new VonPayCheckout({
apiKey: "vp_sk_live_xxx",
apiVersion: "2026-04-14",
baseUrl: "https://checkout.vonpay.com", // default
maxRetries: 2, // default
timeout: 30_000, // ms, default
errorReporter: (err, ctx) => { // optional — see Error reporting below
Sentry.captureException(err, { extra: ctx });
},
});

The constructor validates the key prefix. A key must start with one of vp_sk_test_, vp_sk_live_, vp_pk_test_, or vp_pk_live_; passing a key that matches none of these throws immediately. A missing key (undefined, null or an empty string) throws Error("API key is required"). (Most server-side calls require a secret vp_sk_* key; see sessions.get below.)

What kind of key is this (4.7.0+). keyMode(key) answers "test", "live", "publishable_test", "publishable_live" or "unknown". heldAsLive(key) is true for a live secret key and for every "unknown" key. Use it to decide whether to ask a person before an action that moves money: a key whose prefix the SDK does not know is never treated as sandbox. Both read the prefix only, never call the API and never throw. Import them from @vonpay/checkout-node. isLiveKey(key) is unchanged: it is true for vp_sk_live_* only.

A live key is sent only to Von Payments (4.0.0+). With a vp_sk_live_* key the constructor throws a TypeError unless baseUrl is unset or https on checkout.vonpay.com or checkout-staging.vonpay.com. If you route API calls through your own proxy on purpose, pass allowCustomBaseUrl: true where you create the client. The environment variable VONPAY_ALLOW_CUSTOM_BASE_URL=1 on its own still works in 4.x, but from 4.5.0 it prints a one-time deprecation warning, and from 5.0.0 it is refused. An explicit allowCustomBaseUrl: false is never overridden by the environment variable. Test and publishable keys are never refused; an address other than Von Payments or this machine gets a one-time console.warn. keyDestinationProblem(apiKey, baseUrl) returns the same refusal as a sentence (or null) without creating a client, so you can check a deployment's configuration before it starts.


vonpay.sessions.create(params, options?)​

Create a checkout session and get a checkout URL.

const session = await vonpay.sessions.create({
amount: 1499, // in cents — required and >= 1 for mode "payment"
currency: "USD", // required, 3-letter code (uppercased)
successUrl: "https://mystore.com/order/123/confirm", // optional (HTTPS)
cancelUrl: "https://mystore.com/cart", // optional
country: "US", // optional, ISO 3166-1 alpha-2
mode: "payment", // optional, default "payment"
description: "Order #123", // optional
locale: "en", // optional
expiresIn: 1800, // optional, seconds (300–604800, max 7 days)
buyerId: "cust_abc", // optional — your STABLE per-user ID (not per-visit)
buyerName: "Jane Doe", // optional
buyerEmail: "jane@example.com", // optional
lineItems: [ // optional
{ name: "Widget", quantity: 1, unitAmount: 1499 },
],
metadata: { orderId: "order_123" }, // optional
}, {
idempotencyKey: "order_123_create", // optional request option
});

// session.id => "vp_cs_live_k7x9m2n4p3"
// session.checkoutUrl => "https://acme.vonpay.com/checkout?session=..."
// session.expiresAt => "2026-03-31T15:30:00.000Z"

From 3.5.0, buyerContact sends the buyer's phone, shippingAddress and billingAddress when you already have them, for example a sale your staff keys in. Every part is optional; addresses use the ShippingAddress shape (send state: "" where the country has none). Secret key only, never returned by sessions.get(), and personal data: send only what the buyer gave you and never log it. The session read also types nameCollection, emailCollection and channel.

amount is in minor units (cents): 1499 is $14.99. It is required and must be >= 1 for the default mode: "payment". currency is required and normalised to a 3-letter uppercase code. successUrl is optional; when present it must be a valid HTTPS URL. idempotencyKey is passed as the second-argument request option and sent as the Idempotency-Key header.

The live checkout URL is hosted on your merchant subdomain (for example https://acme.vonpay.com/checkout?session=...). expiresAt is an ISO-8601 timestamp string.

See Create a Session for the full parameter reference.

Embedded charge-and-save​

If the buyer completes payment through the embedded checkout (Embedded Fields) rather than the hosted page, the buyer fields above are what wire the session to vaulting:

  • A buyerId on the session is what a reusable vp_pmt_* is saved to. Without one, a card the buyer agrees to save goes to a buyer Von Payments creates for that checkout: in elements mode with or without a buyerEmail, in embed mode when the session carries a buyerEmail. An email never files the card under an existing buyer with that email. In embed mode a session with neither a buyerId nor a buyerEmail charges once and saves nothing, and a session that can save does so only with the buyer's agreement known when the form loads (vora.js 1.44.0 and later).
  • Under charge-and-save the embed charges on submit, so the server must not also call paymentIntents.create for that same session, or the buyer is charged twice.
  • The embed's client-side result is a UX signal only. Confirm settlement from the charge.succeeded webhook before fulfilling.

See Charge and save for the full embedded flow and the { token } | { charged: true } | { error } result shape.


vonpay.sessions.get(sessionId)​

Retrieve the full status of a session. Requires a secret key (vp_sk_*); a publishable key is rejected with HTTP 403 (auth_key_type_forbidden).

const status = await vonpay.sessions.get("vp_cs_live_k7x9m2n4p3");

// status.id => "vp_cs_live_k7x9m2n4p3"
// status.status => "succeeded"
// status.transactionId => "txn_abc123"
// status.amount => 1499
// status.currency => "USD"

Returns a full SessionStatus object including payment details and metadata. status.status is typed SessionState in the SDK, whose members are pending, processing, succeeded, failed, and expired. processing is a transient state during authorization, not a result: treat it as non-terminal and keep polling or wait for the webhook rather than branching on it as an outcome. On an expired session, expiredFrom: "processing" can later change to "failed" once the provider confirms an abandoned bank check authorized nothing, so a processing you read once is not final. The rules are on The session object.

From 3.6.0 the read also types these fields, in wire spelling like vp_tx_id:

  • retry: { allowed, attempts_remaining }, whether the session accepts another card after a decline (an elements or embed session whose card form is on your own page, on an account with retry enabled). It is the only place to learn this when the decline came after the bank's check. null when it does not apply.
  • last_payment_error: { code, decline_code } for the most recent declined attempt. code is card_declined or payment_failed (open enum); decline_code uses the payment intent's failure_code values, or null. From 3.9.0 it also carries action (for your server only: it reads hard for a card the bank flagged or one of your own rules), and buyer_message / buyer_action, the wording and advice that are safe to show the shopper.
  • amount_refunded, remaining_refundable and refundable: the refund totals, null together when they could not be read or the session has no single payment. null is not zero.

Each reads undefined from a server that does not send it, never a default.

From 4.5.0, last_payment_error.payment_intent_id is the payment intent (vpi_*) of the declined attempt it describes: pass it to paymentIntents.retrieve() to read that attempt in full. After more than one attempt it is the latest declined one. It is null when the decline was recorded without a payment intent. It is not the session's paymentIntentId, which names only a payment that took money. Keep it on your server, like code and decline_code.

From 4.1.0 the read also types vp_buyer_id: the buyer (vp_by_*) Von Payments created for this session, when a card saved on it for charges made while the shopper is away belongs to that buyer. It is null when you named the buyer with buyerId, or when the shopper's email identified one for a card saved without a payment, and always null on the sessions.update() and sessions.expire() answers. Treat undefined from an older server as null.

From 4.11.0 the read also types payment_method_card_check: whether an approved $0 card check stored the card in paymentMethod (how the check works).

  • { status: "approved", stored_credential_use }: a check stored the card.
  • null: the card was saved without a check, or it was checked before 13 November 2026 and what the check declared is not on record.
  • undefined: not read. paymentMethod is null, or the answer came from sessions.update() or sessions.expire(). Never read it as "no check".

The read returns this field as the API sent it. Treat an object with another status or stored_credential_use as not read.


vonpay.sessions.update(sessionId, params, options?)​

Change the total of an open, unpaid elements session, for example after the buyer picks a shipping option in the Apple Pay or Google Pay sheet, or add keys to its metadata, for example your order number once your store has created the order. Requires a secret key. Added in 2.11.0; metadata from 4.2.0. The rules are on Change an open session's total.

From 4.3.0, sessions.create() and sessions.update() take cardFormGroup, sent as card_form_group: the session's card-form group, which lets the buyer keep the card they typed when your checkout replaces its session. Derive it on your server, one value per shopper checkout, for example createHmac("sha256", serverKey).update(cartId).digest("base64url") with a key only your server holds. Never send it to the browser. It is write-once: sessions.update() can set it on an open session that has none, never change it.

import { SessionNotModifiableError } from "@vonpay/checkout-node";

try {
const session = await vonpay.sessions.update("vp_cs_live_k7x9m2n4p3", { amount: 5498 });
// session.amount => 5498
await vonpay.sessions.update("vp_cs_live_k7x9m2n4p3", { metadata: { order_id: "ORD-1234" } });
} catch (err) {
if (err instanceof SessionNotModifiableError) {
// Nothing was changed. err.reason is not_open | integration_mode |
// setup_session | store_order | in_page_bank_check; err.session has its state.
}
// err.code === "session_update_conflict" (409) is a different error and
// retryable: other changes kept landing, nothing was changed, the session is
// still open. Wait a moment and send the same update again.
throw err;
}

params takes amount (minor units), metadata, or both. metadata keys merge into the session's metadata: a sent key is added or replaced, and nothing is removed. currency (omit it to keep the session's currency) and lineItems (replaces the displayed line items) go only with amount. An update that sends none of amount, a non-empty metadata, cardFormGroup, recurring or the buyer fields below throws a TypeError before anything is sent. From 4.13.0, a restricted key with charge limits cannot set a total over them: the call throws VonPayError with code api_key_limit_exceeded (limit per_session or daily_total) and nothing changes (limits). It resolves with the updated session. Both changes are idempotent on their own, so idempotencyKey is optional.

Name a guest (4.9.0+). When you learn the shopper's email after the page opened, send buyerEmail, setupForFutureUse: "on_session" or storedCredentialUse: "unscheduled". Any one may be sent alone. Send them in a request of their own: with amount, metadata, cardFormGroup or recurring, the API answers 400 validation_error and changes nothing. If the email changes, send it again: the last value wins. The card field does not need rebuilding.

await vonpay.sessions.update("vp_cs_live_k7x9m2n4p3", {
buyerEmail: "jane@example.com",
setupForFutureUse: "on_session",
});

This works only on an integrationMode: "elements" payment session with chargeAtSubmit: true, no buyerId, no recurring, no connected-store order and no cardFormGroup, before any payment is attempted. Otherwise it throws SessionNotModifiableError, which you can ignore: the payment goes ahead on what the session holds, and the card is not saved. Its new reason values are customer_named, subscription_signup, forwarded_gateway, card_form_group and payment_attempted.

Name the customer (4.13.0+). When the shopper creates or signs in to an account after the page opened, send buyerId, your own customer reference, alone or with the guest fields. It works on the same sessions as naming a guest, and only once: a session that already names a customer refuses a different buyerId with reason: "customer_named". buyerId alone does not keep the card: that needs reuse consent, as on a session created with buyerId. A session created with storedCredentialUse "recurring" or "installment" refuses buyer details that would change that declaration, with reason: "stored_credential_declared". The rules are on Name the customer.

await vonpay.sessions.update("vp_cs_live_k7x9m2n4p3", { buyerId: "cust_1042" });

vonpay.sessions.expire(sessionId, options?)​

Close an open, unpaid session so no payment can start on it afterwards. Call it before taking payment for the same order another way. Requires a secret key. Resolves with the closed session; any other state throws SessionNotExpirableError with the session's state, and nothing changes. The rules, including the one exception on embed sessions, are on Close a session so you can charge another way.

import { SessionNotExpirableError } from "@vonpay/checkout-node";

try {
await vonpay.sessions.expire("vp_cs_live_k7x9m2n4p3");
// Closed: now take payment another way.
} catch (err) {
if (err instanceof SessionNotExpirableError && err.reason === "recent_activity") {
// A declined session that changed recently: call expire() again after
// err.retryAfterSeconds and it closes. The SDK never repeats the call itself.
} else if (err instanceof SessionNotExpirableError) {
// Nothing changed, and a payment may exist on it. Do not charge another way.
}
throw err;
}

From 3.5.0 the error carries reason: "recent_activity" (call again after retryAfterSeconds), "payment_may_be_in_flight", or "unknown" for a value the SDK does not recognise, which you handle like "payment_may_be_in_flight". It is undefined when the API sent none. rawReason keeps the value as sent. A closed session's expiredFrom can be "failed" (a declined session closed this way), and like "pending" nothing can start on it afterwards.


vonpay.paymentIntents.retrieve(paymentIntentId)​

Read a payment intent's stored state (maps to GET /v1/payment_intents/{id}). Added in 2.7.0. Requires a secret key; a publishable key is rejected 403.

const intent = await vonpay.paymentIntents.retrieve("vpi_live_9f2nd4kq7x1m");

// intent.status => "succeeded"
// intent.amount => 1499

This is how you confirm a payment on a 3-D Secure return page. Pass the id you stored when you created the intent, never one read out of the return URL, which anyone can forge. Fulfill only on status === "succeeded": authorized is a hold, and captured is still pending at the processor.

From 3.6.0 the read also types:

  • avsResultCode and cvvResultCode: the address and security-code results for the payment. null when nothing was checked or no result came back. "unavailable" and "not_supported" (address) or "not_provided" and "unavailable" (security code) mean the check did not run, not that it failed. This server read is where a payment taken in the browser gets its result, because the browser never receives it. Keep the values on your server.
  • amountRefunded, remainingRefundable and refundable: the refund totals. All three are null together when the totals could not be read at that moment, and null is not zero: read again or call refunds.list(). refundable is false until the charge settles.
  • nextAction while the payment is requires_action, with issuedAt on the same object (beside redirectToUrl, not inside it) saying when the challenge link was issued. If your server lost the create response, send the buyer to the link from here; check issuedAt first, since the payment provider decides how long a link stays usable. See 3-D Secure.

From 3.7.0, this read and the create, capture and void responses also type networkTransactionId: the card network's own identifier for the charge (Visa's Transaction Identifier, Mastercard's trace id). Store it exactly as received if you keep your own records of stored cards; never parse it. null means not reported yet, not "none": some connections report it only once the payment settles, so read the payment again later. It is always null for payment methods other than cards. The charge.succeeded and payment_intent.succeeded webhooks carry the same value as data.network_transaction_id.

From 3.8.0, the read also types declineCode, action, declineMessage and ruleCode. They are filled when status is failed, with the same values as the create response and the charge.failed webhook, and null on any other status. Branch retry logic on action, not declineCode. When declineCode is blocked_by_rule, one of your own rules refused the payment: do not pass declineCode, declineMessage or ruleCode to the buyer's browser.

const pi = await vonpay.paymentIntents.retrieve(storedIntentId);
if (pi.cvvResultCode === "no_match") {
// a real mismatch
}

From 4.9.0 the read also types:

  • lateMoneyOutcome (type LateMoneyOutcome from 4.13.0): what happened to money that arrived after the payment read failed, cancelled or voided. Given back automatically: reversed (given back: refunded, or the hold released), reversing (in progress) and reverse_failed (not given back yet, and the Von Payments team finishes it: do not refund it yourself). Given back by hand: manual_refund_pending (not given back yet; our team contacts you, or refund it by its settlement row), manually_refunded (recorded as given back) and kept_by_merchant (you kept it). null (4.13.0) means no late money arrived, or the records could not be read just then: read the payment again. The field is absent only from a server from before checkout's 18 November 2026 release, and there an absent field does not prove that no late money arrived. Treat a value you do not know as not given back yet. status does not change. See the payment read for each value. It is not on list items, and the capture() and void() answers do not read it: call retrieve().
  • attempts: every time the payment was sent to one of your connections, in order (PaymentIntentAttempt: attempt, processorConnection, result, declineCode, processorResponse, outcome, networkAdvice, networkAdviceRetryAfterMs, createdAt). The last item is the connection that decided the payment. An empty list means no connection was tried.
  • attemptsStatus: complete, pending or unavailable. Count attempts only when it is complete. On pending the list is null: read again in a few minutes. On unavailable no record is held, and attempts is null. Payments made before 2 November 2026 read this way. To count approvals and declines per connection, group the items by processorConnection.id.
  • processorResponse: { code, description }, the card processor's own answer to a declined charge. null when it was not recorded, and on a payment that is not failed. The server cuts description to 200 characters and masks it: a long number reads [REDACTED_NUMBER], and a value the processor repeated back reads [REDACTED_VALUE]. Use declineCode to decide what to do. Use this field to match the processor's own reports. description is untrusted text: read it on your server, escape it where you display it, never show it to the buyer, and keep it out of an AI model's prompt.
  • card: { brand, last4, bin } from Von Payments' own records. bin is the card's first six digits. Each field is null when not known. The full card number is never returned.
const read = await vonpay.paymentIntents.retrieve(storedIntentId);
if (read.attemptsStatus === "complete" && read.attempts) {
for (const a of read.attempts) console.log(a.processorConnection?.id, a.result, a.declineCode);
}

On the create(), capture() and void() answers, card is now complete (brand and last4 both read) or null when checkout could not read the card. The capture() and void() answers also carry card.bin, processorResponse, attempts and attemptsStatus. The create() answer carries none of them.


vonpay.paymentIntents.list(), listPages(), listAutoPaging() and summary()​

From 4.5.0. These read payment reports. Use a restricted key with only payment_intents.read.

// Every bank decline in October, one request at a time
for await (const pi of vonpay.paymentIntents.listAutoPaging({
createdGte: "2026-10-01T00:00:00Z",
createdLt: "2026-11-01T00:00:00Z",
outcome: ["bank_declined"],
maxItems: 5000,
})) {
console.log(pi.id, pi.declineCode, pi.card.brand);
}

// Or whole pages, keeping each cursor so you can resume within 24 hours
for await (const page of vonpay.paymentIntents.listPages({ outcome: ["bank_declined"] })) {
console.log(page.data.length, page.nextCursor);
}

const summary = await vonpay.paymentIntents.summary({
createdGte: "2026-10-01T00:00:00Z",
groupBy: ["day"],
timeZone: "America/New_York",
});
console.log(summary.totals.rates.approvalRate); // null, not 0, when there was no traffic
  • list() returns one page. To read on, call it again with the same filters and window and startingAfter: page.nextCursor. The cursor lasts 24 hours and works only with the request it came from.
  • listPages() yields whole pages, each with its nextCursor, so you can resume within 24 hours. listAutoPaging() yields one item at a time and stops after maxItems. Both send one request at a time.
  • summary() returns counts, amounts and rates. generatedAt says when the figures were computed, and ageSeconds how old they are: a summary is cached for 45 seconds.
  • A refused filter throws VonPayError with param naming it. A report that is too big throws report_too_large, with maxGroups or timeoutMs saying which limit. Narrow it rather than retry.
  • From 4.9.0 each item also carries attempts, attemptsStatus, processorResponse and card.bin, with the same rules as the read. An item never carries lateMoneyOutcome.

vonpay.securityCodeSessions.create(params)​

Open a session for the buyer to re-type a saved card's security code (maps to POST /v1/security_code_sessions). Added in 3.7.0. Requires a secret key. Hand id to the browser's vora.securityCode() field; once its submit() resolves, charge with securityCodeSession:

const scs = await vonpay.securityCodeSessions.create({
paymentMethod: { id: "vp_pmt_test_QAqnXEJF_TCum1jg" },
buyerId: "buyer_123",
});
// scs.id => "vp_scs_test_…", scs.card => { brand: "visa", last4: "4242" }

// after the browser field's submit() resolves:
const intent = await vonpay.paymentIntents.create(
{
amount: 1499,
currency: "USD",
paymentMethod: { id: "vp_pmt_test_QAqnXEJF_TCum1jg" },
securityCodeSession: scs.id,
buyerId: "buyer_123",
returnUrl: "https://your-store.example.com/checkout/return",
},
{ idempotencyKey: "ord_42_create" },
);

A session lasts 15 minutes and pays for one charge attempt, whatever the outcome; a 422 security_code_not_collected refusal does not use it up, so send the same request again once the buyer submits. It takes no idempotencyKey: a repeated call opens a second session, which counts toward the limit of 10 per saved card per hour. The refusals are on the guide.


vonpay.refunds.list(target, page?)​

The refunds of one payment, plus its refund totals (maps to GET /v1/refunds). Added in 3.6.0. Requires a secret key. It never moves money and is retried like any other read.

const page = await vonpay.refunds.list(
{ transaction: session.vp_tx_id! }, // or { paymentIntent: "vpi_..." }, exactly one
{ limit: 25, startingAfter: cursor },
);

page.data; // newest first, every status
page.amountRefunded; // succeeded + still in progress, across all pages
page.remainingRefundable; // what a refund with no amount would refund now
page.refundable; // false until the charge settles, and when disputed or fully refunded
page.nextCursor; // pass back as startingAfter while hasMore; null on the last page

Name the payment with exactly one of paymentIntent or transaction: both or neither is a compile error, and a TypeError before any request. Refunds made through either id are listed whichever one you ask with. Check each refund's own status, since a requested refund is still in progress and can still fail. Each listed refund carries idempotencyKey (the key you sent, or null) and createdAt. There is no auto-paging helper: loop on nextCursor. A duplicate-record transaction throws 422 refund_target_is_duplicate with refundInstead, as on refunds.create(). The fields are on List a payment's refunds.

A refunds.create() answer now types idempotent: true when it replays an earlier request with the same idempotencyKey, so no new refund was issued.


vonpay.sessions.validate(params)​

Dry-run validation of session parameters without creating a session (maps to POST /v1/sessions?dry_run=true). Returns validation results.

const result = await vonpay.sessions.validate({
amount: 1499,
currency: "USD",
successUrl: "https://mystore.com/confirm",
});

// result.valid => true
// result.warnings => ["cancelUrl is recommended for production"]

vonpay.webhooks.verifySignature(payload, signature, secret)​

Verify an incoming webhook's HMAC-SHA256 signature. Uses crypto.timingSafeEqual to prevent timing attacks. Returns a boolean for every delivery. Prefer constructEvent for typed event parsing.

A secret that cannot be right throws (4.7.0+). verifySignature and constructEvent throw a TypeError before they verify anything when secret is missing, empty, only whitespace or not a string; is an example value from our samples and docs, such as whsec_your_endpoint_signing_secret; or is a Von Payments API key. This is a setup mistake, not a bad delivery, so do not answer it with a 401. Pass your endpoint's whsec_* signing secret. A real secret is not checked for its format.

const isValid = vonpay.webhooks.verifySignature(
req.body, // raw request body (Buffer or string)
req.headers["x-vonpay-signature"] as string, // signature header (t=…,v1=…)
process.env.VON_PAY_WEBHOOK_SECRET, // whsec_* — per-endpoint secret
);

vonpay.webhooks.constructEvent(payload, signature, secret)​

Verify the signature, enforce the asymmetric replay window (5 min past / 30 sec future), and parse the webhook payload into a typed event. Takes 3 arguments. On a malformed header, a stale timestamp, or an HMAC mismatch it throws a VonPayError with code webhook_invalid_signature and HTTP status 401. An unusable secret throws a TypeError instead (above).

import express from "express";

const endpointSecret = process.env.VON_PAY_WEBHOOK_SECRET; // whsec_*

app.post("/webhooks/vonpay", express.raw({ type: "application/json" }), (req, res) => {
// 1. Verify. Only a bad signature answers 400.
let event;
try {
event = vonpay.webhooks.constructEvent(
req.body, // raw body (Buffer)
req.headers["x-vonpay-signature"] as string, // signature header (t=…,v1=…)
endpointSecret, // whsec_* — per-endpoint secret
);
} catch (err) {
console.error("webhook verification failed:", (err as Error).message);
res.status(400).json({ error: "Invalid signature" });
return;
}

// 2. Handle. If your own code fails here, answer 500 (not 400) so the event
// is sent again (see the full handler on the Webhooks page).
switch (event.type) {
case "charge.succeeded":
console.log(`Paid: ${event.data.payment_intent_id}`);
break;
case "charge.failed":
console.log(`Failed: ${event.data.failure_reason}`);
break;
case "charge.refunded":
// null means the connection could not derive the total: say so, never "0".
console.log(`Refunded so far: ${event.data.amount_refunded_total ?? "unknown, review"}`);
break;
default:
// Unknown event types: log and fall through. constructEvent still
// returns a well-formed envelope for an event type added server-side
// after this SDK version, so new types may arrive without an SDK bump.
console.log(`Unhandled event: ${event.type}`);
}

// Your handler returns the HTTP 200 ack — constructEvent only parses the
// event; it does not send an HTTP response.
res.status(200).json({ received: true });
});

The webhook secret is per-endpoint (whsec_*), minted when you register the endpoint at /dashboard/developers/webhooks. The signature header is named x-vonpay-signature with the format t=<unix-seconds>,v1=<hex-hmac>. See Webhook Signing Secrets for the create / rotate / revoke lifecycle.


Confirming a return redirect​

When the buyer is redirected back to your successUrl, read the outcome from the API: the redirect itself only tells you they came back.

const client = new VonPayCheckout(process.env.VON_PAY_SECRET_KEY);

const params = Object.fromEntries(
new URL(req.url, `https://${req.headers.host}`).searchParams,
);

// The session id YOUR server stored with this order (not the one in the URL).
const outcome = await client.sessions.confirmReturn(params, undefined, {
expectedSessionId: order.vonpaySessionId,
});

if (outcome.paid) {
// show the confirmation page; if outcome.needsReview, check the payments before you fulfil
} else if (outcome.reason === "still_pending") {
// IN FLIGHT, not declined — show "confirming your payment", never a failure
} else if (outcome.reason === "refunded") {
// the money went back: do not fulfil; show "this payment was returned"
} else {
// not succeeded
}

sessions.confirmReturn(params) reads the payment from the server with your API key and returns { paid, needsReview, reviewReason, signatureValid, status, reason }. Branch on paid, then read needsReview. The return link carries only session, so nothing in the URL can tell you the result (Handle the Return).

Tie the answer to this order (4.0.0+). On its own, paid: true means the session in the URL is one of your paid sessions, so a buyer could paste the return link of a different, cheaper order they paid for. Pass what your server recorded when it created the session, in the third argument: expectedSessionId, and/or expectedAmount with expectedCurrency (always together). A different session reads paid: false with reason: "session_mismatch"; a different amount or currency reads paid: false with reason: "amount_mismatch". A bad option value throws a TypeError before any request.

A refund changes the answer (4.7.0+). A session's status keeps reading succeeded after its payment is refunded, disputed or paid a second time, so confirmReturn also reads the refund totals on the session:

What happenedpaidAlsoWhat to do
Nothing left of the payment: refunded in full (a full refund in progress counts until it fails), or refunded in part with the rest disputedfalsereason: "refunded"Do not fulfill. Show a neutral message ("this payment is being returned or has been returned"), not "payment failed".
Refunded in parttrueneedsReview: falseWhat a partial refund means for the order is your decision.
Two or more payments on the sessiontrueneedsReview: true, reviewReason: "second_payment"Check both payments before you fulfill or refund.
Refund totals not sent: for a few moments after the payment, while a manual-capture payment is on hold, or when the totals could not be readtrueneedsReview: true, reviewReason: "refund_state_unknown"Check the payment before you fulfill. Unknown never reads as "nothing refunded", and never as "not paid".

A dispute with no refund is not on the session: listen for the dispute.* webhooks.

The checks run in this order: no session id (missing_session), expectedSessionId differs (session_mismatch), expectedAmount or expectedCurrency differs (amount_mismatch), status not succeeded (still_pending or not_succeeded), then the refund totals. Among those, a second payment and missing totals are read before refunded, and both report paid with review.

Do not pass a secret. The secret parameter is optional, and return links no longer carry a signature to check. Leaving it out is the normal path: signatureValid then reads null, which means "not checked", a healthy value, not a failure.

⚠️ paid: true is not "safe to fulfill". The status keeps reading succeeded on every replay of the same URL, so record which session IDs you have already fulfilled; and on a captureMethod: "manual" session succeeded means authorized and held, not paid. Fulfill the order from the charge.succeeded webhook rather than here: a buyer who pays and closes the tab never loads this page. See Handle the Return.

VonPayCheckout.verifyReturnSignature is deprecated

Return links no longer carry a signature, so this static method returns false for every one of them and logs a one-time warning. It does not throw, and it is removed in 5.0. Use confirmReturn above: it needs no secret.

Signature verification belongs on webhooks, where each endpoint has its own whsec_* secret; see vonpay.webhooks.verifySignature.


vonpay.webhookSubscriptions.list(params?)​

List your registered webhook endpoints (maps to GET /v1/webhook_subscriptions). Newest first, ordered by creation time.

const page = await vonpay.webhookSubscriptions.list({ limit: 20 });

// page.object => "list"
// page.hasMore => true
// page.data[0] => { id, url, enabledEvents, status, lastSuccessAt, … }

limit is 1–100 and defaults to 10. To page, pass the last item's id as startingAfter:

const first = await vonpay.webhookSubscriptions.list({ limit: 20 });
const next = first.hasMore
? await vonpay.webhookSubscriptions.list({
limit: 20,
startingAfter: first.data[first.data.length - 1].id,
})
: null;
A cursor you do not own is a 400, not an empty page

If startingAfter does not reference one of your own subscriptions, the request fails with 400 validation_error. Pagination deliberately does not silently restart from the top: restarting would let an id be probed across merchants, and a paging loop that mistakes it for "no more pages" would silently re-read page one forever.

Each entry carries status, typed as "active" | "paused" | "disabled", plus lastDeliveryAt, lastSuccessAt and lastErrorAt. Those three are the ones worth surfacing in your own dashboard: a subscription can read active while every recent delivery failed.

From 3.7.0 each entry also types autoPausedAt: the time we paused deliveries after repeated failures, while status still reads "active". Only null means "not paused"; test autoPausedAt === null, not !autoPausedAt, because a missing value means the pause state is unknown. Fix the endpoint, then set status back to "active" to resume.


vonpay.webhookSubscriptions.retrieve(webhookSubscriptionId)​

Look up a single endpoint by id (maps to GET /v1/webhook_subscriptions/{id}).

const sub = await vonpay.webhookSubscriptions.retrieve("vp_whsub_live_k7x9m2n4p3");

// sub.url => "https://mystore.com/webhooks/vonpay"
// sub.enabledEvents => ["charge.succeeded", "charge.refunded"]
// sub.status => "active"

Ownership failures are a 404, never a 403. An id belonging to another merchant and an id that has been deleted both return the same 404 webhook_subscription_not_found as an id that never existed: one body for all three, so ids cannot be probed across merchants.

The one 403 this call can return is unrelated to ownership: like the rest of this resource it is secret-key only, so a publishable key is rejected with 403 auth_key_type_forbidden before the lookup happens.


vonpay.webhookSubscriptions.sendTestEvent(id, params)​

Send one signed test event to an endpoint through the real delivery path and get the outcome in the same call (maps to POST /v1/webhook_subscriptions/{id}/send_test_event). Added in 3.6.0. Requires a secret key. Use it to prove your endpoint verifies and processes notifications.

const outcome = await vonpay.webhookSubscriptions.sendTestEvent(sub.id, {
eventType: "charge.succeeded",
sessionId: "vp_cs_test_k7x9m2n4p3", // optional
});

// outcome.delivered => true when the endpoint answered 2xx
// outcome.responseStatus => the endpoint's HTTP status, or null if nothing answered
// outcome.deliveryAttemptId => audit handle for the attempt
// outcome.signaturePreview => first 12 characters of the signature header sent
// outcome.error => why it was not delivered; null when delivered

delivered: false with a responseStatus is a successful test of an endpoint that answered non-2xx. delivered: false with a null responseStatus and an "address is not allowed" error means nothing was sent: the endpoint's hostname resolves to a private or reserved address. If the endpoint could not be reached or timed out, the call throws 422 webhook_test_delivery_failed with nextAction: "fix_input", and the SDK does not repeat it: check the URL and send again. A 429 or 503 is retried as usual.

The delivered event carries test_event: true, the only marker that it is synthetic. Your handler must check it before touching an order: with sessionId, the payload carries that session's real ids and will match a real order. See Webhook Event Types.


Answering "did my endpoint actually receive that event?"

Read lastDeliveryAt, lastSuccessAt and lastErrorAt from webhookSubscriptions.list() above. Those describe deliveries to your endpoint.

webhookEvents.retrieve(id) is a different thing: it reads our stored record of an event we received from the processor. Its id is the one shown in the dashboard's Events view, not the vp_evt_* id on a payload delivered to you.


vonpay.health()​

Check API health and latency (maps to GET /api/health).

const health = await vonpay.health();
// health.status => "ok" // the only value this call can return, but not
// // for the reason you might expect. "healthy" and
// // "degraded" belong to the DEEP check (?deep=true),
// // which this call does not request — "healthy" is a
// // 200, not a 503 — and health() has no parameter
// // to request the deep check. "error" IS a 503, and the
// // SDK throws on any non-2xx. Wrap in try/catch, not a switch.
// health.version => "" // the endpoint sends no version field; the client
// // defaults it. Do not monitor deploys with this.
// health.latencyMs => 42

vonpay.buyers — stored shopper profiles​

New in 2.0.0. A buyer profile is a stored shopper record you can attach payments to and look up later.

const buyer = await vonpay.buyers.upsert({ externalId: "cust_4471", email: "ada@example.com" });
await vonpay.buyers.retrieve(buyer.id);
await vonpay.buyers.find({ email: "ada@example.com" }); // null when not found
await vonpay.buyers.update(buyer.id, { phone: "+15551234567" });

Six methods: upsert, retrieve, find, list, update, eraseEmail. find returns null rather than throwing when there is no match. Several of your buyers may share an email, so find({ email }) returns one of them: the most recently seen. To see every buyer with that email, use vonpay.buyers.list({ email }) (4.11.0 and later). It returns { data }, most recently seen first, at most 100. By externalId it holds zero or one buyer.

Erasing an email is its own method, on purpose​

⛔ This is the one part of the buyers API where the SDK deliberately refuses to do what the endpoint allows. PATCH /v1/buyers/{id} treats email: null as a permanent erase. Several common JSON libraries serialise an absent optional field as null by default, so a routine "update this shopper's phone number" built from a half-populated struct can wipe their address, return 200, and look exactly like a success.

So update() cannot express null (it is a compile error) and eraseEmail() is the only path that sends it:

await vonpay.buyers.eraseEmail(buyer.id); // the only way to erase

⛔ eraseEmail is not a complete deletion and must never be described to a shopper as one. It clears the address on the profile. Copies elsewhere keep their own retention rules and this call does not touch them.

⚠ And a success does not confirm the provider's copy is gone. We ask your payment provider to drop theirs, but that request is dispatched after we answer you and reports no failure back. For a buyer you only ever identified by email, the retraction cannot be performed at all: the key it needs was derived from the address just erased.

Buyers is the full model, which copies survive, why that list is examples rather than an inventory, and what to do when you are answering a formal erasure request. Read it before you build on this.

vonpay.walletDomains: Apple Pay and Google Pay domains​

New in 3.11.0. Register the domains your checkout runs on for Apple Pay and Google Pay from code, instead of in the dashboard (maps to /v1/wallet-domains). Every call needs a secret key. How entries work (one per domain and wallet, stable ids, the check limit, what Verified means) is in How domain entries work.

import { writeFile } from "node:fs/promises";

// 1. Register. Safe to repeat: the same domain + wallet returns the existing entry.
const apple = await vonpay.walletDomains.create({
domain: "shop.example.com",
walletType: "apple_pay",
});

// 2. Apple Pay only: fetch the file once and deploy it as a static file.
const file = await vonpay.walletDomains.retrieveFile(apple.id);
await writeFile("public/.well-known/apple-developer-merchantid-domain-association", file.content);

// 3. Once the file is live, ask for a check and read the outcome on the entry.
const checked = await vonpay.walletDomains.verify(apple.id);
// checked.verificationStatus => "pending" | "verified" | "failed" | "revoked"
// checked.failureReason => why it is not verified yet, or null

// Google Pay: its own entry, no file.
await vonpay.walletDomains.create({ domain: "shop.example.com", walletType: "google_pay" });
  • Store the id (why it is safe to).
  • create() does not check again. Repeating it returns the saved entry as it is. After you host the file, call verify().
  • verify() returns the entry whatever the outcome. A check that does not pass is not an error: read verificationStatus and failureReason, which can be set on "pending" too. Over the check limit, the SDK waits out the 429 and checks again, so the call can take about 30 seconds. If the 429 still comes back, the domain was not checked again. Poll walletDomains.retrieve(id) between checks.
  • Host the Apple Pay file as a static file. retrieveFile() returns the exact bytes (content, a Uint8Array) and verificationStatus from the X-Vonpay-Verification-Status header. Serve the bytes unchanged at /.well-known/apple-developer-merchantid-domain-association, over HTTPS, with no redirect. Never call retrieveFile() from a public route on each request: it uses your secret key and spends its rate limit. A Google Pay entry has no file (404 wallet_domain_wrong_type).
  • failureReason is one of five codes; Why a check failed says what each means and what to do.
  • create() refusals: 409 wallet_domain_no_binder (your account cannot take wallet payments yet), 422 wallet_domain_invalid (send a bare hostname: no scheme, port or path) and 503 wallet_domain_provider_unavailable (temporary; safe to retry). See error codes.
  • walletDomains.remove(id) stops the button on that domain. Removing it again answers 404 wallet_domain_not_found, so after a retried call check list() before treating a 404 as a failure.
  • walletDomains.list({ limit, cursor }) returns entries newest first (25 by default, at most 100); pass nextCursor as cursor while hasMore is true.
  • Can a wallet payment actually go through? (4.0.0+) Each list() row carries chargeReadiness ({ canCharge, reasons }), and the page carries walletReadiness (one entry per wallet, with setUp) and walletSettings. Verified only means the button can show; canCharge stays false until every step is in place, including a first approved payment with that wallet on your account. Check row.chargeReadiness?.canCharge === true: null means not reported, a not-ready answer is still an object, and a reason code you do not recognise means not ready. The three are null on the answers of create(), retrieve() and verify(); read them from list().

The dashboard flow and per-framework hosting recipes are in Apple Pay setup.

vonpay.subscriptions: Subscriptions​

For businesses with Subscriptions switched on (4.4.0 and later). Start a subscription with recurring on paymentIntents.create(), then read and change it here:

const terms = await vonpay.subscriptionProducts.terms("vsprod_live_Hk29sLq0");
const { data } = await vonpay.subscriptions.list({ buyerId: "cust_1042", status: "active" });
await vonpay.subscriptions.pause(data[0].id, { resumesOn: "2026-12-01" }, { idempotencyKey: "pause_cust_1042_1" });

From 4.6.0, vonpay.subscriptionProducts.list({ productRef, status, limit, startingAfter }) lists your products, newest first, each with its sign-up terms. While hasMore is true, pass nextCursor as startingAfter to read the next page.

Every change (cancel, unscheduleCancel, pause, resume, skip, setNextBillDate, setInterval, setPrice, setDiscount, removeDiscount) takes { idempotencyKey, dryRun?, actorLabel? } as its last argument and returns a SubscriptionChange. From 4.5.0, pause() and skip() also take { customerRequested, note } (skip(id, params, options)), and a Subscription carries paidThrough: give the customer access by it, never by status. The SDK refuses a change without idempotencyKey before sending it, unless dryRun is true. From 4.10.0, a Subscription carries heldReason: why it is held, and null for any other status (the reasons). From 4.13.0, vonpay.subscriptions.listAttempts(subscriptionId, { limit?, startingAfter? }) lists every payment try for the subscription, newest first: pass nextCursor as startingAfter while hasMore is true. The webhook types are SubscriptionCreatedEvent, SubscriptionRenewedEvent, SubscriptionPaymentFailedEvent, SubscriptionCancelledEvent and SubscriptionUpdatedEvent, all with SubscriptionEventData, which from 4.13.0 carries attempt_number, retries_left and final_attempt. Every call, field and event is on the Subscriptions reference; the steps in order are in the Integration guide.

From 4.11.0:

  • Customer pauses. A Subscription carries customerPause: allowed, reason and maxResumesOn. Read it before you offer the customer a pause (customer pauses). A pause sent with customerRequested: true can be refused with 409 subscription_pause_not_allowed, or with 400 subscription_pause_too_long, which carries err.maxCycles and err.maxResumesOn.
  • Brand and store. A Subscription carries brand ({ id, name }) and store ({ platform, domain }). Each is null when the subscription has none.
  • Product changes. vonpay.subscriptionProducts.retrieve(product) reads one product, by id or by reference. Five calls change products: subscriptionProducts.create(params, options), subscriptionProducts.update(productId, params, options), subscriptionProducts.changePrice(productId, params, options), subscriptionProducts.archive(productId, options) and subscriptionProducts.unarchive(productId, options). Each needs options.idempotencyKey: the SDK refuses a call without one before sending it. changePrice() requires applyToExisting (false changes the price for new sign-ups only). A restricted key needs subscription_products.write. A product also carries publicUrl, publicUrlAllowed and warnings. The fields, rules and refusals are on Subscription products.

Upgrading to 4.13.0​

Check:

  • Late money. lateMoneyOutcome is now LateMoneyOutcome | null | undefined. Code that declared it as the old three-value union no longer compiles. null means no late money arrived (the values).
  • Exhaustive checks. SessionNotModifiableReason gains stored_credential_declared, ApiKeyLimit gains per_session, and PaymentIntentWarningCode gains mit_anchor_not_used.

New:

  • Name the customer with buyerId on sessions.update().
  • Session limits on a restricted key. A session total over the key's charge limits gets 422 api_key_limit_exceeded with limit per_session, on sessions.create() and sessions.update(). daily_total now also counts the key's open sessions (limits).
  • A customer-initiated charge of a saved card may leave out mit.originalTransactionId. An id that cannot be used is not used either: mitOriginalTransactionId is null and warnings carries mit_anchor_not_used.
  • derivedAmount on order_total_mismatch and lineIndex on the two mirror-line refusals, on VonPayError.
  • vp_tx_id_source on the charge.succeeded, charge.refunded, refund.failed and charge.failed types: how vp_tx_id was matched (webhook events).
  • subscriptions.listAttempts() and the try fields on subscription events.

Upgrading to 4.12.0​

Additive. Check:

New:

  • The in-page bank check. Pass nextActionPresentation: "in_page" to paymentIntents.create() (type NextActionPresentation; leave it out for "redirect", the default). Hand the answer's clientReadSecret to your page in the response body, and from there only to vora.handleNextAction(). Never log or store it. The SDK leaves it out of console.log, JSON.stringify and { ...pi }, so read it as pi.clientReadSecret. The rules and refusals: show the check in a pop-up on your page.
  • paymentIntents.createClientReadSecret(id) mints a new secret for a payment still waiting on the bank, for a page that reloaded. It answers { paymentIntent, clientReadSecret, expiresAt }. The SDK never repeats this call. A timeout or network error throws ClientReadSecretOutcomeUnknownError, because a secret may have been minted: read the payment before you call again.
  • Refund limits on a restricted key. A refund that does not fit the key's refund limits gets 422 api_key_limit_exceeded with limit per_refund or refund_daily_total, and nothing is refunded. refund_daily_total clears by waiting (retryable: true). Its advice is exported as API_KEY_REFUND_DAILY_TOTAL_HELP.

Upgrading to 4.11.0​

Additive. Check:

  • Test doubles. Seven fields are now required: cardCheck on SavedPaymentMethod; brand, store and customerPause on Subscription; and publicUrl, publicUrlAllowed and warnings on SubscriptionProduct. Add them to an object you build by hand in a test: null for each, and [] for warnings. Code that only reads these types is unaffected.
  • Exhaustive checks. ErrorCode gains payment_under_review, subscription_pause_not_allowed, subscription_pause_too_long, public_url_not_allowed and the product refusals. RestrictedKeyPermission gains subscription_products.write.

New:

  • cardCheck on each saved card from paymentMethods.list() (type SavedCardCheck): { status: "approved", storedCredentialUse } when an approved $0 card check stored the card, or null when it was saved without one. null also covers a card checked before 13 November 2026 whose declaration is not on record. Read how it works before its first merchant-initiated charge.
  • payment_method_card_check on the session read.
  • customerPause, brand, store and the product calls on Subscriptions.
  • buyers.list() for every buyer with one email.
  • warnings on the sessions.create() answer: test_store_order_not_written says a test checkout writes no order in its store (test orders).

Upgrading to 4.10.0​

Additive. Check:

  • Test doubles. heldReason is required on the Subscription type. Add it to a Subscription you build by hand in a test.
  • Restricted keys that change billing. RestrictedKeyPermission now includes subscriptions.write_billing. The API already asks a restricted key for it on setNextBillDate, setInterval, setPrice, setDiscount, removeDiscount and createPortalLink, whatever SDK version you use (permissions). The upgrade does not change that.

New: heldReason on the subscription.

Upgrading to 4.9.0​

Additive. Check:

  • Tests against a local server. A client whose baseUrl is on localhost, 127.0.0.1 or [::1] no longer sends SDK telemetry by default.
  • The card on create(), capture() and void(). card is complete or null. Check for null before you read card.brand.
  • Exhaustive checks. SessionNotModifiableReason gains five values (sessions.update()), and ErrorCode gains mirror_test_order_limit_reached (Auto-Retry).

New: lateMoneyOutcome, attempts, attemptsStatus, processorResponse and card on the payment read and the list items, and the guest fields on sessions.update().

Upgrading to 4.7.0​

Check:

  • confirmReturn reads refunds. A return with nothing left of the payment now reads paid: false with reason: "refunded". It read paid: true before. If you branch on reason exhaustively, add it, and read needsReview before you fulfill (details).
  • verifyReturnSignature. It returns false for every return without sig, which is every return link today. Move to confirmReturn. It is removed in 5.0.
  • Webhook secrets. verifySignature and constructEvent throw a TypeError on an empty or example secret or on an API key. Nothing changes for a real whsec_* secret.
  • A missing API key. new VonPayCheckout({ apiKey: undefined }) (or null) now throws Error("API key is required"), not a TypeError. No client was created before, and none is created now.

New: keyMode() and heldAsLive().

Upgrading to 4.5.0​

Additive for every call you can make today. Check:

  • A proxy opted in by the environment variable alone. A live key sent to a baseUrl that is not a Von Payments address because only VONPAY_ALLOW_CUSTOM_BASE_URL=1 is set still works, with a one-time deprecation warning. Pass allowCustomBaseUrl: true instead: from 5.0.0 the environment variable alone is refused.
  • Exhaustive checks. ErrorCode gains report_too_large, subscription_customer_change_limit_reached and subscription_limited_discount_active. A switch with a default branch is unaffected.

New:

  • Payment reports: paymentIntents.list(), listPages(), listAutoPaging() and summary(), with VonPayError.param, maxGroups and timeoutMs.
  • Subscriptions: paidThrough, pendingProductChange, customerScheduleChangeUsed and customerScheduleChangeAvailableAt on Subscription; { customerRequested, note } on pause() and skip(); VonPayError.nextChangeAllowedOn on 409 subscription_customer_change_limit_reached (limits).
  • last_payment_error.payment_intent_id on the session read (above).
  • ERROR_CODES (every ErrorCode as a list) and isErrorCode(value), and stripHiddenCharacters(text), which removes the characters that hide or reorder text. Use it before you show text from a payment, a customer or an AI agent to a person.

Upgrading to 4.4.0​

Additive for every call you can make today. Check:

  • Exhaustive checks. ErrorCode gains payment_intent_not_found, transaction_not_found, payment_method_not_stored and recurring_mandate_required. WebhookEvent gains members, among them MerchantCardTestingSuspectedEvent. A switch with a default branch is unaffected; one that asserts exhaustiveness with never names the new cases.
  • Code that reads session_not_found after a payment lookup. A payment or transaction that is not found now answers payment_intent_not_found or transaction_not_found. This comes from the API, so it applies to every SDK version. It affects paymentIntents.retrieve(), capture() and void(), refunds.create() and refunds.list(), and paymentIntents.create() when mit.originalTransactionId names no payment intent of yours.

New:

  • paymentIntentId on VonPayError: on a 422 from paymentIntents.create() that was refused before any money moved, the failed payment intent that records the attempt (The record of a refused charge). Nothing was charged and no webhook is sent for it. Send the corrected charge with a new idempotencyKey. undefined when no record was written.
  • Error help for the four new codes, and for payment_method_unvaulted and capability_not_supported, which read as unknown codes before. payment_method_unvaulted is retryable: true with nextAction: "wait_and_retry": the saved card is still being stored. The SDK never repeats a 422, so wait a few seconds and send the charge again yourself, with a new idempotencyKey. payment_method_not_stored and recurring_mandate_required are nextAction: "ignore", as for a decline: the customer must enter the card again or pay while present.
  • MerchantCardTestingSuspectedEvent (data type CardTestingSuspectedData) types the merchant.card_testing_suspected alert.
  • Subscriptions: subscriptions.list(), retrieve(), cancel(), unscheduleCancel(), pause(), resume(), skip(), setNextBillDate(), setInterval(), setPrice(), setDiscount(), removeDiscount() and createPortalLink(), subscriptionProducts.terms(), the recurring sign-up on paymentIntents.create(), and the five subscription.* webhook types. See above.

Upgrading to 4.3.0​

Additive for every call you can make today. Check:

  • Exhaustive checks. ErrorCode gains members, among them api_key_permission_denied, api_key_limit_exceeded, the three mirror_settle_only_* refusals, platform_fee_exceeds_amount, request_body_too_large and request_body_timeout. SessionNotModifiableReason gains "concurrent_update". A switch with a default branch is unaffected; one that asserts exhaustiveness with never names the new cases.
  • Objects you build yourself. SavedPaymentMethod gains a required field, consent: a test double that builds one must add it (null is accepted).
  • Custom base URLs. Every key that is not a sandbox secret key (vp_sk_test_*) or a publishable key (vp_pk_*) is now held to the live-key rule: the client refuses to send it to an address that is not Von Payments' own, including localhost, unless you set allowCustomBaseUrl: true or VONPAY_ALLOW_CUSTOM_BASE_URL=1.

New:

  • processorConnection (type ProcessorConnection, { id, name }) on payment intents from create(), retrieve(), capture() and void(), and processor_connection on the charge.* and payment_intent.* webhook payloads: which of your payment connections processed the payment. Match and group on id. name is your own label, free text and possibly null: keep it internal and never show it to shoppers. null when no connection was reached. It is not returned to a publishable key, and session.failed does not send it.
  • networkAdvice and networkAdviceRetryAfterMs (type NetworkAdvice) on payment intents, and network_advice / network_advice_retry_after_ms on the charge.failed, payment_intent.failed and session.failed webhook payloads: the card network's own advice about the card (Decline handling). Treat a word you do not recognise as "do_not_try_again". null is never permission to retry.
  • mitAnchorSource (type MitAnchorSource): what a merchant-initiated charge is linked to, "payment" or "card_check". null on a charge without an mit block.
  • fraudEvidence on paymentIntents.create() (type FraudEvidence: customerIp, deviceFingerprint, customerEmail, customerAccountId, productDescription) and fraudEvidenceForwarded on the create response (Fraud evidence).
  • Store facts on a settle-only refusal. On the three mirror_settle_only_* codes, VonPayError carries chargeAmount, chargeCurrency, orderBalance (on an amount mismatch, the amount to charge instead), orderBalanceRaw, orderCurrency, orderStatus and orderPaymentStatus (the order's payment status, not this request's). A store fact reads null when the store could not be read.
  • Restricted-key details. On api_key_limit_exceeded, VonPayError carries limit (type ApiKeyLimit), limitMinor, usedMinor and limitCurrency. With limit: "daily_total" the error reads retryable: true: the 24-hour total clears by waiting. On api_key_permission_denied it carries refusedFields. Type RestrictedKeyPermission lists the permission names a restricted key can hold.
  • Error help for platform_fee_exceeds_amount (an account setting: contact support), request_body_too_large and request_body_timeout. The SDK does not resend a request_body_timeout for you: resend the same request, with the same idempotencyKey where the call takes one.

Upgrading to 4.2.0​

Additive: nothing was removed or renamed. Check:

  • Exhaustive checks. ErrorCode gains "mirror_line_invalid_variant_ref" (Shopify order lines). A switch with a default branch is unaffected; one that asserts exhaustiveness with never names the new case.

New:

  • sessions.update() takes metadata, alone or with amount, which is now optional.
  • Error help for mirror_line_missing_product_ref: retryable: false, nextAction: "fix_input".
  • The invalid_transition help now names cancelled as a final status: do not retry, and do not charge the buyer again on your own.

Upgrading to 4.1.0​

Additive: nothing was removed or renamed. Check:

  • Exhaustive checks. PaymentIntentStatus gains "cancelled" (final, no money taken: see Status lifecycle), and the ErrorCode and WebhookEvent unions gain members. A switch with a default branch is unaffected; one that asserts exhaustiveness with never names the new cases.
  • Objects you build yourself. A test double of SavedPaymentMethod must add setupForFutureUseMethod (null for "not recorded").

New:

  • How the buyer agreed to reuse. tokens.create({ setupForFutureUseMethod }) takes "checkbox" or "checkout_terms" (type SetupForFutureUseMethod), recorded on the card only beside a setupForFutureUse in the same call. paymentMethods.list() rows read it back as setupForFutureUseMethod, and the payment_method.attached webhook as setup_for_future_use_method (type SetupForFutureUseMethodStored, an open set: treat a value you do not recognise as "recorded, method unknown"). See Recurring & saved cards.
  • vp_buyer_id on sessions.get() and on the payment_method.attached webhook: the buyer Von Payments created for a session that named none.
  • SessionExpiredFrom gains "authentication_cancelled", a session closed while its payment waited on the bank's security check (Close a session). If the bank's check completes later anyway, the payment is still recorded, so check paymentStatus too.
  • Error help (retryable, nextAction) for session_payment_in_progress, provider_operation_refused, refund_declined, refund_before_settlement, wallet_session_refused, wallet_not_saved and payment_form_used. The currency_not_supported help now lists UGX.

Upgrading to 4.0.0​

Two changes can break code that worked on 3.x. Nothing was removed or renamed.

  • A live key with your own baseUrl. With a vp_sk_live_* key, new VonPayCheckout(...) now throws a TypeError unless baseUrl is unset or https on checkout.vonpay.com / checkout-staging.vonpay.com. Remove baseUrl, or opt in for a proxy you run on purpose (Initialize).
  • Retry logic that reads err.retryable. An error with retryWithheld: true now carries retryable: false and nextAction: "reconcile": read the payment back before anything else (Auto-Retry).

Also check:

  • Webhook card is typed optional: read event.data.card?.last4. A check such as event.data.card !== null passes on a payload without a card and then fails.
  • Exhaustive checks. WebhookEvent gains payment_method.attached, and ReturnOutcome.reason gains session_mismatch / amount_mismatch (only when you pass the new confirmReturn options). A switch with a default branch is unaffected.
  • Objects you build yourself. A test double of WalletDomain or WalletDomainList must add chargeReadiness, walletReadiness and walletSettings (null for "not reported").

New: the confirmReturn order check, wallet charge readiness, walletType on the tokens.revoke() result, and error help for charge_in_progress and charge_already_in_flight.

Upgrading to 3.11.0​

Additive. New: walletDomains (list, create, retrieve, retrieveFile, verify, remove). The six wallet_domain_* error codes now carry their own retry advice (retryable, nextAction) instead of a generic fallback.

Upgrading to 3.10.0​

Additive. New: a buyer's saved cards.

  • paymentMethods.list({ buyerId, limit?, startingAfter? }) lists one buyer's saved cards, newest first. buyerId is your own customer reference.
  • tokens.revoke(tokenId, { buyerId?, initiatedBy? }) revokes a saved card permanently. When a shopper removes their own card, pass { buyerId, initiatedBy: "buyer" } so the card is revoked only if it is theirs; take buyerId from your signed-in session, never from the shopper's request. alreadyRevoked true or false are both success.

Both need a secret key. A blank buyerId throws a TypeError before anything is sent. Tokens has the full behaviour, including which cards are listed and revoking.

Upgrading to 3.9.0​

Additive. New:

  • securityCodeVerification: "strict" on paymentIntents.create(), only with securityCodeSession: the charge completes only on an issuer security-code match (strict check). New ErrorCode members security_code_not_verified and security_code_check_in_progress.
  • mit.originalTransactionId is optional on a merchant-initiated charge of a saved card; the linked payment comes back as mitOriginalTransactionId. A card with no customer-present payment is refused with mit_anchor_unknown.
  • retry_after_ms and outcome on sessions.get(), and action, buyer_message and buyer_action on its last_payment_error (session object).
  • pulseStreamToken on the paymentIntents.create() response; pulseToken is deprecated and null in production.
  • session_attempt_limit_reached joins ErrorCode.

Upgrading to 3.8.0​

Additive. New: the decline reason on paymentIntents.retrieve() (declineCode, action, declineMessage, ruleCode), and the ErrorCode member buyer_reference_conflict: buyers.upsert() is refused with 409 when the externalId belongs to a buyer created with your other-mode key.

Upgrading to 3.7.0​

Additive. New: networkTransactionId on payment intents and network_transaction_id on the two success webhooks (see paymentIntents.retrieve()), and autoPausedAt on webhook subscriptions (see webhookSubscriptions.list()). ErrorCode gains payment_form_expired, and NextAction gains "reload_payment_form": if you switch exhaustively on err.nextAction, add it. No SDK method calls the route that returns that code; it is named so a server that relays the browser's answer can match it.

Upgrading to 3.6.0​

Additive, apart from one type correction. Saved-card details can be null. Token.card.brand, .last4, .expMonth and .expYear are now typed string | null / number | null, matching what the API already sends when the payment provider's details for a saved card cannot be read (the card is still saved and usable). At runtime, a field the response omits now reads null instead of undefined, and a response with no card now gives a card whose four fields are null instead of no card at all. A response that carries every field is unchanged. TypeScript may now ask for a null check where you read them:

const label = token.card.last4 ?? "unknown";

If you switch exhaustively on resolvedDescriptor.reason, add "invalid_for_provider": the charge was sent without your configured descriptor because it breaks a provider limit. See Statement descriptors.

Upgrading to 3.0.0​

Two breaking changes. Nothing was removed or renamed.

Pass idempotencyKey to void() to keep automatic retries. A void now follows the same rule as capture and refunds: after a timeout or a 500/502/503/504 it is retried only when you passed a key. Without one, the first error is thrown with retryWithheld: true. A void releases the hold for good, and an unclear failure does not mean it was not applied.

await vonpay.paymentIntents.void(paymentIntentId, { idempotencyKey: `order_${orderId}_void` });

A redirect from the API is now an error. The API never redirects, so a 3xx means something else answered: a proxy, a mistyped baseUrl, or a hijacked connection. The SDK no longer follows it and throws unexpected_redirect with retryable: false and a new nextAction value, check_configuration. Do not retry: check that baseUrl is https://checkout.vonpay.com with no path, then any proxy and the network. If you switch exhaustively on ErrorCode or nextAction, add both values.

3.0.0 also exports formatMinorUnits(amount, currency) (display only: do not parse or store its output), minorUnitDigits(currency) and isLiveKey(key).

Upgrading to 2.0.0​

One breaking change, and it is a type change rather than a behaviour change.

rejectReason dropped five values it could never receive. not_authorized, already_captured, already_voided, already_refunded and amount_exceeds_remaining are gone; the server never sent any of them, so every comparison against one was already dead code. Those comparisons now fail to compile. Delete them.

⭐ The value worth adding a branch for is concurrent_update: another capture or void is in flight for the same payment right now. Before 2.0.0 the SDK replaced any value it did not recognise with nothing at all, so a branch checking for a race never fired and a payment still in flight was read as terminal. That is how a live payment gets cancelled or refunded. Treat it as "unknown outcome, read again", never as an end state.

The full list and what each value means is on Error codes.

Error reporting​

The SDK accepts an optional errorReporter callback in the constructor so integrators can pipe SDK failures into their own observability stack (Sentry, Datadog, custom logger). Your reporter is invoked synchronously, fire-and-forget; if it throws, the SDK swallows the throw with a console.warn and continues.

A separate SDK-telemetry channel can POST anonymised error events back to Von Payments to improve the SDK. It is enabled by default for test keys (vp_sk_test_*) and off for live keys unless you explicitly enable it; it never carries request bodies or PII. From 4.9.0 it is also off by default when baseUrl is on localhost, 127.0.0.1 or [::1], whatever the key, because such a client is a test against a local server. Pass telemetry: { enabled: true } to keep it on. The errorReporter callback above is independent of this and runs whether or not telemetry is enabled.

When it fires​

  • API request failures: a non-retryable response (any status not in the retry set: 4xx including 401/403/404/422, plus non-retryable 5xx like 501); retry-exhaustion on a retryable status (429, 500, 502, 503, 504); and network/timeout errors after retry exhaustion
  • webhooks.constructEvent verification failures (signature mismatch, stale timestamp, malformed header)

It does not fire on:

  • verifySignature / verifyReturnSignature: these return boolean for a delivery or a return
  • The TypeError for an unusable webhook secret: it is thrown before any verification
  • The constructor's invalid-key-prefix throw: that's a dev-time error before the reporter is wired

Callback shape​

import type { ErrorReporter, ErrorReporterContext } from "@vonpay/checkout-node";

const reporter: ErrorReporter = (err, ctx) => {
// err is VonPayError | Error
// ctx is ErrorReporterContext:
// method: string // e.g. "sessions.create", "sessions.get",
// // "sessions.validate", "webhooks.constructEvent",
// // or a "GET /api/health"-style fallback
// sdkVersion: string
// url?: string // origin + path, no query string (no PII via params)
// status?: number // HTTP status if from API response
// requestId?: string // X-Request-Id for correlation
// code?: string // server error code (auth_invalid_key, etc.)
// attempt?: number // 0-indexed retry attempt
};

ErrorReporterContext.method is typed as a plain string: the SDK passes a method label such as "sessions.create" or "webhooks.constructEvent" where one is available, and otherwise falls back to a "<HTTP-METHOD> <path>" string (for example "GET /api/health").

Sentry example​

import * as Sentry from "@sentry/node";
import { VonPayCheckout } from "@vonpay/checkout-node";

const vonpay = new VonPayCheckout({
apiKey: process.env.VON_PAY_SECRET_KEY!,
errorReporter: (err, ctx) => {
Sentry.captureException(err, {
tags: { sdk: "vonpay-node", method: ctx.method, code: ctx.code },
contexts: { vonpay: ctx },
});
},
});

Datadog example​

import { VonPayCheckout } from "@vonpay/checkout-node";

const vonpay = new VonPayCheckout({
apiKey: process.env.VON_PAY_SECRET_KEY!,
errorReporter: (err, ctx) => {
logger.error("vonpay sdk error", { err, ...ctx });
},
});

errorReporter is opt-in and additive: if you don't configure it, errors still propagate via throw and nothing else changes.


Charges without an idempotency key​

From the 28 October 2026 cut-off the API can refuse a charge that carries no Idempotency-Key with 400 idempotency_key_required, before anything is charged (Idempotency). From 3.2.0 the SDK prints one [vonpay] warning per process the first time paymentIntents.create() is called without idempotencyKey. The charge is still sent. An empty string counts as no key. VONPAY_QUIET=1 silences the warning.

Pass the same key on every retry of the same charge:

await vonpay.paymentIntents.create(params, { idempotencyKey: `order_${orderId}_create` });

Auto-Retry​

The SDK automatically retries on 429 (rate-limited) and 5xx (server error) responses with exponential backoff. It reads the Retry-After header when present, capped at 60 seconds. Configure with maxRetries in the constructor (default: 2).

From 4.9.0 the SDK never repeats 429 mirror_test_order_limit_reached, and err.retryable is false. It means a sandbox account whose test orders go into a real connected store has too many open at once. Nothing was charged. Cancel the open test orders in the store, or wait about a day for them to clear, then send the request again.

Money-moving calls without an idempotency key are not retried​

Four calls move money: paymentIntents.create, paymentIntents.capture, paymentIntents.void (from 3.0.0) and refunds.create.

When one of them ends ambiguously (a 500, 502, 503, 504, or a network timeout), the SDK cannot tell whether the charge was applied before the connection broke. If you sent no idempotency key, retrying could take the buyer's money a second time, so the SDK stops and raises the first error instead.

Send an idempotency key and the retries come back. The same key rides every attempt, so the repeat is collapsed server-side and is safe. One exception, from 3.3.0: when the 5xx reply to a money call (paymentIntents.create, .capture, .void, refunds.create) cannot be read, because it was cut off or replaced by a proxy's HTML error page, the SDK stops after the first attempt even with a key. The error carries retryWithheld: true; read the payment intent back before repeating anything.

await vonpay.paymentIntents.create(
{ amount: 1499, currency: "USD", paymentMethod: { id: "vp_pmt_live_..." }, returnUrl: `https://mystore.com/checkout/return?order=${orderId}` },
{ idempotencyKey: `order_${orderId}_create` }, // ← retries stay enabled
);

Two boundaries, so this doesn't read as broader than it is:

  • 429 is still retried without a key. A rate-limited request is rejected before it reaches the handler, so nothing was charged and repeating it is safe.
  • Non-money writes are unchanged. sessions.create, tokens.create and the webhook-subscription writes retry exactly as before.

On the HTTP path the raised VonPayError carries retryWithheld: true so you can tell this case apart from an ordinary failure:

catch (err) {
if (err instanceof VonPayError && err.retryWithheld) {
// Ambiguous outcome, no key sent — the charge MAY have gone through.
// Do not blindly re-issue; look up the payment intent before retrying.
}
}

From 4.0.0 a charge, capture, void or refund error with retryWithheld: true carries retryable: false and nextAction: "reconcile" (the advice is exported as RETRY_WITHHELD_HELP), so retry logic keyed on err.retryable does not fire for it. Read the payment back first (paymentIntents.retrieve(), or refunds.list() for a refund). Send it again only if it did not happen, and only with the same idempotencyKey.

A timeout is withheld too, but arrives without the flag

The same protection applies when the request times out or the network drops: that outcome is always ambiguous. But a network failure raises the underlying error rather than a VonPayError, so retryWithheld is not present on it.

Do not treat "no retryWithheld" as "safe to retry". After any failed money-moving call sent without an idempotency key, confirm the actual state before re-issuing.

The cleanest fix for all of this is to send an idempotency key on every money-moving call; then none of the above applies. See Idempotency.

payment_outcome_unknown is never retried​

In 2.11.0 and later, the SDK never repeats a call that answers 502 payment_outcome_unknown, with or without an idempotency key, on a capture or a void alike: the provider accepted the operation and only the record of it failed, so a repeat could capture twice. The error carries nextAction: "reconcile" and captureOutcome or voidOutcome set to "unknown". Read the payment intent back with paymentIntents.retrieve() before doing anything else.


Error Handling​

All methods throw VonPayError on non-2xx responses. Errors include structured fields for programmatic handling.

import { VonPayCheckout, VonPayError } from "@vonpay/checkout-node";

try {
await vonpay.sessions.create({ ... });
} catch (err) {
if (err instanceof VonPayError) {
console.error(err.message); // "Invalid API key"
console.error(err.status); // 401
console.error(err.code); // "auth_invalid_key"
console.error(err.fix); // "Check that your API key is correctly formatted and active"
console.error(err.docs); // "https://docs.vonpay.com/reference/security#key-types"
console.error(err.requestId); // "req_abc123"
console.error(err.rateLimit); // { limit: 100, remaining: 0, reset: 1710000000, retryAfter: 30 }
}
}

rateLimit is { limit, remaining, reset, retryAfter? }; retryAfter (seconds) is populated from the Retry-After header when the server sends one.

ErrorCode union type​

The code field is a string-literal union, enabling exhaustive switch statements:

import type { ErrorCode } from "@vonpay/checkout-node";

function handleError(code: ErrorCode) {
switch (code) {
case "auth_missing_bearer":
case "auth_invalid_key":
case "auth_key_expired":
case "auth_key_type_forbidden":
case "auth_merchant_inactive":
case "auth_service_unavailable":
// authentication errors
break;
case "validation_error":
case "validation_missing_field":
case "validation_invalid_amount":
// validation errors
break;
case "rate_limit_exceeded":
case "rate_limit_exceeded_per_key":
// back off
break;
case "session_not_found":
case "session_expired":
case "session_wrong_state":
case "session_integrity_error":
// session errors
break;
case "payment_intent_not_found":
case "transaction_not_found":
// check the id and the key's mode
break;
// ... exhaustive handling
}
}

auth_invalid_key maps to HTTP 401, auth_key_type_forbidden to 403, and both rate_limit_exceeded / rate_limit_exceeded_per_key to 429.


Webhook Event Types​

WebhookEvent is a discriminated union on the type field. The envelope carries id, type, created, livemode, merchant_id, and a typed data payload that varies by event type, plus test_event?: true on a Send test event delivery only: if (event.test_event === true) return 200 and do nothing else. See Webhook Event Reference for the full per-event data shapes.

EventTyped data fields
charge.succeededsession_id, payment_intent_id, transaction_id, vp_tx_id, amount, currency, card
charge.failedsession_id, payment_intent_id, transaction_id, vp_tx_id, amount, currency, failure_reason, failure_code, rule_code, network_decline_code, card, retry
charge.refundedsession_id, payment_intent_id, transaction_id, vp_tx_id, refund_id, amount, refund_amount, amount_refunded_total, currency, reason, is_partial, original_charge_amount, card
refund.failedsession_id, payment_intent_id, transaction_id, vp_tx_id, refund_id, amount, refund_amount, amount_refunded_total, currency, reason, reason_code, is_partial, original_charge_amount, retry_available, card
payment_intent.succeededsession_id, payment_intent_id, transaction_id, amount, currency
payment_intent.failedsession_id, payment_intent_id, transaction_id, amount, currency, failure_reason, failure_code, rule_code, network_decline_code, retry
payment_intent.cancelledsession_id, payment_intent_id, transaction_id, amount, currency, cancellation_reason

Reconcile and refund on vp_tx_id, the Von transaction id, never transaction_id, which is not one id space. The charge.* types name it as of 2.7.1, and refund.failed as of 2.7.2. The wire carries more, unchanged on event.data: avs_result_code / cvv_result_code on charge.succeeded, and decline_code / action / decline_message on the failure family. The event reference documents each. Every top-level data key is nullable: the SDK types each as T | null, so always null-check before use. card is { brand, last4 } (its inner fields are non-null once card itself is present) and is populated only when card enrichment is active for the merchant. From 4.0.0 it is typed optional as well as nullable (card?: WebhookCard | null), so read it as event.data.card?.last4. failure_code is the normalized decline code (e.g. card_declined); network_decline_code is the raw ISO-8583 code (e.g. 05).

The table lists the most-used events, not every member of the union. From 3.6.0, charge.failed, payment_intent.failed and session.failed type retry, the same { allowed, attempts_remaining } object as on sessions.get(). A failure event is sent for every declined attempt, so one is not final on its own: allowed: true means the session was re-opened for another card (keep the order open); allowed: false with attempts_remaining: 0 is final for this checkout; null means retry does not apply. An event without the field is unknown, never final. See A failed charge is not always the end of the checkout.

import type { WebhookEvent } from "@vonpay/checkout-node";

function handle(event: WebhookEvent) {
switch (event.type) {
case "charge.succeeded":
// event.data.transaction_id is typed here
break;
case "charge.failed":
// event.data.failure_reason is typed here
break;
case "charge.refunded":
// event.data.amount_refunded_total is typed here
break;
}
}

TypeScript​

All types are exported:

import type {
VonPayCheckoutConfig,
CreateSessionParams,
CheckoutSession,
SessionStatus,
LineItem,
HealthStatus,
VonPayError,
ErrorCode,
WebhookEvent,
} from "@vonpay/checkout-node";

Sample apps​

Clone-and-run reference integrations using this SDK live in Von-Payments/vonpay-samples:

Each ships with .env.example, a per-sample README, and pinned to a known-working SDK version.