react-isw-webpay
v0.0.7
Published
React integration for Interswitch WebPay payment gateway
Downloads
43
Maintainers
Readme
React Interswitch WebPay
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-webpayyarn 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 paymentisLoading- Boolean indicating payment processing stateerror- 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
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📚 Documentation: Full Documentation
🏷️ Changelog
v1.0.0
- Initial release
- WebPayModal component
- useWebPay hook
- Payment validation utilities
- TypeScript support
