PaymentClient API Reference

The PaymentClient is the main entry point for FundKit integration. It provides a unified interface to interact with multiple payment providers.

Constructor

new PaymentClient(config)

Creates a new PaymentClient instance with provider configurations. Parameters:
  • config (PaymentClientConfig): Configuration object
Example:
import { PaymentClient } from '@fundkit/core';
import { HoneyCoin } from '@fundkit/honeycoin';
import { EasyPay } from '@fundkit/easypay';

const honeycoin = new HoneyCoin({
  apiKey: process.env.HONEYCOIN_API_KEY!,
  publicKey: process.env.HONEYCOIN_PUBLIC_KEY!,
});

const easypay = new EasyPay({
  apiKey: process.env.EASYPAY_SECRET!,
  clientId: process.env.EASYPAY_CLIENT_ID!,
});

const client = new PaymentClient({
  apiKey: process.env.FUNDKIT_API_KEY!,
  providers: [honeycoin, easypay],
  environment: 'sandbox',
  webhook: {
    url: 'https://api.myapp.com/webhooks/fundkit',
    secret: process.env.WEBHOOK_SECRET!,
  },
});
Configuration Options:
interface PaymentClientConfig {
  apiKey: string;                    // Required: Your FundKit API key
  providers: BaseProvider[];         // Required: Array of provider instances
  environment?: 'sandbox' | 'production'; // Default: 'sandbox'
  timeout?: number;                   // Request timeout in milliseconds
  retries?: number;                   // Number of retry attempts
  webhook?: {                         // Optional: Webhook configuration
    url: string;                      // Webhook endpoint URL
    secret: string;                   // Webhook secret for signature verification
  };
  logger?: Logger;                    // Custom logger instance
}

Methods

collect(request)

Initiates a payment collection request using the best available provider. Parameters:
  • request (CollectionRequest): Payment collection details
Returns: Promise<PayClientCollectionResponse> Example:
const result = await client.collect({
  amount: 10000,
  currency: 'UGX',
  phoneNumber: '+256701234567',
  reason: 'Payment for order #12345',
  reference: 'order-12345'
});

console.log(result.provider); // 'honeycoin'
console.log(result.data.transactionId); // 'tx-abc123'
Request Schema:
interface CollectionRequest {
  amount: number;          // Amount in minor currency units
  currency: string;        // ISO currency code
  phoneNumber: string;     // International format
  reason: string;          // Payment description
  reference?: string;      // Optional external reference
  metadata?: object;       // Optional metadata
}
Response Schema:
interface PayClientCollectionResponse {
  provider: string;        // Selected provider name
  data: CollectionResponse;
}

interface CollectionResponse {
  transactionId: string;   // Provider transaction ID
  status: TransactionStatus;
  amount: number;
  currency: string;
  phoneNumber: string;
  reference?: string;
  metadata?: object;
  createdAt: string;       // ISO timestamp
}
Validation Rules:
  • amount: Must be positive integer
  • currency: Must be supported by at least one provider
  • phoneNumber: Must be valid international format
  • reason: Required, minimum 3 characters

checkTransactionStatus(transactionId, provider?)

Checks the current status of a transaction. Parameters:
  • transactionId (string): Transaction ID to check
  • provider (string, optional): Specific provider to query
Returns: Promise<PayClientTransactionResponse> Example:
const status = await client.checkTransactionStatus(
  'tx-abc123',
  'honeycoin'
);

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

getAvailableProviders()

Returns list of configured and available providers. Returns: string[] Example:
const providers = client.getAvailableProviders();
console.log(providers); // ['honeycoin', 'easypay', 'tola']

getProviderCurrencies(provider?)

Returns supported currencies for a provider or all providers. Parameters:
  • provider (string, optional): Specific provider name
Returns: string[] | Record<string, string[]> Example:
// Get currencies for specific provider
const honeycoinCurrencies = client.getProviderCurrencies('honeycoin');
console.log(honeycoinCurrencies); // ['UGX', 'KES', 'TZS']

// Get currencies for all providers
const allCurrencies = client.getProviderCurrencies();
console.log(allCurrencies);
// {
//   honeycoin: ['UGX', 'KES', 'TZS'],
//   easypay: ['UGX'],
//   tola: ['UGX']
// }

validateRequest(request)

Validates a collection request without executing it. Parameters:
  • request (CollectionRequest): Request to validate
Returns: ValidationResult Example:
const validation = client.validateRequest({
  amount: -100, // Invalid
  currency: 'USD', // Unsupported
  phoneNumber: 'invalid',
  reason: ''
});

if (!validation.isValid) {
  console.log(validation.errors);
  // [
  //   { field: 'amount', message: 'Amount must be positive' },
  //   { field: 'currency', message: 'Currency USD not supported' },
  //   { field: 'phoneNumber', message: 'Invalid phone number format' },
  //   { field: 'reason', message: 'Reason is required' }
  // ]
}

Events

The PaymentClient extends EventEmitter and emits various events during operation.

Event: transaction:created

Emitted when a new transaction is created.
client.on('transaction:created', (data) => {
  console.log('Transaction created:', data.transactionId);
});

Event: transaction:updated

Emitted when a transaction status changes.
client.on('transaction:updated', (data) => {
  console.log('Status changed:', data.status);
});

Event: provider:selected

Emitted when a provider is selected for a transaction.
client.on('provider:selected', (data) => {
  console.log('Selected provider:', data.provider);
});

Event: error

Emitted when an error occurs.
client.on('error', (error) => {
  console.error('Payment error:', error.message);
});

Webhook Configuration

Webhooks are configured at the PaymentClient level, providing a unified webhook endpoint for all providers.

Webhook Configuration

const client = new PaymentClient({
  apiKey: process.env.FUNDKIT_API_KEY!,
  providers: [honeycoin, easypay],
  webhook: {
    url: 'https://api.myapp.com/webhooks/fundkit',
    secret: process.env.WEBHOOK_SECRET!,
  },
});

Webhook Event Structure

All webhook events follow this unified structure:
interface WebhookEvent {
  event: 'transaction_completed' | 'transaction_failed' | 'transaction_pending';
  data: {
    transactionId: string;
    transactionType: 'COLLECTION' | 'PAYOUT';
    amount: string;
    currency: string;
    operator: string;
    accountNumber: string;
    externalId: string;
    environment: 'sandbox' | 'production';
  };
}

Webhook Headers

Webhook requests include the following headers:
  • X-Webhook-Signature: HMAC-SHA256 signature
  • X-Webhook-Timestamp: Unix timestamp for replay attack prevention

Error Handling

All methods can throw the following error types:

ValidationError

Thrown when request validation fails.
try {
  await client.collect(invalidRequest);
} catch (error) {
  if (error.name === 'ValidationError') {
    console.log('Validation failed:', error.details);
  }
}

ProviderError

Thrown when a provider API call fails.
try {
  await client.collect(request);
} catch (error) {
  if (error.name === 'ProviderError') {
    console.log('Provider failed:', error.provider, error.message);
  }
}

ConfigurationError

Thrown when client configuration is invalid.
try {
  const client = new PaymentClient({});
} catch (error) {
  if (error.name === 'ConfigurationError') {
    console.log('Config error:', error.message);
  }
}

Type Definitions

TransactionStatus

type TransactionStatus = 
  | 'pending'
  | 'processing' 
  | 'completed'
  | 'failed'
  | 'cancelled'
  | 'expired';

CurrencyCode

type CurrencyCode = 'UGX' | 'KES' | 'TZS' | 'RWF';

ProviderName

type ProviderName = 'honeycoin' | 'easypay' | 'tola';