@cloudbank/sdk
v0.2.0
Published
Official Node.js SDK for CloudBank API
Maintainers
Readme
CloudBank Node.js SDK
The official Node.js SDK for CloudBank - A mature RESTful API designed for mission-critical financial operations with a focus on developer experience and modern banking features.
Features
- 🔐 Secure by Default - Built-in authentication and HTTPS-only communication
- 🚀 TypeScript Native - Full type safety with comprehensive TypeScript definitions
- 🔄 Modern Async/Await - Promise-based API with full async/await support
- 🛡️ Error Handling - Comprehensive error handling with detailed error messages
- 📦 Tree Shakeable - Modular design for optimal bundle sizes
- 🌍 Multi-Environment - Support for staging and production environments
- 🏢 Multi-Provider - Support for CloudBank and MagePay distributions
- 💰 Full API Coverage - Complete coverage of CloudBank's payment, checkout, and account APIs
Installation
Choose your preferred package manager:
# npm
npm install @cloudbank/sdk
# yarn
yarn add @cloudbank/sdk
# pnpm
pnpm add @cloudbank/sdk
# bun
bun add @cloudbank/sdkQuick Start
import { createCloudBank } from '@cloudbank/sdk';
// Initialize the CloudBank client
const cloudBank = createCloudBank({
accessToken: 'your-access-token',
environment: 'staging', // or 'production'
apiVersion: '1.0.0',
});
// Create a payment intent
const payment = await cloudBank.payments.intents.create({
amount: {
value: 10000, // 100.00 XAF (amount in minor units)
currency: 'XAF',
},
external_id: 'order_123',
description: 'Payment for premium subscription',
customer: {
name: 'John Doe',
email: '[email protected]',
phone_number: '+237123456789',
},
});
console.log('Payment intent created:', payment.payment_intent_id);API Reference
Configuration
interface Configuration {
accessToken: string; // Your API access token
provider?: Provider; // 'cloudbank' | 'magepay' (default: 'cloudbank')
environment?: Environment; // 'staging' | 'production' (default: 'production')
apiVersion?: ApiVersion; // API version (default: '1.0.0')
baseUrl?: string; // Custom base URL (optional)
userAgent?: string; // Custom user agent (optional)
timeout?: number; // Request timeout in milliseconds (default: 30000)
}Client Services
The CloudBank client provides access to the following services:
const cloudBank = createCloudBank(config);
// Payment Services
cloudBank.payments.intents // Payment Intent operations
cloudBank.payments.retrieve // Payment retrieval
// Checkout Services
cloudBank.checkout.sessions // Checkout Session operations
// Account Services
cloudBank.accounts // Account managementCore Operations
Payment Intents
Payment intents represent your intent to collect payment from a customer.
// Create a payment intent
const paymentIntent = await cloudBank.payments.intents.create({
amount: {
value: 50000,
currency: 'XAF',
},
external_id: 'unique-order-id',
description: 'Premium subscription payment',
customer: {
name: 'Jane Smith',
email: '[email protected]',
phone_number: '+237987654321',
},
payment_method_types: ['mobile_money', 'card'],
});
// Confirm the payment intent with a payment method
const confirmed = await cloudBank.payments.intents.confirm(
paymentIntent.payment_intent_id,
{
payment_method: {
type: 'mobile_money',
phone_number: '+237987654321',
mobile_money_provider: 'mtn_momo',
},
customer: {
name: 'Jane Smith',
email: '[email protected]',
},
}
);
// Get payment intent details
const details = await cloudBank.payments.intents.get(paymentIntent.payment_intent_id);Checkout Sessions
Checkout sessions provide a hosted payment experience for your customers.
// Create a checkout session
const session = await cloudBank.checkout.sessions.create({
amount: 25000,
external_id: 'checkout-789',
cancel_url: 'https://yourapp.com/cancel',
success_url: 'https://yourapp.com/success',
failure_url: 'https://yourapp.com/failure',
customer: {
name: 'Alice Johnson',
email: '[email protected]',
phone_number: '+237555123456',
},
line_items: [
{
type: 'product',
name: 'Premium Plan',
quantity: 1,
unit_amount: 25000,
description: 'Monthly premium subscription',
},
],
payment_method_types: ['mobile_money', 'card'],
});
console.log('Checkout URL:', session.checkout_url);
// Validate a checkout session (webhook validation)
const validated = await cloudBank.checkout.sessions.validate(session.session_id, {
sig: 'webhook-signature',
encoded_state: 'encoded-state-from-webhook',
});
// Get checkout session details
const sessionDetails = await cloudBank.checkout.sessions.get(session.session_id);Account Management
Manage your CloudBank accounts and view balances.
// List all accounts
const accounts = await cloudBank.accounts.list();
// Get specific account details
const account = await cloudBank.accounts.get('acct_123456789');
console.log('Available balance:', account.balances.available_balance);
console.log('Account status:', account.status);Payment Retrieval
Retrieve completed payment details.
// Get payment details
const payment = await cloudBank.payments.retrieve('pay_123456789');
console.log('Payment status:', payment.status);
console.log('Payment amount:', payment.amount);
console.log('Payment method:', payment.payment_method);Payment Methods
CloudBank supports multiple payment methods across African markets:
Mobile Money
{
type: 'mobile_money',
phone_number: '+237123456789',
mobile_money_provider: 'mtn_momo' | 'airtel_money',
account_holder_name: 'John Doe', // optional
}Card Payments
{
type: 'card',
brand: 'VISA' | 'MASTERCARD' | 'AMERICAN_EXPRESS' | 'UNIONPAY',
last4: '4242',
card_type: 'CREDIT' | 'DEBIT' | 'PREPAID',
card_holder: {
name: 'John Doe',
email: '[email protected]',
},
expiry_year: 25,
expiry_month: 12,
}Bank Account
{
type: 'bank_account',
bank_brand: 'postal_bank',
account_type: 'checking' | 'savings',
account_number: '1234567890',
}Error Handling
The SDK provides comprehensive error handling with detailed error information:
import { HttpError } from '@cloudbank/sdk';
try {
const payment = await cloudBank.payments.intents.create({
amount: { value: -100, currency: 'XAF' }, // Invalid amount
external_id: 'test-payment',
});
} catch (error) {
if (error instanceof HttpError) {
console.error('HTTP Error:', error.status);
console.error('Error details:', error.body);
switch (error.status) {
case 400:
console.error('Bad request - check your parameters');
break;
case 401:
console.error('Authentication failed - check your access token');
break;
case 403:
console.error('Access denied - insufficient permissions');
break;
case 422:
console.error('Validation error:', error.body);
break;
case 429:
console.error('Rate limited - please slow down your requests');
break;
default:
console.error('Unexpected error occurred');
}
} else {
console.error('Network or other error:', error);
}
}Configuration
Provider Configuration
The SDK supports multiple provider distributions with different API endpoints:
CloudBank (Default)
const cloudBank = createCloudBank({
accessToken: 'your-cloudbank-token',
provider: 'cloudbank', // Optional, defaults to 'cloudbank'
environment: 'production',
});
// Uses: https://api.cloudbank.fnstack.devMagePay
const magePay = createCloudBank({
accessToken: 'your-magepay-token',
provider: 'magepay',
environment: 'production',
});
// Uses: https://api.magepay.appEnvironment Configuration
Staging Environment
const cloudBank = createCloudBank({
accessToken: 'your-staging-token',
provider: 'cloudbank',
environment: 'staging',
});
// Uses: https://staging.api.cloudbank.fnstack.devProduction Environment
const cloudBank = createCloudBank({
accessToken: 'your-production-token',
provider: 'cloudbank',
environment: 'production',
});
// Uses: https://api.cloudbank.fnstack.devProvider-Environment Combinations
The SDK automatically constructs the correct API endpoint based on your provider and environment:
| Provider | Environment | API Endpoint |
|----------|------------|--------------|
| cloudbank | production | https://api.cloudbank.fnstack.dev |
| cloudbank | staging | https://staging.api.cloudbank.fnstack.dev |
| magepay | production | https://api.magepay.app |
| magepay | staging | https://staging.api.magepay.app |
Custom Configuration
const cloudBank = createCloudBank({
accessToken: 'your-token',
baseUrl: 'https://custom-api-endpoint.com', // Overrides provider/environment
timeout: 60000, // 60 seconds
userAgent: 'MyApp/1.0',
});TypeScript Support
The SDK is built with TypeScript and provides comprehensive type definitions:
import type {
CloudBankClient,
Configuration,
PaymentIntent,
PaymentIntentStatus,
CheckoutSession,
Account,
Payment,
HttpError,
} from '@cloudbank/sdk';
// Type-safe client usage
const client: CloudBankClient = createCloudBank(config);
// Type-safe response handling
const payment: PaymentIntent = await client.payments.intents.create({
// TypeScript will provide autocomplete and validation
});Supported Currencies
CloudBank supports the following African currencies:
- XAF - Central African CFA Franc (Cameroon, Chad, Central African Republic, Republic of the Congo, Equatorial Guinea, Gabon)
- XOF - West African CFA Franc (Benin, Burkina Faso, Côte d'Ivoire, Guinea-Bissau, Mali, Niger, Senegal, Togo)
- CDF - Congolese Franc (Democratic Republic of the Congo)
- EUR - Euro (for international transactions)
Rate Limiting
CloudBank implements rate limiting to ensure fair usage:
- Production: 1000 requests per minute per API key
- Staging: 100 requests per minute per API key
When rate limited, you'll receive a 429 status code. Implement exponential backoff in your retry logic.
Webhooks
Handle CloudBank webhooks to receive real-time payment notifications:
// Validate webhook signatures
const isValid = await cloudBank.checkout.sessions.validate(sessionId, {
sig: req.headers['x-cloudbank-signature'],
encoded_state: req.body.encoded_state,
});
if (isValid) {
// Process webhook payload
console.log('Valid webhook received');
}Migration Guide
Provider Configuration (Latest)
Breaking Change: The SDK now requires explicit provider configuration to support multiple API distributions (CloudBank and MagePay).
Migration Steps
Add provider field: Update your configuration to include the
providerfield// Before (will still work - defaults to 'cloudbank') const client = createCloudBank({ accessToken: 'your-token', environment: 'production', }); // After (recommended - explicit provider) const client = createCloudBank({ accessToken: 'your-token', provider: 'cloudbank', environment: 'production', });For MagePay users: Specify the MagePay provider
const client = createCloudBank({ accessToken: 'your-magepay-token', provider: 'magepay', environment: 'production', });Custom baseUrl: If you were using a custom
baseUrl, no changes needed// This continues to work - baseUrl overrides provider/environment const client = createCloudBank({ accessToken: 'your-token', baseUrl: 'https://custom-endpoint.com', });
What Changed?
- Added:
providerfield to configuration (optional, defaults to"cloudbank") - Changed: URL construction now uses both
providerandenvironment - Backward Compatible: Existing code without
providerdefaults to CloudBank
Provider-to-URL Mapping
| Configuration | Generated URL |
|--------------|---------------|
| { provider: "cloudbank", environment: "production" } | https://api.cloudbank.fnstack.dev |
| { provider: "cloudbank", environment: "staging" } | https://staging.api.cloudbank.fnstack.dev |
| { provider: "magepay", environment: "production" } | https://api.magepay.app |
| { provider: "magepay", environment: "staging" } | https://staging.api.magepay.app |
| { environment: "production" } (no provider) | https://api.cloudbank.fnstack.dev (default) |
From v0.0.x to v0.1.x
Import changes: Update import statements
// Before import CloudBank from '@cloudbank/sdk'; // After import { createCloudBank } from '@cloudbank/sdk';Client initialization: Use the new factory function
// Before const client = new CloudBank({ accessToken: 'token' }); // After const client = createCloudBank({ accessToken: 'token' });Error handling: Update error handling for new error types
// Before catch (error) { /* generic error */ } // After import { HttpError } from '@cloudbank/sdk'; catch (error) { if (error instanceof HttpError) { // Handle HTTP errors specifically } }
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Documentation: https://docs.cloudbank.fnstack.dev
- API Reference: https://api.cloudbank.fnstack.dev/docs
- GitHub Issues: Report a bug or request a feature
- Email: [email protected]
Related Packages
- @cloudbank/sdk-magepay - MagePay Partner Edition SDK
- @cloudbank/nextjs - Next.js integration helpers
