react-native-magento
v2.0.0
Published
A comprehensive React Native library for Magento e-commerce platform integration - Mirror of flutter_magento
Maintainers
Readme
🚀 React Native Magento Library 2.0
A comprehensive React Native library for Magento e-commerce platform integration. This library mirrors the functionality of the Flutter Magento plugin and provides 200+ functions for building modern mobile commerce applications.
✨ Features
🎯 Unified Architecture
- Eliminates Code Duplication: One API for all applications
- Modular Structure: Use only the components you need
- Type Safety: Strict typing with TypeScript interfaces
- Consistency: Same approach across all applications
🔐 Advanced Authentication
- JWT tokens with automatic refresh
- Secure storage with React Native Keychain
- "Remember Me" support
- Automatic token validation
- Session expiration handling
🌐 Unified Network Layer
- Axios HTTP client with automatic retries
- Internet connectivity monitoring
- Automatic error handling
- Request logging in debug mode
- Response caching
🌍 Localization System
- 45+ languages out of the box
- Automatic system locale detection
- Pluralization support
- RTL support for Arabic and Hebrew
- Custom translations
📱 Offline Mode
- Automatic data caching
- Offline operation queue
- AsyncStorage + secure storage for fast access
- Automatic sync when network is restored
- Configurable caching strategies
🎨 State Management
- Built-in state management with observers
- Ready-to-use services for all operations
- Reactive UI updates
- Centralized state management
🛍️ Extended E-commerce Functionality
- Full integration with Magento REST API
- GraphQL support for complex queries
- Cart with guest user support
- Wishlist with multiple lists
- Advanced search and filtering
🚀 Getting Started
Installation
npm install react-native-magento
# or
yarn add react-native-magentoAdditional Dependencies
Install required peer dependencies:
npm install axios react-native-async-storage react-native-device-info react-native-keychain react-native-netinfo
# or
yarn add axios react-native-async-storage react-native-device-info react-native-keychain react-native-netinfoQuick Start
import ReactNativeMagento from 'react-native-magento';
// Initialize the library
const initializeMagento = async () => {
const success = await ReactNativeMagento.initialize({
baseUrl: 'https://your-magento-store.com',
headers: { 'Content-Type': 'application/json' },
supportedLanguages: ['en', 'ru', 'de', 'fr', 'es'],
});
if (success) {
console.log('✅ Magento initialized successfully');
}
};
// Authenticate customer
const login = async (email: string, password: string) => {
try {
const result = await ReactNativeMagento.login(email, password, true);
console.log('Logged in:', result);
} catch (error) {
console.error('Login failed:', error);
}
};
// Get products
const loadProducts = async () => {
try {
const products = await ReactNativeMagento.getProducts({
page: 1,
pageSize: 20,
searchQuery: 'phone',
});
console.log('Products:', products);
} catch (error) {
console.error('Failed to load products:', error);
}
};
// Add to cart
const addProductToCart = async (sku: string, quantity: number) => {
try {
const success = await ReactNativeMagento.addToCart({
sku,
quantity,
});
console.log('Added to cart:', success);
} catch (error) {
console.error('Failed to add to cart:', error);
}
};📚 API Reference
Authentication
// Customer login
const authResult = await ReactNativeMagento.login('[email protected]', 'password123');
// Customer registration
const customer = await ReactNativeMagento.register({
email: '[email protected]',
password: 'password123',
firstName: 'John',
lastName: 'Doe',
});
// Get current customer
const currentCustomer = ReactNativeMagento.currentCustomer;
// Logout
await ReactNativeMagento.logout();Products
// Get products with filters
const products = await ReactNativeMagento.getProducts({
page: 1,
pageSize: 20,
searchQuery: 'phone',
categoryId: '123',
sortBy: 'price',
sortOrder: 'asc',
filters: { brand: 'Apple' },
});
// Get single product
const product = await ReactNativeMagento.getProduct('SKU123');
// Search products
const searchResults = await ReactNativeMagento.searchProducts('smartphone', {
page: 1,
pageSize: 20,
});Cart Management
// Get cart
const cart = await ReactNativeMagento.getCart();
// Add item to cart
const success = await ReactNativeMagento.addToCart({
sku: 'SKU123',
quantity: 2,
});
// Remove item from cart
await ReactNativeMagento.removeFromCart(itemId);
// Clear cart
await ReactNativeMagento.clearCart();Orders
// Get customer orders
const orders = await ReactNativeMagento.getOrders({
page: 1,
pageSize: 20,
});
// Get order details
const order = await ReactNativeMagento.getOrder('ORDER123');Wishlist
// Get wishlist
const wishlist = await ReactNativeMagento.getWishlist();
// Add to wishlist
await ReactNativeMagento.addToWishlist('SKU123');
// Remove from wishlist
await ReactNativeMagento.removeFromWishlist(itemId);Localization
// Set locale
await ReactNativeMagento.setLocale('ru');
// Translate text
const text = ReactNativeMagento.translate('product.add_to_cart');
// Format currency
const price = ReactNativeMagento.formatCurrency(99.99, 'USD');
// Format date
const date = ReactNativeMagento.formatDate(new Date());Network & Offline
// Check online status
const isOnline = ReactNativeMagento.isOnline;
// Get network service
const networkService = ReactNativeMagento.network;
// Add connectivity listener
networkService.addConnectivityListener((isOnline) => {
console.log('Network status changed:', isOnline);
});
// Get offline service
const offlineService = ReactNativeMagento.offline;
// Get cached data
const cachedProducts = await offlineService.getCachedProducts();🏗️ Architecture
The library follows a clean architecture pattern with the following layers:
- Core Layer: Main initialization and coordination
- Service Layer: Business logic and data processing
- API Layer: HTTP client and REST API integration
- Model Layer: Data models with TypeScript interfaces
- Exception Layer: Error handling and custom exceptions
Directory Structure
src/
├── core/
│ └── ReactNativeMagentoCore.ts # Main core class
├── services/
│ ├── MagentoApiService.ts # API communication
│ ├── AuthService.ts # Authentication
│ ├── CartService.ts # Shopping cart
│ ├── NetworkService.ts # Network monitoring
│ ├── OfflineService.ts # Offline support
│ └── LocalizationService.ts # Internationalization
├── exceptions/
│ └── MagentoException.ts # Custom exceptions
├── types/
│ └── index.ts # TypeScript interfaces
├── models/
│ └── index.ts # Data models
└── index.ts # Main export🔧 Configuration
Environment Setup
// Development
await ReactNativeMagento.initialize({
baseUrl: 'https://dev-store.com',
connectionTimeout: 30000,
receiveTimeout: 30000,
});
// Production
await ReactNativeMagento.initialize({
baseUrl: 'https://store.com',
headers: {
'X-API-Key': 'your-api-key',
'X-Store-Code': 'default',
},
});Custom Headers
await ReactNativeMagento.initialize({
baseUrl: 'https://store.com',
headers: {
'Authorization': 'Bearer token',
'Accept-Language': 'en-US',
'X-Custom-Header': 'value',
},
});🧪 Testing
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Build library
npm run build📱 Platform Support
- ✅ iOS
- ✅ Android
- ✅ React Native 0.70+
🔒 Security Features
- JWT token authentication
- Secure token storage with Keychain
- Input validation and sanitization
- Rate limiting support
- Automatic token refresh
📊 Performance Features
- Request caching
- Offline mode
- Background sync
- Memory management
- Network optimization
🆚 Comparison with Flutter Version
This React Native library mirrors the Flutter Magento plugin functionality:
| Feature | Flutter Magento | React Native Magento | |---------|----------------|---------------------| | Architecture | ✅ Clean Architecture | ✅ Clean Architecture | | Authentication | ✅ JWT + Secure Storage | ✅ JWT + Keychain | | Offline Support | ✅ SQLite + Hive | ✅ AsyncStorage | | Localization | ✅ 45+ Languages | ✅ 45+ Languages | | Network Monitoring | ✅ Connectivity Plus | ✅ NetInfo | | State Management | ✅ Provider/Riverpod | ✅ Built-in Observers | | API Client | ✅ Dio | ✅ Axios | | Error Handling | ✅ Custom Exceptions | ✅ Custom Exceptions |
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- 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: Wiki
- 💬 Community: Discord
🙏 Acknowledgments
- Magento team for the excellent e-commerce platform
- React Native team for the amazing framework
- Flutter Magento plugin for inspiration and architecture
- All contributors and community members
Made with ❤️ by NativeMind Team
