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
Markdown
# 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`