UNPKG

@vulog/aima-payment

Version:

Payment management module for the AIMA platform. This module provides functionality to handle payments, setup intents, payment methods, and trip payments.

322 lines (255 loc) 8.68 kB
# @vulog/aima-payment Payment management module for the AIMA platform. This module provides functionality to handle payments, setup intents, payment methods, and trip payments. ## Installation ```bash npm install @vulog/aima-client @vulog/aima-core @vulog/aima-payment ``` ## Usage ### Initialize Client ```javascript import { getClient } from '@vulog/aima-client'; import { getSetupIntent, getPaymentMethodDetailsForUser, getSynchronize, payATrip } from '@vulog/aima-payment'; const client = getClient({ apiKey: 'your-api-key', baseUrl: 'https://your-api-base-url', clientId: 'your-client-id', clientSecret: 'your-client-secret', fleetId: 'your-fleet-id', }); ``` ## API Reference ### Payment Setup #### getSetupIntent Create a setup intent for payment method configuration. ```javascript const setupIntent = await getSetupIntent(client, 'user-uuid-here'); ``` **Parameters:** - `client`: AIMA client instance - `entityId`: User UUID **Returns:** Setup intent object for payment method configuration #### getPaymentMethodDetailsForUser Retrieve payment method details for a specific user. ```javascript const paymentMethods = await getPaymentMethodDetailsForUser(client, 'user-uuid-here'); ``` **Parameters:** - `client`: AIMA client instance - `entityId`: User UUID **Returns:** Array of user's payment methods ### Payment Processing #### payATrip Process payment for a trip. ```javascript const paymentResult = await payATrip(client, { tripId: 'trip-uuid-here', paymentMethodId: 'payment-method-id-here', amount: 25.50, currency: 'EUR' }); ``` **Parameters:** - `client`: AIMA client instance - `paymentData`: Payment configuration object - `tripId`: Trip identifier - `paymentMethodId`: Payment method identifier - `amount`: Payment amount - `currency`: Currency code **Returns:** Payment processing result #### getSynchronize Synchronize payment data. ```javascript const syncResult = await getSynchronize(client, { entityId: 'user-uuid-here', lastSyncDate: '2024-01-01T00:00:00Z' }); ``` **Parameters:** - `client`: AIMA client instance - `syncData`: Synchronization configuration - `entityId`: User UUID - `lastSyncDate`: Last synchronization date **Returns:** Synchronization result ## Types ### SetupIntent ```typescript interface SetupIntent { id: string; clientSecret: string; status: 'requires_payment_method' | 'requires_confirmation' | 'requires_action' | 'processing' | 'succeeded' | 'canceled'; paymentMethodTypes: string[]; createdAt: string; updatedAt: string; } ``` ### PaymentMethod ```typescript interface PaymentMethod { id: string; type: 'card' | 'bank_account' | 'sepa_debit'; card?: { brand: string; last4: string; expMonth: number; expYear: number; }; bankAccount?: { bankName: string; last4: string; routingNumber: string; }; isDefault: boolean; createdAt: string; updatedAt: string; } ``` ### PaymentResult ```typescript interface PaymentResult { id: string; status: 'succeeded' | 'failed' | 'pending' | 'canceled'; amount: number; currency: string; paymentMethodId: string; tripId: string; errorMessage?: string; createdAt: string; } ``` ## Error Handling All functions include validation and will throw appropriate errors if: - Required parameters are missing - Invalid user or trip IDs are provided - Payment processing fails - Network errors occur ## Examples ### Complete Payment Workflow ```javascript import { getClient } from '@vulog/aima-client'; import { getSetupIntent, getPaymentMethodDetailsForUser, payATrip } from '@vulog/aima-payment'; const client = getClient({ apiKey: 'your-api-key', baseUrl: 'https://your-api-base-url', clientId: 'your-client-id', clientSecret: 'your-client-secret', fleetId: 'your-fleet-id', }); async function paymentWorkflow() { try { const userId = 'user-uuid-here'; // Create setup intent for new payment method const setupIntent = await getSetupIntent(client, userId); console.log('Setup intent created:', setupIntent); // Get user's existing payment methods const paymentMethods = await getPaymentMethodDetailsForUser(client, userId); console.log(`User has ${paymentMethods.length} payment methods`); // Process trip payment const paymentResult = await payATrip(client, { tripId: 'trip-uuid-here', paymentMethodId: paymentMethods[0].id, amount: 25.50, currency: 'EUR' }); console.log('Payment processed:', paymentResult); return { setupIntent, paymentMethods, paymentResult }; } catch (error) { console.error('Payment workflow error:', error); throw error; } } ``` ### Payment Method Management ```javascript async function managePaymentMethods(client, userId) { try { const paymentMethods = await getPaymentMethodDetailsForUser(client, userId); const analysis = { totalMethods: paymentMethods.length, defaultMethod: paymentMethods.find(pm => pm.isDefault), cardMethods: paymentMethods.filter(pm => pm.type === 'card'), bankMethods: paymentMethods.filter(pm => pm.type === 'bank_account'), sepaMethods: paymentMethods.filter(pm => pm.type === 'sepa_debit') }; console.log('Payment Method Analysis:'); console.log(`Total Methods: ${analysis.totalMethods}`); console.log(`Default Method: ${analysis.defaultMethod?.id || 'None'}`); console.log(`Card Methods: ${analysis.cardMethods.length}`); console.log(`Bank Methods: ${analysis.bankMethods.length}`); console.log(`SEPA Methods: ${analysis.sepaMethods.length}`); return analysis; } catch (error) { console.error('Payment method management error:', error); throw error; } } ``` ### Trip Payment Processing ```javascript async function processTripPayment(client, tripId, userId, amount, currency = 'EUR') { try { // Get user's payment methods const paymentMethods = await getPaymentMethodDetailsForUser(client, userId); if (paymentMethods.length === 0) { throw new Error('No payment methods found for user'); } // Use default payment method or first available const paymentMethod = paymentMethods.find(pm => pm.isDefault) || paymentMethods[0]; // Process payment const paymentResult = await payATrip(client, { tripId, paymentMethodId: paymentMethod.id, amount, currency }); if (paymentResult.status === 'succeeded') { console.log(`Payment successful: ${amount} ${currency} for trip ${tripId}`); } else { console.log(`Payment failed: ${paymentResult.errorMessage}`); } return paymentResult; } catch (error) { console.error('Trip payment processing error:', error); throw error; } } ``` ### Payment History and Analytics ```javascript async function analyzePayments(client, userId) { try { // This would require additional API endpoints for payment history // For now, we'll demonstrate with payment methods const paymentMethods = await getPaymentMethodDetailsForUser(client, userId); const analysis = { userPaymentMethods: paymentMethods.length, hasDefaultMethod: paymentMethods.some(pm => pm.isDefault), supportedTypes: [...new Set(paymentMethods.map(pm => pm.type))], cardBrands: paymentMethods .filter(pm => pm.card) .map(pm => pm.card.brand), recentMethods: paymentMethods .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) .slice(0, 3) }; console.log('Payment Analysis:'); console.log(`Payment Methods: ${analysis.userPaymentMethods}`); console.log(`Has Default: ${analysis.hasDefaultMethod}`); console.log(`Supported Types: ${analysis.supportedTypes.join(', ')}`); console.log(`Card Brands: ${analysis.cardBrands.join(', ')}`); console.log('Recent Methods:', analysis.recentMethods); return analysis; } catch (error) { console.error('Payment analysis error:', error); throw error; } } ```