storm-sdk
v1.1.0
Published
A comprehensive TypeScript SDK for the Storm Payments Infrastructure platform, providing secure payment processing, wallet management, and advanced security features.
Readme
Storm Payments SDK
A comprehensive TypeScript SDK for the Storm Payments Infrastructure platform, providing secure payment processing, wallet management, and advanced security features.
Features
- 🔐 Secure Authentication - JWT-based authentication with automatic token management
- 💰 Wallet Management - Create and manage multiple wallets with real-time balance tracking
- 💳 Payment Processing - Support for cards, digital wallets, and bank transfers
- 🔄 Transaction Management - Complete transaction lifecycle with immutable records
- 🔒 Secure Vault - Encrypted storage for sensitive data
- 📊 Activity Monitoring - Comprehensive audit trails and reporting
- 🛡️ Type Safety - Full TypeScript support with comprehensive type definitions
Installation
```bash npm install @storm/payments-sdk ```
Quick Start
```typescript import { StormClient } from '@storm/payments-sdk';
// Initialize the client const storm = new StormClient({ baseUrl: 'https://storm-core2.onrender.com', timeout: 30000 });
// Register a new user const user = await storm.register({ email: '[email protected]', password: 'SecurePass123!', first_name: 'John', last_name: 'Doe' });
// Login and get authentication token const auth = await storm.login({ email: '[email protected]', password: 'SecurePass123!' });
console.log('Authenticated:', auth.user.email); ```
Authentication
Register a New User
```typescript const registration = await storm.register({ email: '[email protected]', password: 'SecurePass123!', first_name: 'John', last_name: 'Doe' }); ```
Login
```typescript const auth = await storm.login({ email: '[email protected]', password: 'SecurePass123!' });
// Token is automatically set for subsequent requests console.log('Token:', auth.token); ```
Manual Token Management
```typescript // Set token manually storm.setToken('your-jwt-token');
// Get current token const token = storm.getToken();
// Clear token storm.clearToken(); ```
Wallet Management
Create a Wallet
```typescript const wallet = await storm.createWallet({ name: 'My Main Wallet', currency: 'USD' });
console.log('Wallet created:', wallet.id); ```
Get All Wallets
```typescript const wallets = await storm.getWallets(); console.log('User has', wallets.length, 'wallets'); ```
Get Wallet Balance
```typescript const balance = await storm.getWalletBalance(wallet.id); console.log('Balance:', balance.balance, balance.currency); ```
Deactivate Wallet
```typescript await storm.deactivateWallet(wallet.id); console.log('Wallet deactivated'); ```
Transaction Management
Create a Transaction
```typescript // Add funds (Credit) const creditTransaction = await storm.createTransaction({ wallet_id: wallet.id, transaction_type: 'Credit', amount: 50000, // $500.00 in cents description: 'Initial deposit', metadata: { source: 'bank_transfer', reference: 'TXN-001' } });
// Withdraw funds (Debit) const debitTransaction = await storm.createTransaction({ wallet_id: wallet.id, transaction_type: 'Debit', amount: 10000, // $100.00 in cents description: 'ATM withdrawal' }); ```
Transfer Between Wallets
```typescript const transfer = await storm.transferFunds({ from_wallet_id: wallet1.id, to_wallet_id: wallet2.id, amount: 25000, // $250.00 in cents description: 'Transfer to savings' });
console.log('Transfer completed:', transfer.debit_transaction.id); ```
Get Transaction History
```typescript const history = await storm.getWalletTransactions(wallet.id, { page: 1, per_page: 10 });
console.log('Found', history.total_count, 'transactions'); ```
Payment Processing
Create a Card Payment
```typescript import { createCardPaymentMethod } from '@storm/payments-sdk';
const payment = await storm.createPayment({ merchant_id: 'merchant_123', amount: 15000, // $150.00 in cents currency: 'USD', payment_method: createCardPaymentMethod( '4242424242424242', 12, 2025, '123' ), metadata: { order_id: 'ORDER-001', customer_email: '[email protected]' } });
console.log('Payment created:', payment.id); ```
Create a Digital Wallet Payment
```typescript import { createWalletPaymentMethod } from '@storm/payments-sdk';
const payment = await storm.createPayment({ merchant_id: 'merchant_123', amount: 7500, // $75.00 in cents currency: 'USD', payment_method: createWalletPaymentMethod('apple_pay', 'tok_apple_pay_12345') }); ```
Confirm Payment
```typescript const confirmedPayment = await storm.confirmPayment(payment.id); console.log('Payment status:', confirmedPayment.status); ```
Secure Vault
Store a Secret
```typescript const vaultEntry = await storm.storeSecret({ key_type: 'api_key', data: 'sk_live_1234567890abcdef' });
console.log('Secret stored:', vaultEntry.entry_id); ```
Retrieve a Secret
```typescript const secret = await storm.getSecret(vaultEntry.entry_id); console.log('Retrieved secret:', secret.data); ```
List Vault Entries
```typescript const entries = await storm.getVaultEntries(); console.log('Vault contains', entries.length, 'entries'); ```
Activity Monitoring
Get Activity Log
```typescript const activities = await storm.getActivities({ page: 1, per_page: 20 });
console.log('Recent activities:', activities.length); ```
Get Activity Report
```typescript const report = await storm.getActivityReport(); console.log('Total activities:', report.total_count); console.log('Date range:', report.date_range); ```
Error Handling
The SDK provides comprehensive error handling with typed error responses:
```typescript import { StormError } from '@storm/payments-sdk';
try { const wallet = await storm.getWallet('invalid-id'); } catch (error) { if (error instanceof StormError) { console.error('Storm API Error:', error.message); console.error('Status Code:', error.statusCode); console.error('Error Code:', error.code); console.error('Details:', error.details); } else { console.error('Unexpected error:', error); } } ```
Utility Functions
The SDK includes helpful utility functions:
```typescript import { formatCurrency, toCents, isValidEmail, isValidPassword, generateReferenceId } from '@storm/payments-sdk';
// Format currency const formatted = formatCurrency(15000, 'USD'); // "$150.00"
// Convert to cents const cents = toCents(150.00); // 15000
// Validate email const validEmail = isValidEmail('[email protected]'); // true
// Validate password const validPassword = isValidPassword('SecurePass123!'); // true
// Generate reference ID const refId = generateReferenceId('ORDER'); // "ORDER-1640995200000-ABC123" ```
Complete Example
```typescript import { StormClient, createCardPaymentMethod, formatCurrency } from '@storm/payments-sdk';
async function completeWorkflow() { const storm = new StormClient({ baseUrl: 'https://storm-core2.onrender.com' });
try { // 1. Register and login await storm.register({ email: '[email protected]', password: 'SecurePass123!', first_name: 'Demo', last_name: 'User' });
const auth = await storm.login({
email: '[email protected]',
password: 'SecurePass123!'
});
console.log('✅ Authenticated as:', auth.user.email);
// 2. Create wallets
const mainWallet = await storm.createWallet({
name: 'Main Checking',
currency: 'USD'
});
const savingsWallet = await storm.createWallet({
name: 'Savings Account',
currency: 'USD'
});
console.log('✅ Created wallets');
// 3. Add initial funds
await storm.createTransaction({
wallet_id: mainWallet.id,
transaction_type: 'Credit',
amount: 100000, // $1000.00
description: 'Initial deposit'
});
console.log('✅ Added initial funds');
// 4. Transfer to savings
const transfer = await storm.transferFunds({
from_wallet_id: mainWallet.id,
to_wallet_id: savingsWallet.id,
amount: 30000, // $300.00
description: 'Monthly savings transfer'
});
console.log('✅ Transfer completed');
// 5. Process a payment
const payment = await storm.createPayment({
merchant_id: 'merchant_demo',
amount: 5000, // $50.00
currency: 'USD',
payment_method: createCardPaymentMethod(
'4242424242424242',
12,
2025,
'123'
)
});
const confirmedPayment = await storm.confirmPayment(payment.id);
console.log('✅ Payment processed:', confirmedPayment.status);
// 6. Check final balances
const mainBalance = await storm.getWalletBalance(mainWallet.id);
const savingsBalance = await storm.getWalletBalance(savingsWallet.id);
console.log('💰 Main wallet:', formatCurrency(mainBalance.balance));
console.log('💰 Savings wallet:', formatCurrency(savingsBalance.balance));
// 7. Store API key in vault
const vaultEntry = await storm.storeSecret({
key_type: 'api_key',
data: 'sk_demo_1234567890abcdef'
});
console.log('🔒 Secret stored in vault');
// 8. Get activity report
const report = await storm.getActivityReport();
console.log('📊 Total activities:', report.total_count);
console.log('🎉 Workflow completed successfully!');} catch (error) { console.error('❌ Error:', error); } }
completeWorkflow(); ```
TypeScript Support
The SDK is built with TypeScript and provides comprehensive type definitions:
```typescript import { Wallet, Transaction, Payment, TransactionType, PaymentStatus } from '@storm/payments-sdk';
// All types are fully typed const wallet: Wallet = await storm.getWallet('wallet-id'); const transaction: Transaction = await storm.getTransaction('txn-id'); const payment: Payment = await storm.getPayment('payment-id'); ```
Configuration Options
```typescript const storm = new StormClient({ baseUrl: 'https://storm-core2.onrender.com', apiKey: 'optional-api-key', // Will be set as Authorization header timeout: 30000, // Request timeout in milliseconds retries: 3 // Number of retry attempts (not implemented yet) }); ```
Security Best Practices
- Never hardcode credentials - Use environment variables
- Validate inputs - Use the provided validation utilities
- Handle errors properly - Always wrap API calls in try-catch blocks
- Store tokens securely - Don't store JWT tokens in localStorage in production
- Use HTTPS - Always use HTTPS endpoints in production
Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Submit a pull request
License
MIT License - see LICENSE file for details.
Support
For support and questions:
- Documentation: https://docs.storm-payments.com
- Email: [email protected]
