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

pesapal-v3-node

v1.1.0

Published

A production-ready **Node.js / TypeScript SDK** for integrating with the Pesapal API 3.0.

Downloads

719

Readme

Pesapal Node.js SDK

A production-ready Node.js / TypeScript SDK for integrating with the Pesapal API 3.0.

This SDK provides a clean, typed, and extensible interface for handling payments, IPN (Instant Payment Notifications), and transaction status—designed with modern best practices like retries, logging, and modular architecture.


✨ Features

  • ✅ Full TypeScript support (typed requests & responses)
  • 🔐 Built-in automatic authentication with intelligent token caching
  • 🔁 Automatic retries with exponential backoff for transient failures
  • 🛡️ Client-side validation for orders and IPNs (fail-fast)
  • 🧾 Structured resources (Orders, IPN)
  • 🔌 IPN Security Utilities (Signature verification & parsing)
  • 🪵 Pluggable logging hooks
  • 🌍 Sandbox & Live environment support
  • 🧪 Comprehensive test suite and CI/CD ready
  • 📃 JSDoc on all methods

🔐 Security Note

[!WARNING] NEVER commit your .env file or hardcode live credentials in your source code. Always use environment variables to store your consumerKey and consumerSecret. Ensure .env is included in your .gitignore file.


📦 Installation

npm install pesapal-v3-node

🚀 Quick Start

import { Pesapal } from 'pesapal-v3-node';

const pesapal = new Pesapal({
  consumerKey: process.env.PESAPAL_CONSUMER_KEY!,
  consumerSecret: process.env.PESAPAL_CONSUMER_SECRET!,
  environment: 'sandbox', // or 'live'
});

// 1. Register IPN URL (Optional if you already have an ipn_id)
const ipn = await pesapal.ipn.registerIPNUrl({
  url: 'https://your-app.com/ipn',
  ipn_notification_type: 'POST',
});

// 2. Submit an Order
const order = await pesapal.orders.submitOrder({
  id: 'ORDER-001',
  currency: 'UGX',
  amount: 100.00,
  description: 'Test payment',
  callback_url: 'https://your-app.com/callback',
  notification_id: ipn.ipn_id, // Use the ipn_id from step 1
  billing_address: {
    email_address: '[email protected]',
    phone_number: '0700000000',
    first_name: 'John',
    last_name: 'Doe',
  },
});

console.log('Redirect URL:', order.redirect_url);

// 3. Check Transaction Status
const status = await pesapal.orders.getStatus(order.order_tracking_id);
console.log('Status:', status.status);

⚙️ Configuration

const pesapal = new Pesapal({
  consumerKey: '...',
  consumerSecret: '...',
  environment: 'sandbox', // Default: sandbox
  retries: 3,            // Number of retries for transient failures (Default: 2)
  timeoutMs: 10000,      // Request timeout in milliseconds (Default: 10000)
  logger: console,       // Optional logger (debug, info, warn, error)
});

📚 API Reference

Orders (pesapal.orders)

Submit Order

Initiates a transaction and returns a redirect URL. Includes client-side validation.

await pesapal.orders.submitOrder(payload: SubmitOrderRequest);

Get Transaction Status

Checks the status of a transaction using its tracking ID.

await pesapal.orders.getStatus(orderTrackingId: string);

IPN (pesapal.ipn)

Register IPN URL

Registers a URL to receive Instant Payment Notifications. Returns an ipn_id.

await pesapal.ipn.registerIPNUrl({
  url: 'https://example.com/ipn',
  ipn_notification_type: 'POST',
});

Handle IPN Webhooks (Security)

The SDK provides helpers to securely parse and verify IPN notifications from Pesapal.

import { verifyIPNSignature, parseIPN } from 'pesapal-v3-node';

// In your webhook controller (e.g., Express)
app.post('/ipn', (req, res) => {
    const rawBody = JSON.stringify(req.body);
    const signature = req.headers['x-pesapal-signature']; // Placeholder header name
    
    // 1. Verify it came from Pesapal
    const isValid = verifyIPNSignature(signature, rawBody, process.env.PESAPAL_CONSUMER_SECRET);
    
    if (isValid) {
        // 2. Parse into a typed object
        const ipnData = parseIPN(req.body);
        console.log(`Update for Order: ${ipnData.OrderTrackingId}`);
    }
    
    res.sendStatus(200);
});

🔁 Retries & Performance

Token Caching

The SDK automatically caches your authentication token and only requests a new one when the current one is near expiry. This eliminates unnecessary network round-trips.

Automatic Retries

The SDK automatically retries requests that fail due to network issues, 5xx errors, or rate limiting (429).

Normalised Errors

All errors are caught and thrown as PesapalError:

import { PesapalError } from 'pesapal-v3-node';

try {
  await pesapal.orders.submitOrder(payload);
} catch (err) {
  if (err instanceof PesapalError) {
    console.error(`Error: ${err.message} (Code: ${err.code}, Status: ${err.status})`);
  }
}

🧪 Development & Testing

# Run tests
npm test

# Build project
npm run build

# Run full validation
npm run prepublishOnly

📁 Project Structure

src/
  index.ts        # Main entry point & IPN utilities
  client.ts       # Core HTTP client with Auth integration
  auth.ts         # Authentication logic & token caching
  orders.ts       # Order resource with validation
  ipn.ts          # IPN resource with validation
  errors.ts       # Error normalization
  helpers/
    ipn.ts        # IPN signature verification & parsing
    retries.ts    # Retry logic
  types/
    types.ts      # TypeScript definitions

📄 License

MIT License