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

react-isw-webpay

v0.0.7

Published

React integration for Interswitch WebPay payment gateway

Downloads

43

Readme

React Interswitch WebPay

npm version License: MIT

A modern React library for integrating Interswitch WebPay payment gateway into your React applications.

🚀 Features

  • Easy Integration - Simple setup with minimal configuration
  • TypeScript Support - Full type definitions included
  • Flexible UI - Customizable modal or headless integration
  • Payment Validation - Built-in validation utilities
  • Environment Support - Development, staging, and production modes
  • Modern React - Built with React hooks and modern patterns

📦 Installation

npm install react-isw-webpay
yarn add react-isw-webpay

🔧 Quick Start

1. Basic Modal Payment

import React, { useState } from 'react';
import { WebPayModal, generateTransactionRef } from 'react-isw-webpay';

function App() {
  const [showModal, setShowModal] = useState(false);
  const [result, setResult] = useState('');

  // All payment config and request fields together
  const paymentRequest = {
    merchant_code: "MX19329",
    pay_item_id: "Default_Payable_MX19329",
    txn_ref: generateTransactionRef('order'),
    amount: 5000, // Amount in kobo (₦50.00)
    cust_id: '[email protected]',
    currency: 566, // NGN
    mode: 'TEST',
    site_redirect_url: "https://google.com/",
    onComplete: (response) => {
      setResult(`✅ Payment successful! Ref: ${response.payRef}`);
      setShowModal(false);
    }
  };

  return (
    <div>
      <button onClick={() => setShowModal(true)}>
        Pay ₦50.00
      </button>

      {result && <div>{result}</div>}

      <WebPayModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        paymentRequest={paymentRequest}
        options={{
          onSuccess: (response) => {
            setResult(`✅ Payment successful! Ref: ${response.payRef}`);
            setShowModal(false);
          },
          onError: (error) => {
            setResult(`❌ Payment failed: ${error.desc}`);
          },
          onCancel: () => {
            setResult('⚠️ Payment cancelled');
            setShowModal(false);
          }
        }}
      />
    </div>
  );
}

2. Direct Payment with Hook

import React from 'react';
import { useWebPay, generateTransactionRef } from 'react-isw-webpay';

function DirectPayment() {
  const { initiatePayment, isLoading, error } = useWebPay();

  const handlePayment = () => {
    const paymentRequest = {
      merchant_code: "MX19329",
      pay_item_id: "Default_Payable_MX19329",
      txn_ref: generateTransactionRef('direct'),
      amount: 10000, // ₦100.00
      cust_id: '[email protected]',
      currency: 566,
      mode: 'TEST',
      site_redirect_url: "https://google.com/"
    };

    initiatePayment(paymentRequest, {
      onSuccess: (response) => console.log('Success:', response),
      onError: (error) => console.log('Error:', error),
      onCancel: () => console.log('Cancelled'),
    });
  };

  return (
    <button 
      onClick={handlePayment} 
      disabled={isLoading}
    >
      {isLoading ? 'Processing...' : 'Pay ₦100.00'}
    </button>
  );
}

📚 API Reference

Components

<WebPayModal />

Modal component for payment processing.

| Prop | Type | Required | Description | |------|------|----------|-------------| | isOpen | boolean | ✅ | Controls modal visibility | | onClose | () => void | ✅ | Called when modal closes | | paymentRequest | PaymentRequest | ✅ | Payment details (includes config) | | options | WebPayHookOptions | ✅ | Payment callbacks | | title | string | ❌ | Modal title | | loadingText | string | ❌ | Loading message | | className | string | ❌ | CSS class name | | style | CSSProperties | ❌ | Inline styles |

<WebPayButton />

Pre-built button component with payment integration.

Hooks

useWebPay()

Hook for direct payment integration.

const { initiatePayment, isLoading, error } = useWebPay();

Returns:

  • initiatePayment(paymentRequest, options) - Function to start payment
  • isLoading - Boolean indicating payment processing state
  • error - Error message if payment fails

useWebPayModal(props)

Headless hook for custom modal implementations.

Utilities

generateTransactionRef(prefix?)

Generates unique transaction reference.

const txn_ref = generateTransactionRef('order');

validatePaymentRequest(request)

Validates payment request data.

const validation = validatePaymentRequest(paymentRequest);
// Returns: { isValid: boolean, errors: string[] }

formatAmount(amount, currency?, locale?)

Formats amount for display.

const formatted = formatAmount(5000, 566); // "₦50.00"

🏗️ Payment Request Structure

interface PaymentRequest {
  merchant_code: string;          // Your Interswitch merchant code
  pay_item_id: string;            // Your pay item ID  
  txn_ref: string;                // Unique transaction reference
  amount: number;                 // Amount in kobo (multiply by 100)
  cust_id?: string;               // Customer ID/email
  currency?: number | string;     // Default: 566 (NGN)
  mode: 'TEST' | 'LIVE';          // Environment mode
  site_redirect_url?: string;     // Custom redirect URL
  split_accounts?: string;        // For split payments
  onComplete?: (response: any) => void; // Callback after payment
  [key: string]: any;             // Any extra fields
}

🎨 Customization Examples

Custom Styled Modal

<WebPayModal
  isOpen={showModal}
  onClose={() => setShowModal(false)}
  paymentRequest={paymentRequest}
  options={options}
  title="Secure Checkout"
  loadingText="Processing your payment securely..."
  className="my-payment-modal"
  style={{ background: 'rgba(0, 0, 0, 0.8)' }}
  LoadingComponent={MyCustomLoader}
  ErrorComponent={MyCustomError}
/>

Headless Implementation

import { useWebPayModal } from 'react-isw-webpay';

function CustomPaymentUI() {
  const modalState = useWebPayModal({
    isOpen: showModal,
    onClose: () => setShowModal(false),
    paymentRequest,
    options
  });

  return (
    <div className="my-custom-modal">
      {modalState.isLoading ? (
        <MyCustomLoader />
      ) : modalState.error ? (
        <MyCustomError error={modalState.error} onRetry={modalState.reset} />
      ) : (
        <MyCustomPaymentForm />
      )}
    </div>
  );
}

💡 Best Practices

1. Environment Configuration

const paymentRequest = {
  merchant_code: process.env.REACT_APP_INTERSWITCH_MERCHANT_CODE!,
  pay_item_id: process.env.REACT_APP_INTERSWITCH_PAY_ITEM_ID!,
  mode: process.env.NODE_ENV === 'production' ? 'LIVE' : 'TEST',
  // ...other fields
};

2. Error Handling

const handlePaymentError = (error) => {
  // Log error for debugging
  console.error('Payment error:', error);
  
  // Show user-friendly message
  setErrorMessage('Payment failed. Please try again.');
  
  // Optional: Send error to monitoring service
  // errorReporting.captureException(error);
};

3. Payment Verification

const handlePaymentSuccess = async (response) => {
  try {
    // Always verify payment on your backend
    const verification = await fetch('/api/verify-payment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        paymentRef: response.payRef,
        transactionRef: response.txnref,
        amount: response.apprAmt
      })
    });
    
    if (verification.ok) {
      handleOrderCompletion();
    } else {
      handleVerificationFailure();
    }
  } catch (error) {
    console.error('Verification error:', error);
  }
};

🔐 Security Notes

  • ⚠️ Never expose sensitive credentials in client-side code
  • Always verify payments on your backend before fulfilling orders
  • Use environment variables for configuration
  • Implement proper error logging for production monitoring

📖 Examples

Check out complete examples in our examples directory:

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🏷️ Changelog

v1.0.0

  • Initial release
  • WebPayModal component
  • useWebPay hook
  • Payment validation utilities
  • TypeScript support