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.
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
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 >
The charge request payload Show ChargeRequest properties
Amount in smallest currency unit (e.g., cents for USD)
ISO 4217 currency code (e.g., “USD”, “BRL”)
paymentMethod
PaymentMethodInput
required
Payment method details. Can be card token, raw card, bank transfer, wallet, PIX, or boleto { type : 'card' , token : 'tok_visa' }
{
type : 'card' ,
number : '4242424242424242' ,
expMonth : 12 ,
expYear : 2025 ,
cvc : '123'
}
Customer information Show CustomerInput properties
Tax ID or national document (e.g., CPF)
Billing or shipping address
Human-readable description of the charge
Arbitrary key-value pairs forwarded to the provider
Prevents duplicate charges when retrying the same request
Per-request routing overrides Show RoutingPreference properties
Force routing to this specific provider
Provider names to exclude from selection
Normalized payment result Show PaymentResult properties
VaultSaaS-normalized transaction identifier
Payment status: completed, pending, requires_action, declined, failed, cancelled, or authorized
Name of the provider that processed the transaction (e.g., “stripe”)
Provider’s own identifier for this transaction
Amount in smallest currency unit
Snapshot of the payment method used Card brand (e.g., “visa”)
metadata
Record<string, string>
required
Merged metadata from request and provider response
How the provider was selected source
'local' | 'platform'
required
Routing source
Reason for provider selection
providerMetadata
Record<string, unknown>
required
Raw provider-specific fields not mapped to normalized schema
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 >
Authorization request payload. Identical to ChargeRequest.
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 >
Capture request payload Show CaptureRequest properties
The transaction ID returned from a prior authorize call
Partial capture amount. Omit to capture the full authorized amount
Prevents duplicate captures when retrying
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 >
Refund request payload Show RefundRequest properties
The transaction ID of the original charge or capture
Partial refund amount. Omit to refund the full amount
Human-readable reason forwarded to the provider
Prevents duplicate refunds when retrying
Normalized refund result Show RefundResult properties
The original transaction that was refunded
status
'completed' | 'pending' | 'failed'
required
Refund status
Refunded amount in smallest currency unit
Provider’s refund identifier
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 >
Void request payload Show VoidRequest properties
The transaction ID of the authorization to void
Prevents duplicate void operations when retrying
Normalized void result Show VoidResult properties
Void operation identifier
The original authorized transaction that was voided
status
'completed' | 'failed'
required
Void status
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 >
The transaction ID to query
Transaction status with history Show TransactionStatus properties
Current transaction status
Provider’s transaction identifier
Array of status change events
ISO 8601 timestamp of last update
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 [] >
ISO 3166-1 alpha-2 country code (e.g., “US”, “BR”)
ISO 4217 currency code (e.g., “USD”, “BRL”)
Array of available payment methods Show PaymentMethodInfo properties
Payment method type (e.g., “card”, “pix”, “boleto”)
Provider offering this payment method
Human-readable payment method name
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 >
The provider name (must match a configured provider)
Raw webhook payload from the provider
HTTP headers from the webhook request (used for signature verification)
Normalized webhook event Show VaultEvent properties
Event type (e.g., “payment.completed”, “payment.failed”)
Associated transaction ID if applicable
Provider’s event identifier
data
Record<string, unknown>
required
Normalized event data
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:
Forced provider - If request.routing.provider is specified
Platform routing - If platformApiKey is configured, queries the VaultSaaS platform
Local routing rules - Evaluates local routing rules based on currency, country, amount, etc.
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)
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.