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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mds-daraja-sdk

v1.1.11

Published

A simple SDK for integrating with Safaricom's Daraja API for M-Pesa payments.

Downloads

779

Readme

MDS DARAJA SDK

The mds-daraja-sdk is a simple, easy-to-use Node.js SDK for integrating with the Safaricom M-Pesa API. It supports key M-Pesa functionalities such as STK Push, B2C payments, and transaction reversals. This SDK works with both JavaScript and TypeScript environments.

Table of Contents


Installation

To install the SDK, simply run:

npm install mds-daraja-sdk

Or with Yarn:

yarn add mds-daraja-sdk

Usage

Importing the SDK

The SDK can be imported in both JavaScript and TypeScript projects.

  • JavaScript:

    const { MdsDarajaSdk } = require('mds-daraja-sdk');
  • TypeScript:

    import { MdsDarajaSdk } from 'mds-daraja-sdk';

Initialization

To start using the SDK, you need to create an instance of the MdsDarajaSdk class. The constructor takes three arguments:

  1. Consumer Key (from Safaricom Developer Portal)
  2. Consumer Secret (from Safaricom Developer Portal)
  3. Sandbox Mode (optional, default is true)

Example:

const sdk = new MdsDarajaSdk('your-consumer-key', 'your-consumer-secret', true); // Sandbox mode

For production use:

const sdk = new MdsDarajaSdk('your-consumer-key', 'your-consumer-secret', false); // Production mode

STK Push

The STK Push feature allows you to initiate a payment request to a customer's phone. It requires the following parameters:

  • businessShortCode: The short code of your M-Pesa Paybill or Till Number.
  • password: Base64-encoded string derived from your short code, passkey, and timestamp.
  • timestamp: The current timestamp in the format yyyyMMddHHmmss.
  • phoneNumber: The customer's phone number (in the format 2547XXXXXXXX).
  • amount: The amount to be paid.
  • callbackUrl: The URL Safaricom will call to confirm payment status.

Example:

const businessShortCode = '174379'; // Your shortcode
const passkey = 'your-lipa-na-mpesa-passkey'; // Safaricom passkey
const timestamp = MdsDarajaSdk.generateTimeStamp();
const password = MdsDarajaSdk.generatePassword(businessShortCode, passkey);
const phoneNumber = '254712345678'; // Customer's phone number
const amount = 100;
const callbackUrl = 'https://example.com/callback';

sdk.initiateStkPush(businessShortCode, password, timestamp, phoneNumber, amount, callbackUrl)
  .then(response => console.log('STK Push Response:', response))
  .catch(error => console.error('STK Push Error:', error));

Transaction Reversal

The transaction reversal feature allows you to reverse a mistaken transaction.

Parameters:

  • shortCode: The short code initiating the reversal.
  • password: Security credential.
  • transactionID: The ID of the transaction to be reversed.

Example:

const shortCode = '600000'; // Your shortcode
const password = 'your-security-credential'; // Safaricom security credential
const transactionID = 'LKXXXX1234'; // The ID of the transaction to reverse

sdk.reverseTransaction(shortCode, password, transactionID)
  .then(response => console.log('Reversal Response:', response))
  .catch(error => console.error('Reversal Error:', error));

B2C Payments

B2C (Business to Customer) payments allow you to send money from your business to a customer.

Parameters:

  • shortCode: The short code initiating the payment.
  • password: Security credential.
  • timestamp: The current timestamp.
  • phoneNumber: The customer's phone number.
  • amount: The amount to be paid.

Example:

const shortCode = '600000'; // Your shortcode
const password = 'your-security-credential'; // Safaricom security credential
const timestamp = MdsDarajaSdk.generateTimeStamp();
const phoneNumber = '254712345678'; // Recipient's phone number
const amount = 1000; // Amount to send

sdk.initiateB2cPayment(shortCode, password, timestamp, phoneNumber, amount)
  .then(response => console.log('B2C Response:', response))
  .catch(error => console.error('B2C Error:', error));

Utilities

Generate Password

The password for STK Push is generated using your Business Short Code, Passkey, and a timestamp.

const password = MdsDarajaSdk.generatePassword('shortCode', 'passkey');

Generate Timestamp

Generate a Safaricom-compliant timestamp in the format yyyyMMddHHmmss:

const timestamp = MdsDarajaSdk.generateTimeStamp();

Error Handling

All methods return a Promise. Use .then() and .catch() to handle the responses and errors.

Example:

sdk.initiateStkPush(businessShortCode, password, timestamp, phoneNumber, amount, callbackUrl)
  .then(response => {
    console.log('STK Push successful:', response);
  })
  .catch(error => {
    console.error('Error initiating STK Push:', error);
  });

Common error scenarios include:

  • Invalid consumer key or secret.
  • Incorrect API credentials.
  • Network-related issues.

For detailed error codes, consult the M-Pesa API Documentation.


Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository.
  2. Create a new feature branch (git checkout -b feature-branch).
  3. Commit your changes (git commit -m 'Add new feature').
  4. Push to the branch (git push origin feature-branch).
  5. Open a pull request.

For major changes, please open an issue first to discuss what you would like to change.


License

This project is licensed under the MIT License. See the LICENSE file for more details.


Notes

  1. Ensure your callback URLs are publicly accessible when testing M-Pesa API features like STK Push and B2C payments.
  2. For security, make sure you do not expose sensitive credentials (consumer key, secret, passkey, etc.) in your production code or version control.