A simple and powerful SDK for integrating ModemPay payments into your applications
npm install modempay-sdkbash
npm install modempay-sdk
`
Quick Start
$3
`typescript
import { createModemPay } from 'modempay-sdk';
// Initialize ModemPay
const modempay = createModemPay({
secretKey: process.env.MODEMPAY_SECRET_KEY!,
webhookSecret: process.env.MODEMPAY_WEBHOOK_SECRET,
publicKey: process.env.NEXT_PUBLIC_MODEMPAY_PUBLIC_KEY,
});
`
$3
`typescript
// Create a payment intent
const payment = await modempay.createPaymentIntent({
amount: 1000, // Amount in smallest currency unit (e.g., 1000 = 10.00 GMD)
currency: 'GMD',
metadata: {
userId: 'user123',
courseId: 'course456',
},
customerName: 'John Doe',
customerEmail: 'john@example.com',
customerPhone: '7000001',
returnUrl: 'https://yourapp.com/success',
cancelUrl: 'https://yourapp.com/cancel',
});
console.log('Payment Link:', payment.paymentLink);
console.log('Payment Intent ID:', payment.paymentIntentId);
// Redirect user to payment link
window.location.href = payment.paymentLink;
`
$3
`typescript
// Verify payment status
const verification = await modempay.verifyPayment('payment_intent_id_here');
if (verification.success) {
console.log('Payment Status:', verification.paymentStatus);
console.log('ModemPay Status:', verification.modemPayStatus);
if (verification.paymentStatus === 'COMPLETED') {
// Payment successful - update your database
await updateUserEnrollment(userId, courseId);
}
}
`
$3
`typescript
import { ModemPayWebhookHandler } from 'modempay-sdk';
// Create webhook handler
const webhookHandler = new ModemPayWebhookHandler({
onChargeSucceeded: async (event) => {
const paymentIntentId = event.payload.payment_intent_id;
const metadata = event.payload.metadata;
// Update payment status in your database
await updatePaymentStatus(paymentIntentId, 'COMPLETED');
// Handle successful payment (e.g., grant access, send email)
if (metadata?.userId && metadata?.courseId) {
await enrollUserInCourse(metadata.userId, metadata.courseId);
}
},
onChargeFailed: async (event) => {
const paymentIntentId = event.payload.payment_intent_id;
await updatePaymentStatus(paymentIntentId, 'FAILED');
},
onChargeCancelled: async (event) => {
const paymentIntentId = event.payload.payment_intent_id;
await updatePaymentStatus(paymentIntentId, 'CANCELLED');
},
});
// In your API route (Next.js example)
export async function POST(req: Request) {
try {
const payload = await req.json();
const signature = req.headers.get('x-modem-signature')!;
const event = modempay.handleWebhook(payload, signature);
await webhookHandler.processEvent(event);
return Response.json({ received: true });
} catch (error) {
console.error('Webhook error:', error);
return Response.json({ error: 'Webhook processing failed' }, { status: 500 });
}
}
`
$3
`typescript
import express from 'express';
import { createWebhookMiddleware } from 'modempay-sdk';
const app = express();
app.use(express.json());
// Use the webhook middleware
app.post('/api/webhooks/modempay', createWebhookMiddleware(modempay, webhookHandler));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
`
$3
`html
`
API Reference
$3
#### Constructor
`typescript
new ModemPay(config: ModemPayConfig)
`
#### Methods
##### createPaymentIntent(options: PaymentIntentOptions): Promise
Creates a new payment intent.
##### verifyPayment(paymentIntentId: string): Promise
Verifies the status of a payment intent.
##### getPaymentIntent(paymentIntentId: string): Promise
Retrieves details of a payment intent.
##### handleWebhook(payload: any, signature: string): any
Validates and parses webhook payload.
$3
`typescript
interface ModemPayConfig {
secretKey: string;
webhookSecret?: string;
publicKey?: string;
}
interface PaymentIntentOptions {
amount: number;
currency?: string;
metadata?: Record;
customerName?: string;
customerEmail?: string;
customerPhone?: string;
returnUrl?: string;
cancelUrl?: string;
}
enum PaymentStatus {
PENDING = 'PENDING',
COMPLETED = 'COMPLETED',
FAILED = 'FAILED',
CANCELLED = 'CANCELLED'
}
`
Environment Variables
`bash
MODEMPAY_SECRET_KEY=your_secret_key_here
MODEMPAY_WEBHOOK_SECRET=your_webhook_secret_here
NEXT_PUBLIC_MODEMPAY_PUBLIC_KEY=your_public_key_here
`
Error Handling
The SDK throws errors for invalid configurations or API failures. Always wrap your calls in try-catch blocks:
`typescript
try {
const payment = await modempay.createPaymentIntent(options);
// Handle success
} catch (error) {
console.error('Payment creation failed:', error);
// Handle error
}
``