UNPKG

zips-react-native-sdk-test

Version:

Lightweight ZIPS Payment Gateway SDK for React Native - Complete payment solution with card payments, wallet payments (AfrMoney & ZApp), netbanking, and native UI design

727 lines (573 loc) โ€ข 18.8 kB
# ZIPS React Native SDK v2.0.0 A lightweight and comprehensive React Native SDK for integrating ZIPS payment gateway into your mobile applications. Built with React Context API and React Query for advanced state management and optimal performance. ## โœจ Features - ๐Ÿš€ **Easy Integration**: Simple drop-in component with provider-based architecture - ๐Ÿ’ณ **Complete Card Payments**: Full-featured card payment UI with real-time validation - ๐Ÿ’ฐ **Wallet Payments**: Support for AfrMoney and ZApp wallet payments - ๐Ÿฆ **Multi-Bank Support**: Support for all major Gambian banks - ๐ŸŽจ **Highly Customizable**: Multiple variants, sizes, and styling options - ๐Ÿ“ฑ **Native UX**: Automatic modal management with smooth animations - ๐Ÿ”„ **Smart Loading**: Beautiful shimmer effects during processing - ๐Ÿ›ก๏ธ **Secure Processing**: Real-time validation, data masking, and security features - ๐Ÿ” **Card Type Detection**: Automatic detection of Visa, MasterCard, Amex, and more - ๐ŸŒ **Environment Support**: Sandbox and production modes - ๐Ÿ“Š **TypeScript**: Full type safety and IntelliSense support - โšก **Lightweight**: No external styling dependencies - ๐Ÿ”„ **React Query**: Advanced caching and data synchronization - ๐Ÿ—๏ธ **Context Architecture**: Provider-based state management - ๏ฟฝ **TypeScript SDK Integration**: Server-side functionality integration ## ๐Ÿš€ Installation ```bash npm install zips-react-native-sdk-test ``` ## ๐Ÿ“ฑ Quick Start ### 1. Provider Setup (Required for v2.0.0+) First, wrap your app with the required providers: ```tsx import React from 'react'; import { QueryClientProvider } from '@tanstack/react-query'; import { ZipsProvider, NetBankingProvider, WalletProvider, CardProvider, queryClient, } from 'zips-react-native-sdk-test'; export default function App() { return ( <QueryClientProvider client={queryClient}> <ZipsProvider> <NetBankingProvider> <WalletProvider> <CardProvider> <YourAppContent /> </CardProvider> </WalletProvider> </NetBankingProvider> </ZipsProvider> </QueryClientProvider> ); } ``` ### 2. Payment Integration ```tsx import React from 'react'; import { PaymentButton } from 'zips-react-native-sdk-test'; function YourAppContent() { const paymentDetails = { name: "Premium Service", quantity: 1, amount: 100, description: 'Payment for premium service', projectId: 'your-project-id', currency: 'GMD', country: 'The Gambia', firstName: 'John', lastName: 'Doe', phoneNumber: '2207001234', merchantAccountId: 'your-merchant-account-id', }; return ( <PaymentButton apiKey="your-api-key" paymentDetails={paymentDetails} onSuccess={(transaction) => { console.log('Payment successful:', transaction); }} onError={(error) => { console.error('Payment failed:', error); }} /> ); } }} /> ); } ``` ## ๐ŸŽจ Customization Options ### Button Variants ```tsx // Primary blue button (default) <PaymentButton variant="default" title="Pay Now" /> // Outlined button with transparent background <PaymentButton variant="outlined" title="Pay Securely" /> // Ghost button with minimal styling <PaymentButton variant="ghost" title="Quick Pay" /> // Success green button <PaymentButton variant="success" title="Complete Payment" /> // Danger red button <PaymentButton variant="danger" title="Emergency Payment" /> ``` ### Button Sizes ```tsx <PaymentButton size="small" title="Pay" /> <PaymentButton size="medium" title="Pay Now" /> <PaymentButton size="large" title="Pay Securely" /> ``` ### Custom Styling ```tsx // Using React Native styles <PaymentButton style={{ backgroundColor: '#FF6B35', borderRadius: 25, paddingHorizontal: 30, }} textStyle={{ fontSize: 18, fontWeight: 'bold', color: '#FFFFFF', }} title="Custom Payment" /> ``` ## ๐Ÿ“š API Reference ### PaymentButton Props | Prop | Type | Required | Description | | ---------------- | ------------------------------------ | -------- | ---------------------------------- | | `apiKey` | `string` | โœ… | Your ZIPS API key | | `paymentDetails` | `PaymentDetails` | โœ… | Payment information | | `onSuccess` | `(transaction: Transaction) => void` | โœ… | Success callback | | `onError` | `(error: PaymentError) => void` | โœ… | Error callback | | `title` | `string` | โŒ | Button text (default: "Pay Now") | | `variant` | `ButtonVariant` | โŒ | Style variant (default: "default") | | `size` | `ButtonSize` | โŒ | Button size (default: "medium") | | `environment` | `'sandbox' \| 'production'` | โŒ | Environment (default: "sandbox") | | `style` | `ViewStyle` | โŒ | Custom container styles | | `textStyle` | `TextStyle` | โŒ | Custom text styles | | `disabled` | `boolean` | โŒ | Disable the button | ### Types ```tsx interface PaymentDetails { amount: number; currency: string; description: string; customerReference: string; merchantReference: string; } interface Transaction { id: string; amount: number; currency: string; status: 'success' | 'failed' | 'pending'; method: 'bank' | 'card'; timestamp: string; reference: string; } interface PaymentError { code: string; message: string; details?: any; } type ButtonVariant = 'default' | 'outlined' | 'ghost' | 'success' | 'danger'; type ButtonSize = 'small' | 'medium' | 'large'; ``` ## ๐Ÿ”„ What's New in v1.8.0 - โšก **Lightweight Design**: Removed external styling dependencies for better performance - ๐Ÿ’ฐ **Wallet Payments**: Added support for AfrMoney and ZApp payments - ๐ŸŽจ **UI Standardization**: Consistent header design across all payment methods - ๐Ÿ”ง **Improved CVV Input**: Better sizing and user experience for card payments - ๐Ÿ“ฑ **Native Styling**: Pure React Native styling for optimal performance - ๐Ÿš€ **Reduced Bundle Size**: Smaller footprint with no external styling dependencies ## ๐ŸŽฏ Advanced Usage ### Conditional Styling ```tsx const isDarkMode = useColorScheme() === 'dark'; <PaymentButton variant={isDarkMode ? 'outlined' : 'default'} style={{ backgroundColor: isDarkMode ? '#1F2937' : '#007AFF', }} textStyle={{ color: isDarkMode ? '#F3F4F6' : '#FFFFFF', }} title="Pay Now" />; ``` ### Integration with State Management ```tsx import { usePayment } from './hooks/usePayment'; function PaymentComponent() { const { isLoading, processPayment } = usePayment(); return ( <PaymentButton title="Pay Now" disabled={isLoading} onSuccess={processPayment} onError={(error) => { // Handle error with your state management dispatch(setPaymentError(error)); }} /> ); } ``` ## ๐Ÿ”ง Configuration ### Environment Setup ```tsx // Sandbox mode (default) <PaymentButton apiKey="sandbox_key_here" environment="sandbox" /> // Production mode <PaymentButton apiKey="production_key_here" environment="production" /> ``` ## ๐Ÿฆ Supported Banks The SDK supports all major Gambian banks: - GTBank Gambia - Ecobank Gambia - Standard Chartered Bank Gambia - First National Bank Gambia - Arab Gambian Islamic Bank - Access Bank Gambia - And more... ## ๐Ÿ›ก๏ธ Security - All API communications use HTTPS encryption - Sensitive data is never stored locally - PCI DSS compliant payment processing - Bank-grade security standards ## ๐Ÿ“Š Payment Flow 1. User taps the PaymentButton 2. Modal opens with bank selection 3. User selects their bank 4. Account verification via account number 5. OTP sent to registered mobile number 6. User enters OTP for verification 7. Payment processed and confirmed 8. Success/error callback triggered ## ๐Ÿ” Error Handling ```tsx <PaymentButton onError={(error) => { switch (error.code) { case 'INSUFFICIENT_FUNDS': Alert.alert('Insufficient Funds', 'Please check your account balance.'); break; case 'INVALID_OTP': Alert.alert('Invalid OTP', 'Please check the OTP and try again.'); break; case 'NETWORK_ERROR': Alert.alert('Network Error', 'Please check your connection.'); break; default: Alert.alert('Payment Error', error.message); } }} /> ``` ## ๐Ÿ“– Migration Guide ### From v1.6.x to v1.7.x The v1.7.x update removes external styling dependencies to keep the SDK lightweight. All components now use pure React Native styling for optimal performance and compatibility. ```tsx // Old (no longer supported) <PaymentButton className="bg-purple-600 rounded-2xl px-8 py-4" textClassName="text-white text-lg font-bold" /> // New (recommended) <PaymentButton style={{ backgroundColor: '#7C3AED', borderRadius: 16, paddingHorizontal: 32, paddingVertical: 16, }} textStyle={{ color: '#FFFFFF', fontSize: 18, fontWeight: 'bold', }} /> ``` ### Three Ways to Use the SDK #### Method 1: PaymentButton (Recommended) ```tsx import { PaymentButton } from 'zips-react-native-sdk-test'; <PaymentButton apiKey="your-api-key" paymentDetails={paymentDetails} onSuccess={handleSuccess} onError={handleError} />; ``` #### Method 2: Direct SDK Usage ```tsx import { Zips } from 'zips-react-native-sdk-test'; const zips = new Zips('your-api-key', 'sandbox'); const payment = await zips.payments.create(paymentDetails); ``` #### Method 3: React Hooks ```tsx import { useZips } from 'zips-react-native-sdk-test'; function PaymentScreen() { const zips = useZips(); // Use zips instance for custom implementation } ``` ## ๐Ÿ“‹ Requirements - React Native >= 0.68.0 - React >= 16.8.0 - TypeScript >= 5.0.0 (for TypeScript projects) ## ๐Ÿ” Security Best Practices - Store API keys securely (never hardcode in production) - Use environment variables for sensitive data - Validate payment amounts on your backend - Never store sensitive customer data locally - Use HTTPS endpoints (automatically handled) ## ๐Ÿค Support For technical support and documentation: - Email: dev@zips.gm - Documentation: [https://docs.zips.gm](https://docs.zips.gm) - GitHub: [Issues](https://github.com/zips-gm/react-native-sdk/issues) ## ๐Ÿ“„ License MIT License - see LICENSE file for details. --- Made with โค๏ธ by the ZIPS Team for Gambian fintech innovation. ### Method 2: React Hooks (Advanced) ```tsx import { useZips, usePayments, useTransactions } from '@zigtech/zips-rn-sdk'; function AdvancedPaymentScreen() { const zips = useZips(); // Direct Zips instance const payments = usePayments(); // Payments module const transactions = useTransactions(); // Transactions module const handlePayment = async () => { try { const payment = await payments.create(paymentDetails); if (payment.success) { const transaction = await transactions.single(payment.referenceNumber); console.log('Payment:', payment, 'Transaction:', transaction); } } catch (error) { console.error('Payment failed:', error); } }; return ( // Your custom UI here <TouchableOpacity onPress={handlePayment}> <Text>Pay Now</Text> </TouchableOpacity> ); } ``` ### Method 3: Direct SDK Usage (Like TypeScript SDK) ```typescript import { Zips } from '@zigtech/zips-rn-sdk'; async function directPayment() { const zips = new Zips('your-api-key', 'sandbox'); try { // Create payment (same API as TypeScript SDK) const payment = await zips.payments.create({ name: 'Product Purchase', quantity: 1, amount: 5000, description: 'Payment for product', projectId: 'your-project-id', currency: 'GMD', country: 'The Gambia', firstName: 'Customer', lastName: 'Name', phoneNumber: '+220123456789', merchantAccountId: 'your-merchant-account-id', }); console.log('Payment created:', payment); // Get transaction details if (payment.success) { const transaction = await zips.transactions.single( payment.referenceNumber ); console.log('Transaction:', transaction); } // Get all transactions const allTransactions = await zips.transactions.all({ limit: 10, page: 1 }); console.log('All transactions:', allTransactions); } catch (error) { console.error('Payment error:', error); } } ``` ## ๐ŸŽฏ Perfect Compatibility with TypeScript SDK This React Native SDK is **100% compatible** with the existing TypeScript SDK structure found in `sdks/zips-ts/src/backend/`. Same API, same patterns: ```typescript // TypeScript SDK (Web) const zips = new Zips(apiKey); const payment = await zips.payments.create(paymentDetails); const transaction = await zips.transactions.single(payment.referenceNumber); // React Native SDK (Mobile) - IDENTICAL API const zips = new Zips(apiKey, environment); const payment = await zips.payments.create(paymentDetails); const transaction = await zips.transactions.single(payment.referenceNumber); ``` ## ๐Ÿ—๏ธ Architecture ### Core Components - **Zips**: Main SDK class with modular architecture - **PaymentsModule**: Handle payment creation and management - **TransactionsModule**: Transaction tracking and retrieval - **BaseModule**: Shared HTTP functionality - **PaymentButton**: Ready-to-use React Native payment button - **ZipsProvider**: React context provider for configuration ### TypeScript Support Complete type definitions for all APIs: ```typescript import { Zips, PaymentDetails, Payment, Transaction, PaymentError, } from '@zigtech/zips-rn-sdk'; ``` ## ๐Ÿ“ฑ PaymentButton Component Props ```typescript interface PaymentButtonProps { apiKey: string; paymentDetails: PaymentDetails; onSuccess: (payment: Payment, transaction?: Transaction) => void; onError: (error: PaymentError) => void; buttonText?: string; environment?: 'sandbox' | 'production'; style?: any; // React Native style object textStyle?: any; loadingColor?: string; disabled?: boolean; onPress?: () => void; // Custom handler before payment } ``` ## ๐Ÿ”ง Configuration ### Environment Setup ```typescript // Sandbox (Testing) <ZipsProvider apiKey="test_key" environment="sandbox"> // Production <ZipsProvider apiKey="live_key" environment="production"> ``` ### Dynamic Configuration ```typescript const zips = new Zips('api-key', 'sandbox'); // Update API key at runtime zips.updateApiKey('new-api-key'); // Switch environment zips.setEnvironment('production'); // Get current config console.log(zips.config); ``` ## ๐Ÿ”„ Payment Flow 1. **Initialize** SDK with API credentials and environment 2. **Create Payment** using `payments.create()` 3. **Track Transaction** using `transactions.single(referenceNumber)` 4. **Handle Success/Error** with appropriate callbacks 5. **Update UI** based on payment status ## ๐Ÿ› ๏ธ Advanced Usage ### Module-Level Access ```typescript // Get modules directly const payments = zips.payments; const transactions = zips.transactions; // Create payment const payment = await payments.create(paymentDetails); // Get all payments const allPayments = await payments.all({ limit: 15, page: 1 }); // Get transaction by reference const transaction = await transactions.single(referenceNumber); // Get all transactions const allTransactions = await transactions.all({ limit: 10, page: 1 }); ``` ### Error Handling ```typescript try { const payment = await zips.payments.create(paymentDetails); } catch (error) { switch (error.code) { case 'NETWORK_ERROR': // Handle network issues break; case 'API_ERROR': // Handle API errors break; default: console.error(error.message); } } ``` ## ๐Ÿ“‹ Requirements - React Native >= 0.68.0 - React >= 16.8.0 - TypeScript >= 5.0.0 (for TypeScript projects) ## ๐Ÿ” Security Best Practices - Store API keys securely (never hardcode in production) - Use environment variables for sensitive data - Validate payment amounts on your backend - Never store sensitive customer data locally - Use HTTPS endpoints (automatically handled) ## ๐ŸŒ Supported Countries & Banks - **Primary**: ๐Ÿ‡ฌ๐Ÿ‡ฒ Gambia - **Banks**: GT Bank, Access Bank, FCMB, Zenith Bank, and more (fetched dynamically) ## ๐Ÿ“Š API Reference ### PaymentDetails Interface ```typescript interface PaymentDetails { name: string; // Product/service name quantity: number; // Item quantity amount: number; // Amount in minor units (e.g., 2500 = 25.00 GMD) description: string; // Payment description projectId: string; // Your project ID currency: string; // Currency code (GMD) country: string; // Country name firstName: string; // Customer first name lastName: string; // Customer last name phoneNumber: string; // Customer phone (+220...) merchantAccountId: string; // Your merchant account ID middleName?: string; // Optional middle name } ``` ### Payment Response ```typescript interface Payment { data: string; // Payment data/URL success: boolean; // Success status referenceNumber: string; // Unique reference message: string; // Status message } ``` ### Transaction Response ```typescript interface Transaction { status: string; // Transaction status success: boolean; // Success flag message: string; // Status message data: Order; // Order details url: string; // Transaction URL } ``` ## ๐Ÿ—๏ธ Building from Source ```bash git clone https://github.com/zigtech/zips-rn-sdk cd zips-rn-sdk npm install --legacy-peer-deps npm run build ``` ## ๐Ÿงช Testing ```bash # Test core functionality node test-core-enhanced.js # Test with React Native app npm run test ``` ## ๐Ÿ“ž Support & Documentation - **Issues**: [GitHub Issues](https://github.com/zigtech/zips-rn-sdk/issues) - **Documentation**: [ZIPS Docs](https://docs.zips.gm) - **Email**: support@zigtech.gm - **Web SDK**: [TypeScript SDK](../zips-ts/) ## ๐Ÿ“„ License MIT License - see [LICENSE](LICENSE) file for details. ## ๐Ÿ—๏ธ Built by ZigTech Developed with โค๏ธ by the ZigTech team for the Gambian fintech ecosystem. Compatible with existing ZIPS infrastructure and TypeScript SDK. --- **Version**: 1.0.0 Enhanced **Last Updated**: August 2025 **Compatibility**: 100% with `sdks/zips-ts/src/backend`