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

sain-mpesa-sdk

v1.0.18

Published

mpesa sdk

Downloads

20

Readme

Sain Mpesa SDK Package

The sain-mpesa-sdk package provides a convenient way to interact with Mpesa APIs using context-based authentication and session management. Register at mpesa openApi developers portal to get you apikey and publicKey.

Installation

You can install the package via npm:

npm install sain-mpesa-sdk

Usage

To use the Mpesa class, you need to instantiate it with the required parameters to get mpesa session instance to use all the time until the session expires. The SDK will request another session incase it expires using the same instance parameters you provide:

const Mpesa = require('sain-mpesa-sdk');

// Instantiate mpesa with required parameters

const mpesa = new Mpesa(
    {   
      endpoint: process.env.API_ENDPOINT,
      apiKey: process.env.SANDBOX_API_KEY || process.env.API_KEY,
      publicKey:process.env.PUBLIC_KEY
    }
);
  • make use of the mpesa instance to interact with the await mpesa. Below is a documentation of the methods found on the SDK instance.

Create direct debit

createDirectDebit() Direct Debits are payments in M-Pesa that are initiated by the Payee alone without any Payer interaction, but permission must first be granted by the Payer. The granted permission from the Payer to Payee is commonly termed a ‘Mandate’, and M-Pesa must hold details of this Mandate.

The Direct Debit API set allows an organisation to get the initial consent of their customers to create the Mandate that allows the organisation to debit customer's account at an agreed frequency and amount for services rendered. After the initial consent, the debit of the account will not involve any customer interaction. The Direct Debit feature makes use of the following API calls:

  • Create a Direct Debit mandate
  • Pay a mandate

The customer is able to view and cancel the Direct Debit mandate from G2 menu accessible via USSD menu or the Smartphone Application

try {
   const payload = {
          input_AgreedTC: "1",
          input_Country: "TZN", // Country code
          input_CustomerMSISDN: "000000000001", // Customer phone number
          input_EndRangeOfDays: "22", // End date of the direct debit
          input_ExpiryDate: "20161126", // Expiry date of the direct debit
          input_FirstPaymentDate: "20160324", // First payment date of the direct debit
          input_Frequency: "06", //# Frequency of the direct debit
          input_Amount: "1000", // Amount of the direct debit
          input_ServiceProviderCode: "000000", //
          input_StartRangeOfDays: "01", // Start date of the direct debit
          input_ThirdPartyConversationID: "AAA6d1f9391a0052de0b5334a912jbsj1j2kk", //
          input_ThirdPartyReference: "3333", //
        };
  const response = await mpesa.createDirectDebit(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error creating direct debit:', error);
}

Query direct debit

queryDirectDebit(payload) This method is used to query and push for direct debit payment!.

try {
 let payload = {
      input_QueryBalanceAmount: "True", //if the amount can be debited
      input_BalanceAmount: "100", // amount to be debited
      input_Country: "TZN", // Tanzania code
      input_CustomerMSISDN: "255744553111", // phone number
      input_MsisdnToken: "cvgwUBZ3lAO9ivwhWAFeng==", //token
      input_ServiceProviderCode: "112244", // shortcode from account
      input_ThirdPartyConversationID: "GPO3051656128", // order-id
      input_ThirdPartyReference: "Test123", //generated control number
      input_MandateID: "15045", // code generated by mpesa
      input_Currency: "TZS", // currency
    }
  const response = await mpesa.queryDirectDebit(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error creating direct debit:', error);
}

Direct debit payment

directDebitPayment(payload) This method is used to pay direct debit payment!.

try {
 let payload = {
      "input_Amount": "10",
      "input_Country": "TZN",
      "input_Currency": "TZS",
      "input_CustomerMSISDN": "000000000001",
      "input_ServiceProviderCode": "000000",
      "input_ThirdPartyConversationID": "AAA6d1f939c1005v2de053v4912jbasdj1j2kk",
      "input_MandateID": "15045",
      "input_ThirdPartyReference": "5db410b459bd433ca8e5"
      }
    
  const response = await mpesa.directDebitPayment(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error paying direct debit:', error);
}

Cancel direct debit

directDebitCancel() This method is used to cancel direct debit payment!.

try {
   const payload = {
  "input_Country": "TZN",
  "input_CustomerMSISDN": "000000000001",
  "input_ServiceProviderCode": "000000",
  "input_ThirdPartyConversationID": "AAA6d1f939c1005v2de053v4912jbasdj1j2kk",
  "input_MandateID": "15045",
  "input_ThirdPartyReference": "00000000000000000001"
};
  const response = await mpesa.directDebitCancel(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error canceling direct debit:', error);
}

B2C Payment

b2c() The B2C API Call is used as a standard business-to-customer funds disbursement. Funds from the business account’s wallet will be deducted and paid to the mobile money wallet of the customer. Use cases for the B2C includes:

  • Salary payments
  • Funds transfers from business
  • Charity pay-out.
try {
   const payload = {
      input_Amount: "10",
      input_Country: "TZN",
      input_Currency: "TZS",
      input_CustomerMSISDN: "000000000001",
      input_ServiceProviderCode: "000000",
      input_ThirdPartyConversationID: "asv02e5958774f7ba228d83d0d689761",
      input_TransactionReference: "T1234C",
      input_PaymentItemsDesc: "Salary payment"
};
  const response = await mpesa.b2c(payload);
  console.log(response.data);
} catch (error) {
  console.error('B2C error:', error);
}

## Response
#{
#  "output_ConversationID": "d3502e5958774f7ba228d83d0d689761", 
#  "output_ResponseCode": "INS-0",
#  "output_ResponseDesc": "Request processed successfully",
#  "output_TransactionID": "49XCD123F6", 
#  "output_ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
#}

C2B Payment

c2b() The C2B API call is used as a standard customer-to-business transaction. Funds from the customer’s mobile money wallet will be deducted and be transferred to the mobile money wallet of the business. To authenticate and authorize this transaction, M-Pesa Payments Gateway will initiate a USSD Push message to the customer to gather and verify the mobile money PIN number. This number is not stored and is used only to authorize the transaction.

try {
   const payload = {
    "input_Amount": "10", 
    "input_Country": "TZN", 
    "input_Currency": "TZS", 
    "input_CustomerMSISDN": "000000000001", 
    "input_ServiceProviderCode": "000000", 
    "input_ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761", 
    "input_TransactionReference": "T1234C",
    "input_PurchasedItemsDesc": "Shoes"
  };
  const response = await mpesa.c2b(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error pushing c2b payment:', error);
}

## Response
#{
#  "output_ConversationID": "d3502e5958774f7ba228d83d0d689761", 
#  "output_ResponseCode": "INS-0",
#  "output_ResponseDesc": "Request processed successfully",
#  "output_TransactionID": "49XCD123F6", 
#  "output_ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
#}

Reversal

reverse() The Reversal API is used to reverse a successful transaction. Using the Transaction ID of a previously successful transaction, the OpenAPI will withdraw the funds from the recipient party’s mobile money wallet and revert the funds to the mobile money wallet of the initiating party of the original transaction.

try {
   const  payload = {
      input_ReversalAmount: "25",
      input_Country: "TZN",
      input_ServiceProviderCode: "000000",
      input_ThirdPartyConversationID: "asv02e5958774f7ba228d83d0d689761",
      input_TransactionID: "0000000000001",
      // Add other parameters as needed
    };
  const response = await mpesa.reverse(payload);
  console.log(response.data);
} catch (error) {
  console.error('Error reversing payment:', error);
}

## Response
#{
#  "output_ResponseCode": "INS-0",
#  "output_ResponseDesc": "Request processed successfully",
#  "output_TransactionID": "49XCD123F6",
#  "output_ConversationID": "d3502e5958774f7ba228d83d0d689761",
#  "output_ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
#}

For more information please view mpesa openAPI documentation

License

This package is open source and available under the MIT License.