@codeflex-dev/unified-payment-gateway
v1.0.4
Published
Unified payment gateway SDK supporting multiple providers (PayStack, Yoco, etc.)
Downloads
51
Maintainers
Readme
Unified Payment Gateway SDK
A centralized, reusable payment gateway SDK that supports multiple payment providers. Switch between providers (PayStack, Yoco, etc.) with a simple configuration flag - no code changes needed!
Features
- 🎯 Unified Interface - Same API for all payment providers
- 🔄 Easy Provider Switching - Change providers with a single config flag
- 📦 TypeScript Support - Full type safety and IntelliSense
- 🛡️ Type-Safe - Comprehensive TypeScript types for all operations
- 🚀 Zero Dependencies - Minimal external dependencies
- 🔌 Extensible - Easy to add new payment providers
Installation
npm install @codeflex-dev/unified-payment-gatewayOr if using as a local package in a monorepo:
npm install ./path/to/payment-gatewayQuick Start
Basic Usage
import { PaymentGatewayFactory } from '@codeflex-dev/unified-payment-gateway';
// Create gateway instance with provider flag
const gateway = PaymentGatewayFactory.create({
provider: 'paystack', // or 'yoco'
publicKey: 'pk_test_...',
secretKey: 'sk_test_...',
testMode: true,
});
// Initialize payment
const payment = await gateway.initializePayment({
amount: { value: 1000, currency: 'NGN' },
customer: { email: '[email protected]' },
description: 'Payment for order #123',
});
console.log('Payment URL:', payment.authorizationUrl);Verify Payment
const verification = await gateway.verifyPayment({
reference: 'PSK_1234567890_abc123',
});
if (verification.success) {
console.log('Payment successful!', verification.amount);
}Supported Providers
PayStack
import { PaymentGatewayFactory } from '@codeflex-dev/unified-payment-gateway';
const gateway = PaymentGatewayFactory.create({
provider: 'paystack',
publicKey: 'pk_test_...',
secretKey: 'sk_test_...',
});Yoco
import { PaymentGatewayFactory } from '@codeflex-dev/unified-payment-gateway';
const gateway = PaymentGatewayFactory.create({
provider: 'yoco',
secretKey: 'sk_test_...',
testMode: true,
});API Reference
PaymentGatewayFactory
create(config: GatewayConfig): IPaymentGateway
Creates a payment gateway instance based on the provider specified in config.
Parameters:
config.provider:'paystack' | 'yoco'- The payment provider to useconfig.secretKey:string- Secret key for the providerconfig.publicKey:string- Public key (required for PayStack)config.testMode:boolean- Enable test mode
IPaymentGateway
All gateway instances implement this interface:
initializePayment(request: PaymentRequest): Promise<PaymentResponse>
Initialize a new payment transaction.
Request:
{
amount: { value: number, currency: Currency },
customer: { email: string, firstName?: string, lastName?: string, phone?: string },
reference?: string,
description?: string,
callbackUrl?: string,
metadata?: Record<string, any>
}Response:
{
success: boolean,
transactionId: string,
reference: string,
amount: Amount,
status: PaymentStatus,
authorizationUrl?: string,
message?: string,
metadata?: Record<string, any>
}verifyPayment(request: VerifyPaymentRequest): Promise<VerifyPaymentResponse>
Verify a payment transaction status.
Request:
{
reference: string,
transactionId?: string
}Response:
{
success: boolean,
transactionId: string,
reference: string,
amount: Amount,
status: PaymentStatus,
paidAt?: Date,
customer?: Customer,
metadata?: Record<string, any>
}Usage Examples
Express.js Example
import express from 'express';
import { PaymentGatewayFactory } from '@codeflex-dev/unified-payment-gateway';
const app = express();
const gateway = PaymentGatewayFactory.create({
provider: process.env.PAYMENT_PROVIDER as 'paystack' | 'yoco',
publicKey: process.env.PAYMENT_PUBLIC_KEY!,
secretKey: process.env.PAYMENT_SECRET_KEY!,
});
app.post('/api/payments/initialize', async (req, res) => {
try {
const payment = await gateway.initializePayment({
amount: { value: req.body.amount, currency: 'NGN' },
customer: { email: req.body.email },
callbackUrl: req.body.callbackUrl,
});
res.json(payment);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/payments/verify/:reference', async (req, res) => {
try {
const verification = await gateway.verifyPayment({
reference: req.params.reference,
});
res.json(verification);
} catch (error) {
res.status(500).json({ error: error.message });
}
});Environment-Based Provider Selection
import { PaymentGatewayFactory } from '@codeflex-dev/unified-payment-gateway';
// Switch providers via environment variable
const getPaymentGateway = () => {
const provider = process.env.PAYMENT_PROVIDER || 'paystack';
return PaymentGatewayFactory.create({
provider: provider as 'paystack' | 'yoco',
publicKey: process.env[`${provider.toUpperCase()}_PUBLIC_KEY`]!,
secretKey: process.env[`${provider.toUpperCase()}_SECRET_KEY`]!,
testMode: process.env.NODE_ENV !== 'production',
});
};
const gateway = getPaymentGateway();Development
Building
npm run buildWatch Mode
npm run watchTesting
The SDK includes comprehensive integration tests using Jest.
Running Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageTest Structure
tests/integration/- Integration tests for all providersPaymentGatewayFactory.test.ts- Factory pattern testsPayStackGateway.test.ts- PayStack provider testsYocoGateway.test.ts- Yoco provider testsUnifiedInterface.test.ts- Unified interface consistency testsErrorHandling.test.ts- Error handling and edge cases
tests/utils/- Test utilities and helperstest-helpers.ts- Mock data generators and API response mocks
Test Coverage
The test suite covers:
- ✅ Provider initialization and configuration
- ✅ Payment initialization
- ✅ Payment verification
- ✅ Error handling (network, API, validation)
- ✅ Edge cases (missing data, invalid inputs)
- ✅ Unified interface consistency across providers
- ✅ Amount normalization
- ✅ Reference generation
All tests use mocked HTTP requests, so no real API calls are made during testing.
Adding New Providers
To add a new payment provider:
- Create a new class extending
BasePaymentGateway - Implement
initializePaymentandverifyPaymentmethods - Add the provider type to
PaymentProviderintypes/index.ts - Add the provider case in
PaymentGatewayFactory.create()
Example:
export class NewProviderGateway extends BasePaymentGateway {
async initializePayment(request: PaymentRequest): Promise<PaymentResponse> {
// Implementation
}
async verifyPayment(request: VerifyPaymentRequest): Promise<VerifyPaymentResponse> {
// Implementation
}
getProvider(): string {
return 'newprovider';
}
}License
ISC
Fun0D1@m!niss
