npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@charleslit/payment-gateway-kenya

v1.0.0

Published

A flexible payment gateway package for Kenya supporting multiple payment providers

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-kenya

Quick 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=production
import { 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 | undefined
  • getProviders(): PaymentProvider[]

Payment Methods

Supported payment methods:

  • MPESA - M-Pesa mobile money
  • Card - Credit/Debit card payments
  • Bank - Bank transfer
  • Cash - Cash on delivery

Payment Status

  • PENDING - Payment initiated but not completed
  • COMPLETED - Payment successful
  • FAILED - Payment failed
  • CANCELLED - Payment cancelled
  • PENDING_COD - Cash on delivery order created
  • UNKNOWN - 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].