nimbbl-mobile-react-native-sdk
Version: 
Nimbbl React Native SDK for payment integration
518 lines (375 loc) • 14.2 kB
Markdown
# Nimbbl React Native SDK
A comprehensive React Native SDK for integrating Nimbbl payment gateway into your mobile applications. This SDK provides a seamless bridge between React Native and native payment functionality.
## Features
- 🚀 **Easy Integration** - Simple setup and initialization
- 💳 **Multiple Payment Methods** - Support for cards, UPI, netbanking, wallets, EMI, and cash
- 🌐 **WebView Integration** - Built-in payment webview with customization options
- 🔗 **Bridge Module** - Robust native bridge for communication
- 📱 **Cross Platform** - Support for both iOS and Android
- 🛡️ **Type Safety** - Comprehensive TypeScript definitions
- 📊 **Analytics** - Built-in analytics and logging
- 🔄 **Event Handling** - Real-time payment status updates
## Installation
### Option 1: Install from npm (Recommended for production)
```bash
npm install nimbbl-mobile-react-native-sdk
# or
yarn add nimbbl-mobile-react-native-sdk
```
## Compatibility
### NPM Version Support
The Nimbbl React Native SDK is compatible with the following npm versions:
| NPM Version | Support Status | Notes |
|-------------|----------------|-------|
| `^1.0.0-alpha.0` | ✅ Supported | Initial alpha release |
| `^1.0.0-alpha.1` | ✅ Supported | Bug fixes and improvements |
| `^1.0.0-alpha.2` | ✅ Supported | Enhanced error handling |
| `^1.0.0-alpha.3` | ✅ Supported | Enhanced error handling |
| `^1.0.0-alpha.12` | ✅ Supported | Latest alpha release |
| `^1.0.0` | ✅ **Current Stable** | **Production ready** |
| `^1.1.0` | 🔄 Coming Soon | Feature updates |
| `^2.0.0` | 🔄 Coming Soon | Major version with breaking changes |
### React Native Version Support
| React Native Version | Support Status | Notes |
|----------------------|----------------|-------|
| `^0.70.0` | ✅ Supported | Minimum supported version |
| `^0.71.0` | ✅ Supported | Recommended version |
| `^0.72.0` | ✅ Supported | Recommended version |
| `^0.73.0` | ✅ Supported | Latest stable version |
| `^0.74.0` | ✅ Supported | Latest stable version |
| `^0.75.0` | ✅ Supported | Latest stable version |
| `^0.76.0` | ✅ Supported | Latest stable version |
### Node.js Version Support
| Node.js Version | Support Status | Notes |
|-----------------|----------------|-------|
| `^16.0.0` | ✅ Supported | Minimum supported version |
| `^18.0.0` | ✅ Supported | Recommended version |
| `^20.0.0` | ✅ Supported | Latest LTS version |
| `^21.0.0` | ✅ Supported | Latest stable version |
### Platform Support
| Platform | Support Status | Minimum Version |
|----------|----------------|-----------------|
| **Android** | ✅ Supported | API Level 21 (Android 5.0) |
| **iOS** | ✅ Supported | iOS 13.0+ |
### Breaking Changes
- **Alpha Releases**: Alpha versions may contain breaking changes between releases
- **Stable Releases**: Breaking changes will be clearly documented in release notes
- **Migration Guide**: Migration guides will be provided for major version updates
### Versioning Strategy
- **Alpha Releases** (`1.0.0-alpha.X`): For testing and early adoption
- **Beta Releases** (`1.0.0-beta.X`): For feature-complete testing
- **Release Candidates** (`1.0.0-rc.X`): For final testing before stable release
- **Stable Releases** (`1.0.0`, `1.1.0`, etc.): For production use
## Quick Start
### Import the SDK
The import statement depends on whether you're using the npm package or local development version:
**For npm package (production use):**
```javascript
import { NimbblSDK } from 'nimbbl-mobile-react-native-sdk';
```
### 1. Initialize the SDK
```javascript
import { NimbblSDK } from 'nimbbl-mobile-react-native-sdk';
const nimbblSDK = NimbblSDK.getSharedInstance();
// Initialize the SDK (no credentials required - matches iOS pattern)
await nimbblSDK.initialize({
  environment: 'sandbox' // or 'production'
});
```
### 2. Process Payment
```javascript
// Process payment using checkout method (matching iOS pattern)
const checkoutResult = await nimbblSDK.checkout({
  orderToken: 'YOUR_ORDER_TOKEN', // Order token received from your server
  paymentModeCode: '', // Leave empty for all payment modes
  bankCode: '', // Leave empty for all banks
  walletCode: '', // Leave empty for all wallets
  paymentFlow: '' // Leave empty for default flow (or 'phonepe', 'collect', 'intent' for UPI)
});
```
### 3. Handle Payment Status
The SDK automatically manages event listeners and handles payment status updates. You don't need to manually add or remove event listeners - the SDK handles this internally for optimal performance.
## API Reference
### NimbblSDK
The main SDK class that provides all payment functionality.
#### Methods
- `getSharedInstance()` - Get shared SDK instance (singleton pattern)
- `initialize(config)` - Initialize the SDK with configuration and auto-setup event listeners
- `checkout(options)` - Process payment with order token
- `testNativeModule()` - Test native module availability
- `addEventListener(eventName, callback)` - Add event listener (SDK manages lifecycle automatically)
- `removeEventListener(eventName, callback)` - Remove event listener
- `removeAllEventListeners()` - Remove all event listeners
### Event Handling
The SDK automatically manages event listeners for optimal performance. Event listeners are automatically set up during initialization and cleaned up when needed.
```javascript
import { NimbblSDK, EVENTS } from 'nimbbl-mobile-react-native-sdk';
const nimbblSDK = NimbblSDK.getSharedInstance();
// Initialize SDK (automatically sets up event listeners)
await nimbblSDK.initialize({
  environment: 'sandbox'
});
// Listen for payment events (SDK manages listener lifecycle)
nimbblSDK.addEventListener(EVENTS.PAYMENT_SUCCESS, (data) => {
  console.log('Payment successful:', data);
  // Handle success - navigate to success screen
});
nimbblSDK.addEventListener(EVENTS.PAYMENT_FAILED, (data) => {
  console.log('Payment failed:', data);
  // Handle failure - show error message
});
// Optional: Clean up listeners when done (SDK also handles this automatically)
// nimbblSDK.removeAllEventListeners();
```
## Configuration
### SDK Configuration
```javascript
const config = {
  environment: 'sandbox', // 'sandbox' or 'production'
  options: {
    timeout: 30000,
    enable_logging: true,
    enable_analytics: true,
    api_base_url: 'https://api.nimbbl.tech/' // Optional: override default URL
  }
};
```
## Constants
The SDK provides various constants for better development experience:
```javascript
import {
  EVENTS,
  ENVIRONMENTS,
  ERROR_CODES,
  ERROR_MESSAGES,
  DEFAULT_CONFIG,
  SDK_VERSION
} from 'nimbbl-mobile-react-native-sdk';
```
## Error Handling
```javascript
try {
  const checkoutResult = await nimbblSDK.checkout({
    orderToken: 'YOUR_ORDER_TOKEN',
    paymentModeCode: '',
    bankCode: '',
    walletCode: '',
    paymentFlow: ''
  });
} catch (error) {
  console.error('Error processing payment:', error.message);
  
  // Check error codes
  if (error.code === ERROR_CODES.PAYMENT_FAILED) {
    // Handle payment failure
  }
}
```
## Platform Setup
### iOS
1. Install pods:
```bash
cd ios && pod install
```
2. Add to your `Info.plist`:
```xml
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
```
**Note:** The iOS implementation is written in Swift for modern, type-safe development.
### Android
1. Add to your `android/app/build.gradle`:
```gradle
android {
    defaultConfig {
        minSdkVersion 21
    }
}
```
2. Add to your `android/app/src/main/AndroidManifest.xml`:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
**Note:** The Android implementation is written in Kotlin for modern, type-safe development.
## Examples
### Complete Payment Flow
```javascript
import { NimbblSDK, EVENTS } from 'nimbbl-mobile-react-native-sdk';
class PaymentManager {
  constructor() {
    this.nimbblSDK = NimbblSDK.getSharedInstance();
  }
  async initialize() {
    await this.nimbblSDK.initialize({
      environment: 'sandbox'
    });
  }
  setupEventListeners() {
    // Event listeners are automatically managed by the SDK
    // You can add custom listeners for your app's specific needs
    this.nimbblSDK.addEventListener(EVENTS.PAYMENT_SUCCESS, (data) => {
      console.log('Payment successful:', data);
      // Navigate to success screen
    });
    this.nimbblSDK.addEventListener(EVENTS.PAYMENT_FAILED, (data) => {
      console.log('Payment failed:', data);
      // Show error message
    });
  }
  async processPayment(orderToken) {
    try {
      // Process payment using the order token
      const result = await this.nimbblSDK.checkout({
        orderToken: orderToken,
        paymentModeCode: '',
        bankCode: '',
        walletCode: '',
        paymentFlow: ''
      });
      
      return { success: true, result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
}
```
## Troubleshooting
### Common Issues
#### 1. Payment Status Screen Not Opening (iOS)
**Problem**: WebView opens and closes, but payment status screen doesn't appear.
**Solution**: 
- Ensure you're using the latest SDK version (`^1.0.0`)
- The SDK automatically manages event listeners - no manual setup required
- Check that your app properly handles the payment success/failure events
#### 2. Event Listeners Not Working
**Problem**: Payment events are not being received.
**Solution**:
- The SDK automatically sets up event listeners during initialization
- Make sure to call `initialize()` before using the SDK
- Event listeners are managed internally for optimal performance
#### 3. iOS Build Issues
**Problem**: Build fails with missing native modules.
**Solution**:
```bash
cd ios
rm -rf build
rm -rf ~/Library/Developer/Xcode/DerivedData/*
pod install
cd ..
npx react-native run-ios
```
#### 4. Android Build Issues
**Problem**: Build fails with Gradle errors.
**Solution**:
```bash
cd android
./gradlew clean
cd ..
npx react-native run-android
```
#### 5. Metro Bundler Issues
**Problem**: JavaScript bundle fails to load.
**Solution**:
```bash
npx react-native start --reset-cache
```
### Debug Mode
For debugging purposes, you can check the SDK initialization status and handle errors appropriately:
```javascript
const nimbblSDK = NimbblSDK.getSharedInstance();
try {
  await nimbblSDK.initialize({
    environment: 'sandbox'
  });
  console.log('SDK initialized successfully');
} catch (error) {
  console.error('SDK initialization failed:', error);
}
```
### Getting Help
If you encounter issues not covered here:
1. Check the [sample app](https://github.com/nimbbl-tech/nimbbl_react_native_sample_app) for implementation examples
2. Review the [API documentation](#api-reference) above
3. Contact support at support@nimbbl.biz
## License
This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
## Support
For support, email support@nimbbl.biz or join our Slack channel.
## Version Migration
### Upgrading Between Alpha Versions
When upgrading between alpha versions, check the changelog for breaking changes:
```bash
# Check current version
npm list nimbbl-mobile-react-native-sdk
# Upgrade to latest alpha
npm install nimbbl-mobile-react-native-sdk@latest
# Or upgrade to specific version
npm install nimbbl-mobile-react-native-sdk@1.0.0-alpha.3
```
### Migration from Alpha to Stable
**✅ Stable version is now available!**
```bash
# Upgrade from alpha to stable
npm install nimbbl-mobile-react-native-sdk@^1.0.0
# Update your package.json
# Change from: "nimbbl-mobile-react-native-sdk": "^1.0.0-alpha.12"
# To: "nimbbl-mobile-react-native-sdk": "^1.0.0"
```
**Key Changes in v1.0.0:**
- ✅ **Automatic Event Listener Management**: SDK now automatically manages event listeners for optimal performance
- ✅ **Simplified Integration**: No need to manually add/remove event listeners
- ✅ **Enhanced Error Handling**: Improved error messages and debugging capabilities
- ✅ **Production Ready**: Fully tested and optimized for production use
### Breaking Changes Migration
For major version updates (e.g., 1.x to 2.x):
1. Check the migration guide in the release notes
2. Update your code according to the breaking changes
3. Test thoroughly before deploying to production
### Version Locking
For production applications, consider locking to specific versions:
```json
{
  "dependencies": {
    "nimbbl-mobile-react-native-sdk": "1.0.0-alpha.3"
  }
}
```
### Deprecation Policy
- **Alpha versions**: Features may be deprecated without notice
- **Stable versions**: Deprecated features will be marked with warnings for at least one minor version
- **Major versions**: Breaking changes will be clearly documented
## Changelog
### v1.0.0 (Current Stable Release)
**🎉 First Stable Release - Production Ready!**
#### ✨ New Features
- **Automatic Event Listener Management**: SDK now automatically manages event listeners for optimal performance
- **Simplified Integration**: No need to manually add/remove event listeners
- **Enhanced Error Handling**: Improved error messages and debugging capabilities
#### 🔧 Improvements
- **Performance Optimization**: Better memory management and event handling
- **Code Quality**: Comprehensive TypeScript definitions and error handling
- **Documentation**: Complete API documentation with examples and troubleshooting
#### 🐛 Bug Fixes
- Fixed iOS payment status screen not opening issue
- Resolved event listener lifecycle management
- Improved WebView integration stability
#### 📦 Dependencies
- Updated to latest React Native 0.76.0 compatibility
- Enhanced iOS and Android native module integration
---
### Previous Alpha Releases
#### v1.0.0-alpha.12
- Enhanced event listener management
- Improved iOS native module integration
- Added debug logging capabilities
#### v1.0.0-alpha.3
- Enhanced error handling
- Improved WebView integration
- Better TypeScript support
#### v1.0.0-alpha.2
- Bug fixes and improvements
- Enhanced error handling
#### v1.0.0-alpha.1
- Initial alpha release with core functionality