modempay-sdk
v1.0.0
Published
A simple and powerful SDK for integrating ModemPay payments into your applications
Maintainers
Readme
ModemPay SDK
A simple and powerful SDK for integrating ModemPay payments into your applications. Just like Clerk handles authentication, this SDK handles the heavy lifting for ModemPay payment processing.
Installation
npm install modempay-sdkQuick Start
Basic Setup
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,
});Creating a Payment Intent
// 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: '[email protected]',
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;Verifying Payment Status
// 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);
}
}Handling Webhooks
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 });
}
}Express.js Integration
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');
});Frontend Integration (HTML Form)
<form action="https://test.checkout.modempay.com/api/pay" method="POST">
<input type="hidden" name="public_key" value="your_public_key" />
<input type="hidden" name="amount" value="1000" />
<input type="hidden" name="customer_name" value="John Doe" />
<input type="hidden" name="customer_email" value="[email protected]" />
<input type="hidden" name="customer_phone" value="7000001" />
<input type="hidden" name="currency" value="GMD" />
<input type="hidden" name="return_url" value="https://yourapp.com/success" />
<input type="hidden" name="cancel_url" value="https://yourapp.com/cancel" />
<input type="hidden" name="metadata" value='{"userId": "123", "courseId": "456"}' />
<button type="submit">Pay Now</button>
</form>API Reference
ModemPay Class
Constructor
new ModemPay(config: ModemPayConfig)Methods
createPaymentIntent(options: PaymentIntentOptions): Promise<CreatePaymentResult>
Creates a new payment intent.
verifyPayment(paymentIntentId: string): Promise<PaymentVerificationResult>
Verifies the status of a payment intent.
getPaymentIntent(paymentIntentId: string): Promise<PaymentIntent>
Retrieves details of a payment intent.
handleWebhook(payload: any, signature: string): any
Validates and parses webhook payload.
Types
interface ModemPayConfig {
secretKey: string;
webhookSecret?: string;
publicKey?: string;
}
interface PaymentIntentOptions {
amount: number;
currency?: string;
metadata?: Record<string, any>;
customerName?: string;
customerEmail?: string;
customerPhone?: string;
returnUrl?: string;
cancelUrl?: string;
}
enum PaymentStatus {
PENDING = 'PENDING',
COMPLETED = 'COMPLETED',
FAILED = 'FAILED',
CANCELLED = 'CANCELLED'
}Environment Variables
MODEMPAY_SECRET_KEY=your_secret_key_here
MODEMPAY_WEBHOOK_SECRET=your_webhook_secret_here
NEXT_PUBLIC_MODEMPAY_PUBLIC_KEY=your_public_key_hereError Handling
The SDK throws errors for invalid configurations or API failures. Always wrap your calls in try-catch blocks:
try {
const payment = await modempay.createPaymentIntent(options);
// Handle success
} catch (error) {
console.error('Payment creation failed:', error);
// Handle error
}Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see LICENSE file for details.
