React integration for Interswitch WebPay payment gateway
npm install react-isw-webpay

A modern React library for integrating Interswitch WebPay payment gateway into your React applications.
- ✅ 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
``bash`
npm install react-isw-webpay
`bash`
yarn add react-isw-webpay
`tsx
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: 'customer@email.com',
currency: 566, // NGN
mode: 'TEST',
site_redirect_url: "https://google.com/",
onComplete: (response) => {
setResult(✅ Payment successful! Ref: ${response.payRef});
setShowModal(false);
}
};
return (
{result &&
onClose={() => setShowModal(false)}
paymentRequest={paymentRequest}
options={{
onSuccess: (response) => {
setResult(✅ Payment successful! Ref: ${response.payRef});❌ Payment failed: ${error.desc}
setShowModal(false);
},
onError: (error) => {
setResult();
},
onCancel: () => {
setResult('⚠️ Payment cancelled');
setShowModal(false);
}
}}
/>
$3
`tsx
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: 'user@example.com',
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 (
onClick={handlePayment}
disabled={isLoading}
>
{isLoading ? 'Processing...' : 'Pay ₦100.00'}
);
}
`📚 API Reference
$3
####
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 |####
Pre-built button component with payment integration.$3
####
useWebPay()
Hook for direct payment integration.`tsx
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.$3
####
generateTransactionRef(prefix?)
Generates unique transaction reference.`tsx
const txn_ref = generateTransactionRef('order');
`####
validatePaymentRequest(request)
Validates payment request data.`tsx
const validation = validatePaymentRequest(paymentRequest);
// Returns: { isValid: boolean, errors: string[] }
`####
formatAmount(amount, currency?, locale?)
Formats amount for display.`tsx
const formatted = formatAmount(5000, 566); // "₦50.00"
`🏗️ Payment Request Structure
`tsx
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
$3
`tsx
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}
/>
`$3
`tsx
import { useWebPayModal } from 'react-isw-webpay';function CustomPaymentUI() {
const modalState = useWebPayModal({
isOpen: showModal,
onClose: () => setShowModal(false),
paymentRequest,
options
});
return (
{modalState.isLoading ? (
) : modalState.error ? (
) : (
)}
);
}
`💡 Best Practices
$3
`tsx
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
};
`$3
`tsx
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
`tsx
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);
}
};
``- ⚠️ 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
Check out complete examples in our examples directory:
- Basic E-commerce Integration
- Subscription Payment
- Custom UI Implementation
- Next.js Integration
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
- 📧 Email: ezemanneka28@gmail.com
- 🐛 Issues: GitHub Issues
- 📚 Documentation: Full Documentation