M-Pesa Node Library

repository·master·Indexed 41 days ago

https://github.com/safaricom/mpesa-node-library

A Node.js library for interacting with the M-Pesa REST API (Daraja). Version 0.1.3 provides a modular interface for M-Pesa transactions, including B2B, B2C, C2B, Lipa Na M-Pesa (STK Push), account balance requests, and transaction reversals.

Tokens
7.4K
Snippets
28
Records
30
Agent score
51%

What's inside M-Pesa Node

  1. Initialize the Mpesa instance

    master

    The library is modular and allows for multiple instances. At a minimum, you must provide consumerKey and consumerSecret. You can also prefill configuration options like environment, shortCode, and certPath to avoid re-entering them for every call.

    All methods in the Mpesa class return a Promise and can be used with .then() or await. Responses follow the Axios response structure.

    const Mpesa = require('mpesa-node')
    
    // Basic initialization
    const mpesaApi = new Mpesa({
        consumerKey: '<your consumer key>',
        consumerSecret: '<your consumer secret'
    })
    
    // Full configuration example
    const mpesaApiFull = new Mpesa({
        consumerKey: '<your consumer key>',
        consumerSecret: '<your consumer secret>',
        environment: 'sandbox', // or 'production'
        shortCode: '600111',
        initiatorName: 'Test Initiator',
        lipaNaMpesaShortCode: 123456,
        lipaNaMpesaShortPass: '<some key here>',
        securityCredential: '<credential here>',
        certPath: path.resolve('keys/myKey.cert')
    })
  2. Configure the environment for production

    master

    To move from sandbox to production, ensure you have clicked 'Going Live' on the Daraja portal and update the environment key in your configuration object to 'production'.

    new Mpesa({
        consumerKey: '<your consumer key>',
        consumerSecret: '<your consumer secret>',
        environment: 'production',
        // ... other config
    })
  3. Initialize the Mpesa client

    master

    To use the SDK, instantiate the Mpesa class with a configuration object. The configuration requires consumerKey and consumerSecret. You can also specify the environment as either 'production' or 'sandbox' (defaults to 'sandbox').

    Required configuration keys:

    • consumerKey: Your Safaricom consumer key.
    • consumerSecret: Your Safaricom consumer secret.
    • environment: 'production' or 'sandbox' (default).
    • certPath: Path to your security certificate (used by the security() method).
    • securityCredential: Your security credential (used by the security() method).
    const Mpesa = require('./src/m-pesa');
    
    const mpesa = new Mpesa({
      consumerKey: 'YOUR_CONSUMER_KEY',
      consumerSecret: 'YOUR_CONSUMER_SECRET',
      environment: 'sandbox',
      certPath: './path/to/cert.pem',
      securityCredential: 'YOUR_SECURITY_CREDENTIAL'
    });
  4. B2B Request (Business to Business)

    master

    Initiates a transaction between one company and another.

    Signature: b2b(senderParty, receiverParty, amount, queueUrl, resultUrl, senderType = 4, receiverType = 4, initiator = null, commandId = 'BusinessToBusinessTransfer', accountRef = null, remarks = 'B2B Request')

    const { shortCode } = mpesaApi.configs
    const testShortcode2 = 600000
    await mpesaApi.b2b(shortCode, testShortcode2, 100, URL + '/b2b/timeout', URL + '/b2b/success')
  5. C2B Simulate

    master

    Simulates a C2B transaction between an end-user and a company (paybill or till number).

    Signature: c2bSimulate(msisdn, amount, billRefNumber, commandId = 'CustomerPayBillOnline', shortCode = null)

    const testMSISDN = 254708374149
    await mPesa.c2bSimulate(testMSISDN, 100, Math.random().toString(35).substr(2, 7))
  6. Lipa Na M-Pesa Online (STK Push)

    master

    Initiates an M-Pesa Online Payment transaction using STK Push.

    Signature: lipaNaMpesaOnline(senderMsisdn, amount, callbackUrl, accountRef, transactionDesc = 'Lipa na mpesa online', transactionType = 'CustomerPayBillOnline', shortCode = null, passKey = null)

    const testMSISDN = 254708374149
    const amount = 100
    const accountRef = Math.random().toString(35).substr(2, 7)
    await mpesaApi.lipaNaMpesaOnline(testMSISDN, amount, URL + '/lipanampesa/success', accountRef)
  7. B2C Request (Business to Customer)

    master

    Initiates a transaction from a company (shortcode) to end users (mobile numbers).

    Signature: b2c(senderParty, receiverParty, amount, queueUrl, resultUrl, commandId = 'BusinessPayment', initiatorName = null, remarks = 'B2C Payment', occasion = null)

    const { shortCode } = mpesaApi.configs
    const testMSISDN = 254708374149
    await mpesaApi.b2c(shortCode, testMSISDN, 100, URL + '/b2c/timeout', URL + '/b2c/success')
  8. Reversal Request

    master

    Initiates an M-Pesa transaction reversal for B2B, B2C, or C2B APIs.

    Signature: reversal(transactionId, amount, queueUrl, resultUrl, shortCode = null, remarks = 'Reversal', occasion = 'Reversal', initiator = null, receiverIdType = '11', commandId = 'TransactionReversal')

    await mpesaApi.reversal('LKXXXX1234', 100, URL + '/reversal/timeout', URL + '/reversal/success')
  9. C2B Register (Customer to Business)

    master

    Registers confirmation and validation URLs for a company's URLs.

    Signature: c2bRegister(confirmationUrl, validationUrl, shortCode = null, responseType = 'Completed')

    await mpesaApi.c2bRegister(URL + '/c2b/validation', URL + '/c2b/success')
  10. Transaction Status Request

    master

    Checks the status of B2B, B2C, and C2B transactions.

    Signature: transactionStatus(transactionId, receiverParty, idType, queueUrl, resultUrl, remarks = 'TransactionReversal', occasion = 'TransactionReversal', initiator = null, commandId = 'TransactionStatusQuery')

    await mpesaApi.transactionStatus('LKXXXX1234', shortCode, 4, URL + '/transactionstatus/timeout', URL + '/transactionstatus/success')