npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@chabifadeen/mtn-momo

v1.0.0

Published

Professional Node.js SDK for MTN Mobile Money API integration

Readme

mtn-momo-nodejs

Un kit de développement logiciel (SDK) Node.js professionnel, robuste et facile à utiliser pour l'intégration des API MTN Mobile Money (collecte, décaissement, transfert de fonds).

💰 MTN MoMo SDK for Node.js

npm version License: MIT TypeScript

A professional, robust, and easy-to-use Node.js SDK for integrating MTN Mobile Money APIs (Collection, Disbursement, Remittance).

✨ Features

  • 🔐 Automatic Authentication: Token generation, caching, and auto-refresh
  • 📦 Modular Services: Separate modules for Collection, Disbursement, and Remittance
  • 🛡️ Full TypeScript Support: Complete type definitions and IntelliSense
  • Promise-based API: Modern async/await syntax
  • 🔄 Sandbox & Production: Easy environment switching
  • 🧪 Well Tested: Comprehensive unit test coverage
  • 🚨 Error Handling: Custom error classes for better debugging

📦 Installation

npm install @chabifadeen/mtn-momo

or with yarn:

yarn add @chabifadeen/mtn-momo

🚀 Quick Start

1. Configuration

import { Client, MoMoConfig } from '@chabifadeen/mtn-momo';

const config: MoMoConfig = {
  environment: 'sandbox', // or 'production'
  subscriptionKey: 'YOUR_SUBSCRIPTION_KEY',
  apiUser: 'YOUR_API_USER',
  apiKey: 'YOUR_API_KEY',
  callbackUrl: 'https://your-webhook.com/callback', // Optional
};

const client = new Client(config);

2. Collection API (Request to Pay)

Request payment from a customer:

const collection = client.collection();

// Request payment
const referenceId = await collection.requestToPay({
  amount: '500',
  currency: 'EUR',
  externalId: 'order-123',
  payer: {
    partyIdType: 'MSISDN',
    partyId: '256774290781',
  },
  payerMessage: 'Payment for goods',
  payeeNote: 'Thanks for your purchase',
});

console.log('Transaction Reference:', referenceId);

// Check transaction status
const status = await collection.getTransactionStatus(referenceId);
console.log('Status:', status.status); // SUCCESSFUL, FAILED, PENDING
console.log('Amount:', status.amount);
console.log('Currency:', status.currency);

// Get account balance
const balance = await collection.getAccountBalance();
console.log('Available Balance:', balance.availableBalance);

// Validate account holder
const isValid = await collection.validateAccountHolder({
  partyIdType: 'MSISDN',
  partyId: '256774290781',
});
console.log('Account Valid:', isValid);

3. Disbursement API (Transfer Money)

Transfer money to a recipient:

const disbursement = client.disbursement();

// Transfer money
const referenceId = await disbursement.transfer({
  amount: '100',
  currency: 'EUR',
  externalId: 'salary-001',
  payee: {
    partyIdType: 'MSISDN',
    partyId: '256774290781',
  },
  payerMessage: 'Salary payment',
  payeeNote: 'Monthly salary - November 2024',
});

// Check transfer status
const status = await disbursement.getTransferStatus(referenceId);
console.log('Transfer Status:', status.status);

// Get account balance
const balance = await disbursement.getAccountBalance();
console.log('Balance:', balance);

4. Remittance API (International Transfers)

Send money internationally:

const remittance = client.remittance();

// Send remittance
const referenceId = await remittance.transfer({
  amount: '200',
  currency: 'EUR',
  externalId: 'remit-001',
  payee: {
    partyIdType: 'MSISDN',
    partyId: '256774290781',
  },
  payerMessage: 'Money transfer',
  payeeNote: 'Family support',
});

// Check status
const status = await remittance.getTransferStatus(referenceId);
console.log('Remittance Status:', status);

🔧 Advanced Usage

Custom Configuration

const config: MoMoConfig = {
  environment: 'production',
  subscriptionKey: process.env.MTN_SUBSCRIPTION_KEY!,
  apiUser: process.env.MTN_API_USER!,
  apiKey: process.env.MTN_API_KEY!,
  callbackUrl: 'https://api.myapp.com/webhooks/mtn',
  timeout: 30000, // Request timeout in ms
  retryAttempts: 3, // Number of retry attempts
};

Environment Variables

Create a .env file:

MTN_ENVIRONMENT=sandbox
MTN_SUBSCRIPTION_KEY=your_subscription_key
MTN_API_USER=your_api_user
MTN_API_KEY=your_api_key
MTN_CALLBACK_URL=https://your-webhook.com/callback

Then use in your code:

import * as dotenv from 'dotenv';
dotenv.config();

const config: MoMoConfig = {
  environment: process.env.MTN_ENVIRONMENT as 'sandbox' | 'production',
  subscriptionKey: process.env.MTN_SUBSCRIPTION_KEY!,
  apiUser: process.env.MTN_API_USER!,
  apiKey: process.env.MTN_API_KEY!,
  callbackUrl: process.env.MTN_CALLBACK_URL,
};

Error Handling

The SDK provides custom error classes for better error handling:

import {
  MoMoError,
  MoMoAuthError,
  MoMoValidationError,
  MoMoTransactionError,
  MoMoNetworkError
} from '@chabifadeen/mtn-momo';

try {
  const referenceId = await collection.requestToPay({
    // ... payment details
  });
} catch (error) {
  if (error instanceof MoMoAuthError) {
    console.error('Authentication failed:', error.message);
    // Handle authentication issues (refresh credentials, etc.)
  } else if (error instanceof MoMoValidationError) {
    console.error('Validation error:', error.message);
    // Handle validation errors (check input data)
  } else if (error instanceof MoMoTransactionError) {
    console.error('Transaction failed:', error.message, error.code);
    // Handle transaction failures
  } else if (error instanceof MoMoNetworkError) {
    console.error('Network error:', error.message);
    // Handle network issues (retry, etc.)
  } else if (error instanceof MoMoError) {
    console.error('MoMo error:', error.message);
    // Handle generic MoMo errors
  } else {
    console.error('Unexpected error:', error);
  }
}

Webhook Handling

Handle MTN callbacks in your Express app:

import express from 'express';

const app = express();
app.use(express.json());

app.post('/webhooks/mtn', (req, res) => {
  const notification = req.body;
  
  console.log('Payment notification:', notification);
  console.log('Reference ID:', notification.referenceId);
  console.log('Status:', notification.status);
  console.log('Amount:', notification.amount);
  
  // Process the notification
  // Update your database, send confirmation email, etc.
  
  res.sendStatus(200);
});

app.listen(3000);

🧪 Testing

The SDK includes comprehensive tests. Run them with:

npm test

For coverage report:

npm run test:coverage

📖 API Reference

Client

new Client(config: MoMoConfig)

Collection Service

  • requestToPay(params) - Request payment from customer
  • getTransactionStatus(referenceId) - Get transaction status
  • getAccountBalance() - Get account balance
  • validateAccountHolder(params) - Validate account holder
  • getAccountInfo(accountHolderId) - Get account information

Disbursement Service

  • transfer(params) - Transfer money to recipient
  • getTransferStatus(referenceId) - Get transfer status
  • getAccountBalance() - Get account balance
  • validateAccountHolder(params) - Validate recipient

Remittance Service

  • transfer(params) - Send international transfer
  • getTransferStatus(referenceId) - Get transfer status
  • getAccountBalance() - Get account balance

🌍 Supported Countries

MTN Mobile Money is available in multiple African countries. Check MTN's official documentation for the latest list of supported countries and currencies.

📚 Resources

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

👨‍💻 Author

CHABI DOSSOUMON Abdou Fawaz

⭐ Support

If you find this SDK helpful, please give it a star on GitHub!


Made with ❤️ for the African developer community