Skip to main content

Overview

VaultClient is the main orchestration client that manages payment operations across multiple payment providers. It handles routing, idempotency, provider failover, and platform reporting.

Constructor

new VaultClient(config: VaultConfig)
Creates a new VaultClient instance with the provided configuration.
config
VaultConfig
required
Configuration object for the VaultClient. See Configuration for details.

Example

import { VaultClient, StripeAdapter } from '@vaultsaas/core';

const client = new VaultClient({
  providers: {
    stripe: {
      adapter: StripeAdapter,
      config: {
        apiKey: process.env.STRIPE_API_KEY,
      },
    },
  },
  routing: {
    rules: [
      { match: { default: true }, provider: 'stripe' }
    ],
  },
});

Properties

config
VaultConfig
required
The validated configuration object passed to the constructor.

Methods

charge

Executes a one-step payment charge with immediate capture.
async charge(request: ChargeRequest): Promise<PaymentResult>
request
ChargeRequest
required
The charge request payload
PaymentResult
object
Normalized payment result

Example

const result = await client.charge({
  amount: 2500,
  currency: 'USD',
  paymentMethod: {
    type: 'card',
    token: 'pm_card_visa',
  },
  customer: {
    email: '[email protected]',
  },
  metadata: {
    orderId: 'ord_123',
  },
  idempotencyKey: 'order-123',
});

console.log(result.status); // 'completed'
console.log(result.provider); // 'stripe'

authorize

Authorizes a payment without capturing funds (two-step payment flow).
async authorize(request: AuthorizeRequest): Promise<PaymentResult>
request
AuthorizeRequest
required
Authorization request payload. Identical to ChargeRequest.
PaymentResult
object
Normalized payment result with status set to authorized

Example

const authorization = await client.authorize({
  amount: 5000,
  currency: 'USD',
  paymentMethod: {
    type: 'card',
    token: 'pm_card_visa',
  },
  customer: {
    email: '[email protected]',
  },
});

console.log(authorization.status); // 'authorized'

capture

Captures funds from a previously authorized transaction.
async capture(request: CaptureRequest): Promise<PaymentResult>
request
CaptureRequest
required
Capture request payload
PaymentResult
object
Normalized payment result

Example

// Full capture
const captured = await client.capture({
  transactionId: authorization.id,
});

// Partial capture
const partialCapture = await client.capture({
  transactionId: authorization.id,
  amount: 2500, // Capture only $25.00 of the authorized amount
});

refund

Refunds a completed transaction (full or partial).
async refund(request: RefundRequest): Promise<RefundResult>
request
RefundRequest
required
Refund request payload
RefundResult
object
Normalized refund result

Example

// Full refund
const refund = await client.refund({
  transactionId: result.id,
  reason: 'Customer requested refund',
});

// Partial refund
const partialRefund = await client.refund({
  transactionId: result.id,
  amount: 1000, // Refund only $10.00
  reason: 'Partial refund for damaged item',
});

void

Voids (cancels) an authorized transaction before capture.
async void(request: VoidRequest): Promise<VoidResult>
request
VoidRequest
required
Void request payload
VoidResult
object
Normalized void result

Example

const voided = await client.void({
  transactionId: authorization.id,
});

console.log(voided.status); // 'completed'

getStatus

Retrieves the current status of a transaction.
async getStatus(transactionId: string): Promise<TransactionStatus>
transactionId
string
required
The transaction ID to query
TransactionStatus
object
Transaction status with history

Example

const status = await client.getStatus('vtxn_123');
console.log(status.status); // 'completed'
console.log(status.history); // Array of status transitions

listPaymentMethods

Lists available payment methods for a given country and currency across all configured providers.
async listPaymentMethods(
  country: string,
  currency: string
): Promise<PaymentMethodInfo[]>
country
string
required
ISO 3166-1 alpha-2 country code (e.g., “US”, “BR”)
currency
string
required
ISO 4217 currency code (e.g., “USD”, “BRL”)
PaymentMethodInfo[]
array
Array of available payment methods

Example

const methods = await client.listPaymentMethods('BR', 'BRL');

for (const method of methods) {
  console.log(`${method.name} via ${method.provider}`);
}
// Output:
// PIX via stripe
// Boleto via dlocal
// Card via stripe

handleWebhook

Processes incoming webhook events from payment providers.
async handleWebhook(
  provider: string,
  payload: Buffer | string,
  headers: Record<string, string>
): Promise<VaultEvent>
provider
string
required
The provider name (must match a configured provider)
payload
Buffer | string
required
Raw webhook payload from the provider
headers
Record<string, string>
required
HTTP headers from the webhook request (used for signature verification)
VaultEvent
object
Normalized webhook event

Example

import express from 'express';

const app = express();

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  try {
    const event = await client.handleWebhook(
      'stripe',
      req.body,
      req.headers as Record<string, string>
    );
    
    console.log('Webhook event:', event.type);
    
    if (event.type === 'payment.completed') {
      // Handle successful payment
      console.log('Payment completed:', event.transactionId);
    }
    
    res.json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(400).send('Webhook processing failed');
  }
});

Error Handling

All VaultClient methods may throw the following error types:
  • VaultConfigError - Configuration validation errors
  • VaultRoutingError - Provider routing errors
  • VaultProviderError - Provider-specific errors (mapped from provider SDKs)
  • VaultNetworkError - Network and timeout errors
  • VaultIdempotencyConflictError - Idempotency key conflicts
import { VaultError, VaultRoutingError } from '@vaultsaas/core';

try {
  const result = await client.charge(request);
} catch (error) {
  if (error instanceof VaultRoutingError) {
    console.error('No provider available:', error.message);
  } else if (error instanceof VaultError) {
    console.error('Vault error:', error.code, error.message);
  } else {
    throw error;
  }
}

Implementation Details

Provider Resolution

For charge and authorize operations, VaultClient resolves the provider in this order:
  1. Forced provider - If request.routing.provider is specified
  2. Platform routing - If platformApiKey is configured, queries the VaultSaaS platform
  3. Local routing rules - Evaluates local routing rules based on currency, country, amount, etc.
  4. Fallback provider - Uses the highest-priority provider
For capture, refund, void, and getStatus, the client reuses the provider from the original transaction.

Idempotency

All payment operations (charge, authorize, capture, refund, void) support idempotency via the idempotencyKey parameter. When provided:
  • Duplicate requests with the same key return the cached result
  • Requests with the same key but different payloads throw VaultIdempotencyConflictError
  • Records expire after config.idempotency.ttlMs (default: 24 hours)

Platform Reporting

When platformApiKey is configured, VaultClient automatically reports:
  • Transaction metrics (amount, status, latency, provider)
  • Webhook events
  • Routing decisions
Reporting is asynchronous and does not block payment operations.

Build docs developers (and LLMs) love