@charleslit/payment-gateway-kenya
v1.0.0
Published
A flexible payment gateway package for Kenya supporting multiple payment providers
Maintainers
Readme
Payment Gateway Kenya
A flexible, TypeScript-first payment gateway package for Kenya supporting multiple payment providers including Pesapal, M-Pesa, and more.
Features
- 🏦 Multiple Payment Providers - Currently supports Pesapal with easy extensibility for more providers
- 💳 Multiple Payment Methods - M-Pesa, Card payments, Bank transfers, and Cash on Delivery
- 🔒 Type Safe - Full TypeScript support with comprehensive type definitions
- 🔧 Configurable - Environment-based configuration with validation
- 🔌 Extensible - Plugin architecture for adding new payment providers
- 📊 Database Integration - Optional Supabase integration for transaction storage
- 🚀 Framework Agnostic - Works with any Node.js framework (Express, Next.js, etc.)
Installation
npm install @photon-power/payment-gateway-kenyaQuick Start
Basic Setup
import { PaymentGateway, createPesapalConfig } from '@photon-power/payment-gateway-kenya';
// Create configuration
const config = createPesapalConfig(
'your-pesapal-consumer-key',
'your-pesapal-consumer-secret',
{
callbackUrl: 'https://your-domain.com/api/payments/callback',
ipnId: 'your-pesapal-ipn-id',
currency: 'KES'
}
);
// Initialize payment gateway
const paymentGateway = new PaymentGateway(config);Environment Variables Setup
# Pesapal Configuration
PESAPAL_CONSUMER_KEY=your_consumer_key
PESAPAL_CONSUMER_SECRET=your_consumer_secret
PESAPAL_BASE_URL=https://pay.pesapal.com/v3
PESAPAL_CALLBACK_URL=https://your-domain.com/api/payments/callback
PESAPAL_IPN_ID=your_ipn_id
# General Configuration
CURRENCY=KES
NODE_ENV=productionimport { createPaymentGatewayFromEnv } from '@photon-power/payment-gateway-kenya';
// Create gateway from environment variables
const paymentGateway = createPaymentGatewayFromEnv();Usage Examples
Initiating a Payment
import { PaymentRequest } from '@photon-power/payment-gateway-kenya';
const paymentRequest: PaymentRequest = {
customer: {
fullName: 'John Doe',
email: '[email protected]',
phone: '+254700000000',
address: '123 Main St',
city: 'Nairobi',
county: 'Nairobi',
postalCode: '00100'
},
paymentMethod: 'MPESA',
items: [
{
id: 'item-1',
name: 'Solar Panel',
price: 15000,
quantity: 1
}
],
totals: {
subtotal: 15000,
shipping: 500,
tax: 2325,
total: 17825
},
acceptedPolicyHashes: {
'privacy': 'hash123',
'terms': 'hash456'
}
};
try {
const response = await paymentGateway.initiatePayment(paymentRequest);
if (response.success) {
if (response.redirectUrl) {
// Redirect user to payment page
console.log('Redirect to:', response.redirectUrl);
} else if (response.cod) {
// Handle cash on delivery
console.log('Cash on delivery order created');
}
}
} catch (error) {
console.error('Payment initiation failed:', error);
}Verifying a Payment
try {
const verification = await paymentGateway.verifyPayment('order-tracking-id');
console.log('Payment Status:', verification.status);
console.log('Payment Method:', verification.paymentMethod);
console.log('Amount:', verification.amount);
} catch (error) {
console.error('Payment verification failed:', error);
}Handling Payment Callbacks
// Express.js example
app.post('/api/payments/callback', async (req, res) => {
try {
const result = await paymentGateway.handleCallback(req.body, 'pesapal');
// Update your application state based on payment status
console.log('Payment callback processed:', result);
res.status(200).send('OK');
} catch (error) {
console.error('Callback processing failed:', error);
res.status(500).send('ERROR');
}
});Configuration
Complete Configuration Example
import { PaymentGatewayConfig } from '@photon-power/payment-gateway-kenya';
const config: PaymentGatewayConfig = {
providers: {
pesapal: {
name: 'pesapal',
enabled: true,
credentials: {
consumerKey: 'your-consumer-key',
consumerSecret: 'your-consumer-secret',
baseUrl: 'https://pay.pesapal.com/v3',
callbackUrl: 'https://your-domain.com/callback',
ipnId: 'your-ipn-id'
},
settings: {
currency: 'KES',
timeout: 10000
}
}
},
database: {
client: supabaseClient, // Optional: Supabase client for transaction storage
transactionsTable: 'transactions'
},
currency: 'KES',
environment: 'production'
};Database Integration (Optional)
If you want automatic transaction storage, provide a Supabase client:
import { createClient } from '@supabase/supabase-js';
const supabaseClient = createClient(
'your-supabase-url',
'your-supabase-service-role-key'
);
const config = {
// ... other config
database: {
client: supabaseClient,
transactionsTable: 'transactions' // optional, defaults to 'transactions'
}
};API Reference
PaymentGateway
Main class for handling payments.
Methods
initiatePayment(request: PaymentRequest, preferredProvider?: string): Promise<PaymentResponse>verifyPayment(orderTrackingId: string, providerName?: string): Promise<PaymentVerificationResponse>handleCallback(callbackData: any, providerName: string): Promise<PaymentVerificationResponse>getProvider(name: string): PaymentProvider | undefinedgetProviders(): PaymentProvider[]
Payment Methods
Supported payment methods:
MPESA- M-Pesa mobile moneyCard- Credit/Debit card paymentsBank- Bank transferCash- Cash on delivery
Payment Status
PENDING- Payment initiated but not completedCOMPLETED- Payment successfulFAILED- Payment failedCANCELLED- Payment cancelledPENDING_COD- Cash on delivery order createdUNKNOWN- Status unknown
Adding New Payment Providers
To add a new payment provider, extend the PaymentProvider base class:
import { PaymentProvider } from '@photon-power/payment-gateway-kenya';
export class MyCustomProvider extends PaymentProvider {
getSupportedPaymentMethods() {
return ['MPESA', 'Card'];
}
async initiatePayment(request) {
// Implementation
}
async verifyPayment(orderTrackingId) {
// Implementation
}
validateConfig() {
// Validate configuration
}
getRequiredConfigFields() {
return ['apiKey', 'secretKey'];
}
}Error Handling
The package provides specific error types:
import { PaymentGatewayError, ValidationError, ProviderError } from '@photon-power/payment-gateway-kenya';
try {
await paymentGateway.initiatePayment(request);
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation failed:', error.validationErrors);
} else if (error instanceof ProviderError) {
console.log('Provider error:', error.provider, error.message);
} else if (error instanceof PaymentGatewayError) {
console.log('Gateway error:', error.code, error.message);
}
}License
MIT
Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
Support
For support, please open an issue on our GitHub repository or contact us at [email protected].
