react-native-snapmint3
v2.0.3-rc.6
Published
React Native package for Snapmint payment integration with EMI widget components and enhanced callback-based API
Maintainers
Readme
react-native-snapmint3
A React Native package that provides Snapmint payment integration with EMI widget components and native checkout functionality. Features enhanced callback-based API with comprehensive error handling and debugging support.
🚀 Features
- Enhanced Payment Integration: Native checkout with dynamic URL support and callback-based API
- Comprehensive Error Handling: Detailed error reporting with timeout protection
- EMI Widget Component: Interactive EMI calculator with custom styling
- Dynamic API Integration: Fetch EMI data from Snapmint merchant API
- Custom Font Support: Full font family and size customization
- TypeScript Support: Complete TypeScript definitions included
- Advanced Debugging: Detailed logging and event emitter validation
- Promise & Callback Support: Flexible API supporting both Promise and callback patterns
📦 Installation
Install the package and required peer dependency:
# Using npm
npm install react-native-snapmint3 react-native-webview --save
# Or using yarn
yarn add react-native-snapmint3 react-native-webviewiOS (CocoaPods)
cd ios
pod install --clean-install
cd ..Notes:
- React Native (>= 0.60) supports autolinking. No manual Android linking is required.
- If you face build cache issues, clean derived data and reinstall pods.
rm -rf ~/Library/Developer/Xcode/DerivedDatacd ios && pod deintegrate && pod install --clean-install
Requirements:
- iOS 15.0+ (SnapmintMerchantSdk 1.0.12)
💳 Payment Integration
RNSnapmint3
The main checkout functionality for Snapmint payments with enhanced callback-based API.
Enhanced Callback API (Recommended)
import RNSnapmint3 from 'react-native-snapmint3';
// Enhanced callback-based payment with comprehensive error handling
const handlePayment = () => {
const checkoutUrl = "https://pay.sandbox.snapmint.com?id=53029&token=R_hR-rJMEWo_T4naTy7x&merchantId=1456&logo=null&title=null";
RNSnapmint3.openSnapmintMerchant(checkoutUrl, {
// Optional iOS-only header customization
header: {
enableHeader: true,
showTitle: true,
title: 'Checkout',
backButtonColor: '#000000',
titleColor: '#000000',
headerColor: '#FFFFFF',
},
onSuccess: (result) => {
console.log('✅ Payment successful:', result);
console.log('Status:', result.status);
console.log('Message:', result.responseMsg);
console.log('Payment ID:', result.paymentId);
console.log('Timestamp:', result.timestamp);
// Handle successful payment
Alert.alert('🎉 Payment Successful!', result.responseMsg);
},
onError: (error) => {
console.error('❌ Payment failed:', error);
console.error('Error Status:', error.status);
console.error('Error Code:', error.statusCode);
console.error('Error Message:', error.message);
// Handle payment error
Alert.alert('❌ Payment Failed', error.responseMsg || error.message);
}
});
};Promise-based API (Legacy Support)
// Promise-based approach (still supported)
const handlePaymentWithPromise = async () => {
try {
const checkoutUrl = "https://pay.sandbox.snapmint.com?id=53029&token=R_hR-rJMEWo_T4naTy7x&merchantId=1456&logo=null&title=null";
const result = await RNSnapmint3.openSnapmintMerchant(checkoutUrl);
if (result.status === 'success') {
console.log('Payment successful:', result.message);
} else {
console.log('Payment failed:', result.message);
}
} catch (error) {
console.error('Payment error:', error);
}
};RNSnapmint3 Methods
| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| openSnapmintMerchant | checkoutUrl: string, options?: PaymentOptions | Promise<PaymentResult> | Opens Snapmint payment checkout with enhanced error handling |
PaymentOptions Interface
interface PaymentOptions {
onSuccess?: (result: PaymentResult) => void; // Success callback
onError?: (error: PaymentError) => void; // Error callback
// iOS-only header customization
header?: {
enableHeader?: boolean;
showTitle?: boolean;
title?: string;
backButtonColor?: string; // #RRGGBB or #AARRGGBB
titleColor?: string; // #RRGGBB or #AARRGGBB
headerColor?: string; // #RRGGBB or #AARRGGBB
};
}PaymentResult Interface
interface PaymentResult {
status: string; // 'success' | 'failure'
statusCode: number; // HTTP status code (200 for success)
message: string; // Human readable message
responseMsg: string; // Response message
paymentId?: string; // Payment ID (if available)
timestamp: string; // ISO timestamp of the result
}PaymentError Interface
interface PaymentError {
status: string; // 'failure'
statusCode: number; // HTTP status code (300, 400, 408, etc.)
message: string; // Human readable error message
responseMsg: string; // Response error message
timestamp: string; // ISO timestamp of the error
}🎨 EMI Widget Component
RNSnapmintButton
Interactive EMI widget component that fetches data from Snapmint API and displays EMI options.
import { RNSnapmintButton } from 'react-native-snapmint3';
// Basic usage
<RNSnapmintButton
amount="5000"
merchantPath="1616/snap_ketch.json"
onPress={() => console.log('EMI widget clicked')}
/>
// With custom styling
<RNSnapmintButton
amount="5000"
merchantPath="1616/snap_ketch.json"
fontFamily={{
fontFamily: 'Inter-Regular',
fontMultiplier: 15
}}
buttonWidth={300}
disablePopup={false}
/>RNSnapmintButton Props
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| amount | string | ✅ | - | Order amount for EMI calculation |
| merchantPath | string | ❌ | - | Merchant config path (e.g., "1616/snap_ketch.json") - NEW |
| jsonUrl | string | ❌ | - | Full URL for merchant config (deprecated, use merchantPath) |
| fontFamily | object | ❌ | {fontFamily: 'Inter-Regular', fontMultiplier: 15} | Font configuration |
| buttonWidth | number | ❌ | 90% of screen width | Custom button width |
| disablePopup | boolean | ❌ | false | Disable EMI popup modal |
Reference implementation: see
TestProject/App.tsxfor real usage wiring ofRNSnapmintButtonand the checkout callbacks.
FontFamily Object
interface FontFamily {
fontFamily: string; // Font family name
fontMultiplier: number; // Font size multiplier
}Ref Methods
The component exposes several methods via ref:
const buttonRef = useRef();
// Available methods
buttonRef.current.showSnapmintEmiInfo(orderValue, merchantLink);
buttonRef.current.openModal();
buttonRef.current.closeModal();
buttonRef.current.getEmiData();
buttonRef.current.getCalculatedAmounts();
buttonRef.current.isLoading();🔧 API Integration
Merchant Path Structure
The component uses the Snapmint merchant API with the following structure:
- Base URL:
https://merchant-js.snapmint.com/ - Endpoint:
assets/merchant/{merchantPath} - Full URL:
https://merchant-js.snapmint.com/assets/merchant/{merchantPath}
Example Merchant Paths
// Standard merchant
merchantPath="1616/snap_ketch.json"
// Titan merchant
merchantPath="4858/snap_titan.json"
// Custom merchant
merchantPath="your-merchant-id/your-config.json"🎨 UI Components
Components.Card
A styled card component for displaying content.
import { Components } from 'react-native-snapmint3';
<Components.Card
title="EMI Options"
cardStyle={{ backgroundColor: '#f5f5f5' }}
>
<Text>Your EMI options will appear here</Text>
</Components.Card>Components.MultiplyButton
A utility component for mathematical operations.
<Components.MultiplyButton
defaultValueA="5"
defaultValueB="3"
title="Calculate"
onResult={(result) => console.log(`Result: ${result}`)}
/>🚀 Enhanced Features
Advanced Error Handling
- Comprehensive Error Reporting: Detailed error information with status codes and messages
- Timeout Protection: 5-minute timeout to prevent hanging payment sessions
- Automatic Cleanup: Event listeners and resources are automatically cleaned up
- Bridge Testing: Native module bridge connection is validated before payment
Debugging Support
- Detailed Logging: Comprehensive console logging with emoji indicators
- Event Emitter Validation: Event emitter setup is validated and tested
- Bridge Connection Testing: Native module bridge is tested before payment initiation
- Manual Event Testing: Support for manual event emission for debugging
API Flexibility
- Dual API Support: Both Promise-based and callback-based APIs
- Enhanced Callbacks: Rich callback functions with detailed result/error objects
- TypeScript Support: Complete type definitions for all interfaces
- Backward Compatibility: Legacy Promise API still supported
🔄 Migration Guide (v1.x → v2.0)
Breaking Changes
- Renamed Main Class:
IndusBitCheckout→RNSnapmintCheckout - Removed Component:
RNSnapmintButtonGoldhas been removed - New Required Parameter:
openSnapmintMerchant()now requirescheckoutUrlparameter - Package renamed:
indusbit-math→react-native-snapmint3
Migration Steps
Before (v1.x)
// Old usage
import IndusBitCheckout from 'indusbit-math';
await IndusBitCheckout.openSnapmintMerchant();After (v2.0)
import RNSnapmint3 from 'react-native-snapmint3';
// Enhanced Payment with callbacks
RNSnapmint3.openSnapmintMerchant(checkoutUrl, {
onSuccess: (result) => console.log('Success:', result),
onError: (error) => console.error('Error:', error)
});
// EMI Button (use standard button)
<RNSnapmintButton
amount="5000"
merchantPath="1616/snap_ketch.json"
/>📱 Example Usage
Complete Example with Enhanced API
import React, { useRef, useState } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import RNSnapmint3, { RNSnapmintButton } from 'react-native-snapmint3';
const App = () => {
const emiButtonRef = useRef();
const [paymentStatus, setPaymentStatus] = useState('idle');
const handlePayment = () => {
setPaymentStatus('processing');
const checkoutUrl = "https://pay.sandbox.snapmint.com?id=53029&token=R_hR-rJMEWo_T4naTy7x&merchantId=1456";
RNSnapmint3.openSnapmintMerchant(checkoutUrl, {
header: {
enableHeader: true,
showTitle: true,
title: 'Checkout',
backButtonColor: '#000000',
titleColor: '#000000',
headerColor: '#FFFFFF',
},
onSuccess: (result) => {
console.log('✅ Payment successful:', result);
setPaymentStatus('success');
Alert.alert(
'🎉 Payment Successful!',
`Status: ${result.status}\nMessage: ${result.responseMsg}\nPayment ID: ${result.paymentId || 'N/A'}`,
[{ text: 'OK', style: 'default' }]
);
},
onError: (error) => {
console.error('❌ Payment failed:', error);
setPaymentStatus('error');
Alert.alert(
'❌ Payment Failed',
`Status: ${error.status}\nMessage: ${error.responseMsg}\nCode: ${error.statusCode}`,
[{ text: 'OK', style: 'destructive' }]
);
}
});
};
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 18, marginBottom: 20 }}>
Payment Status: {paymentStatus.toUpperCase()}
</Text>
<TouchableOpacity
onPress={handlePayment}
style={{
backgroundColor: '#007AFF',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginBottom: 20
}}
>
<Text style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>
💳 Start Payment
</Text>
</TouchableOpacity>
<RNSnapmintButton
ref={emiButtonRef}
amount="5000"
merchantPath="1616/snap_ketch.json"
fontFamily={{
fontFamily: 'Inter-Regular',
fontMultiplier: 15
}}
/>
</View>
);
};🔧 TypeScript Support
The package includes complete TypeScript definitions:
import RNSnapmint3, {
RNSnapmintButton,
PaymentResult,
PaymentError,
PaymentOptions,
RNSnapmintButtonProps
} from 'react-native-snapmint3';📋 Requirements
- React Native >= 0.66.0
- React >= 16.8.0
- react-native-webview >= 11.26.0
- react-native-render-html >= 6.3.0
🔍 Debugging
Console Logging
The package provides comprehensive console logging with emoji indicators:
- 🏁 App lifecycle events
- 📦 Module loading and availability
- 🚀 Payment flow initiation
- ✅ Success events
- ❌ Error events
- 🧪 Debug and testing events
- ⏰ Timeout events
- 🧹 Cleanup events
Event Emitter Testing
The package automatically tests the event emitter setup and provides debugging information for troubleshooting.
📄 License
MIT
🤝 Contributing
Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
📞 Support
For support and questions, please open an issue on GitHub or contact the development team.
📈 Changelog
v2.0.0
- ✨ Enhanced callback-based API with comprehensive error handling
- 🔧 Improved timeout protection (5-minute timeout)
- 🐛 Better error reporting with detailed status codes
- 🧪 Enhanced debugging support with detailed logging
- 🔄 Automatic cleanup of event listeners and resources
- 🧪 Native module bridge testing and validation
- 📝 Complete TypeScript definitions
- 🎨 Improved UI components and styling
- 🔄 Backward compatibility with Promise-based API
