Coder Social home page Coder Social logo

newtonmunene99 / mpesa-api Goto Github PK

View Code? Open in Web Editor NEW
105.0 13.0 51.0 990 KB

A NodeJs Module to help you with M-Pesa Daraja API calls.

Home Page: http://npmjs.com/package/mpesa-api

License: MIT License

TypeScript 93.77% JavaScript 6.23%
mpesa mpesa-api mpesa-payments mpesa-rest mpesa-sdk mpesapi money online-payments online-payment-system safaricom

mpesa-api's Introduction

Mpesa-Api

⚠️⚠️⚠️⚠️⚠️

The official daraja API and its documentation has recently changed significantly, some links and functionality may be outdated. Due to other obligations, I'm unable to actively maintain the package. Looking for contributors/maintainers who can help write tests and keep everything updated.

⚠️⚠️⚠️⚠️⚠️


⚡ 💣 🔥 🔥 💣 ⚡

An NPM Module built with NodeJs in mind to help you with M-Pesa Daraja API calls.

Please note that this module is intended for use in a node environment on the backend and will raise a few issues if used on the client side/browser environment. This is mainly due to the file system.

Badge
Travis Build Status
Latest Latest
Minified Minified Size
MinZip Min

Ready Methods

Prerequisites

  1. Node 6+.
  2. NPM(comes with Node) or Yarn.

Installation

Mpesa-Api uses Node Package Manager

npm i mpesa-api

Or Yarn

yarn add mpesa-api

Requisites

You Will need a few things from Safaricom before development.

  1. Consumer Key
  2. Consumer Secret
  3. Test Credentials for Development/Sanbox environment
  4. Callback server with Mpesa apis whitelisted
  • Login or Register as a Safaricom developer here if you haven't.
  • Add a new App here
  • You will be issued with a Consumer Key and Consumer Secret. You will use these to initiate an Mpesa Instance.
  • Obtain Test Credentials here.
    • The Test Credentials Obtained Are only valid in Sandbox/Development environment. Take note of them.
    • To run in Production Environment you will need real Credentials.
      • To go Live and be issued with real credentials,please refer to this guide

Getting Started

// import package
import { Mpesa } from "mpesa-api";
//OR
const Mpesa = require("mpesa-api").Mpesa;

// create a new instance of the api
const mpesa = new Mpesa(credentials, environment);

A moment to explain the above. credentials should be an object containing key,secret,initiator password, security credential and certificate path as the properties/keys.

//example
const credentials = {
    clientKey: 'YOUR_CONSUMER_KEY_HERE',
    clientSecret: 'YOUR_CONSUMER_SECRET_HERE',
    initiatorPassword: 'YOUR_INITIATOR_PASSWORD_HERE',
    securityCredential: 'YOUR_SECURITY_CREDENTIAL',
    certificatePath: 'keys/example.cert'
};
// For the initiator_password, use the security credential from the test credentials page.link :https://developer.safaricom.co.ke/test_credentials

// security credential is optional. Set this if you're getting Initiator Name is invalid errors. You can generate your security credential on the test credentials page for sandbox environment or from your mpesa web portal for production environment.

// certificate path is otional. I've provided ceritificates for sandbox and production by default. If you choose not to include it Pass it as null. If you have passed `securityCredential` you should pass `certificatePath` as `null`
const credentials = {
    ...,
    certificatePath: null
};

You can get initiator password from Your Portal(production) or from test credentials(Sandbox). It will be the Security Credential (Shortcode 1). You can generate your security credential on the test credentials page for sandbox environment or from your mpesa web portal for production environment. See this guide for production environment(last step on the go live guide).

Environment should be a string. It can be either 'production' or 'sandbox'

const environment = "sandbox";
//or
const environment = "production";

Methods and Api Calls

Business to Business

This Has Been Disabled as of January 2019 and I have therefore removed it for now.

This API enables Business to Business (B2B) transactions between a business and another business. Use of this API requires a valid and verified B2B M-Pesa short code for the business initiating the transaction and the both businesses involved in the transaction.

mpesa
  .b2b({
    InitiatorName: "Initiator Name",
    Amount: 1000 /* 1000 is an example amount */,
    PartyA: "Party A",
    PartyB: "Party B",
    AccountReference: "Account Reference",
    QueueTimeOutURL: "Queue Timeout URL",
    ResultURL: "Result URL",
    CommandID: "Command ID" /* OPTIONAL */,
    SenderIdentifierType: 4 /* OPTIONAL */,
    RecieverIdentifierType: 4 /* OPTIONAL */,
    Remarks: "Remarks" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. Initiator - This is the credential/username used to authenticate the transaction request.
  2. CommandID - Unique command for each transaction type, default is MerchantToMerchantTransfer possible values are: BusinessPayBill, MerchantToMerchantTransfer, MerchantTransferFromMerchantToWorking, MerchantServicesMMFAccountTransfer, AgencyFloatAdvance
  3. Amount - The amount being transacted.
  4. PartyA - Organization’s short code initiating the transaction.
  5. SenderIdentifier - Type of organization sending the transaction. Deault is 4
  6. PartyB - Organization’s short code receiving the funds being transacted.
  7. RecieverIdentifierType - Type of organization receiving the funds being transacted. Default is 4
  8. Remarks - Comments that are sent along with the transaction.
  9. QueueTimeOutURL - The path that stores information of time out transactions.it should be properly validated to make sure that it contains the port, URI and domain name or publicly available IP.
  10. ResultURL - The path that receives results from M-Pesa it should be properly validated to make sure that it contains the port, URI and domain name or publicly available IP.
  11. AccountReference - Account Reference mandatory for “BusinessPaybill” CommandID.

Business to Customer (B2C)

This API enables Business to Customer (B2C) transactions between a company and customers who are the end-users of its products or services. Use of this API requires a valid and verified B2C M-Pesa Short code.

mpesa
  .b2c({
    Initiator: "Initiator Name",
    Amount: 1000 /* 1000 is an example amount */,
    PartyA: "Party A",
    PartyB: "Party B",
    QueueTimeOutURL: "Queue Timeout URL",
    ResultURL: "Result URL",
    CommandID: "Command ID" /* OPTIONAL */,
    Occasion: "Occasion" /* OPTIONAL */,
    Remarks: "Remarks" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. Initiator - This is the credential/username used to authenticate the transaction request.
  2. CommandID - Unique command for each transaction type e.g. SalaryPayment, BusinessPayment, PromotionPayment
  3. Amount - The amount being transacted
  4. PartyA - Organization’s shortcode initiating the transaction.
  5. PartyB - Phone number receiving the transaction
  6. Remarks - Comments that are sent along with the transaction.
  7. QueueTimeOutURL - The timeout end-point that receives a timeout response.
  8. ResultURL - The end-point that receives the response of the transaction
  9. Occasion - Optional

C2B

This API enables Paybill and Buy Goods merchants to integrate to M-Pesa and receive real time payments notifications.

Register

The C2B Register URL API registers the 3rd party’s confirmation and validation URLs to M-Pesa ; which then maps these URLs to the 3rd party shortcode. Whenever M-Pesa receives a transaction on the shortcode, M-Pesa triggers a validation request against the validation URL and the 3rd party system responds to M-Pesa with a validation response (either a success or an error code). The response expected is the success code the 3rd party

M-Pesa completes or cancels the transaction depending on the validation response it receives from the 3rd party system. A confirmation request of the transaction is then sent by M-Pesa through the confirmation URL back to the 3rd party which then should respond with a success acknowledging the confirmation.

mpesa
  .c2bregister({
    ShortCode: "Short Code",
    ConfirmationURL: "Confirmation URL",
    ValidationURL: "Validation URL",
    ResponseType: "Response Type",
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. ShortCode - The short code of the organization.
  2. ResponseType - Default response type for timeout.
  3. ConfirmationURL- Confirmation URL for the client.
  4. ValidationURL - Validation URL for the client.
Simulate
mpesa
  .c2bsimulate({
    ShortCode: 123456,
    Amount: 1000 /* 1000 is an example amount */,
    Msisdn: 254792123456,
    CommandID: "Command ID" /* OPTIONAL */,
    BillRefNumber: "Bill Reference Number" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. ShortCode - 6 digit M-Pesa Till Number or PayBill Number
  2. CommandID - Unique command for each transaction type. Default is CustomerPayBillOnline
  3. Amount - The amount been transacted.
  4. MSISDN - MSISDN (phone number) sending the transaction, start with country code without the plus(+) sign.
  5. BillRefNumber - Bill Reference Number (Optional).

Account Balance

The Account Balance API requests for the account balance of a shortcode.

mpesa
  .accountBalance({
    Initiator: "Initiator Name",
    PartyA: "Party A",
    IdentifierType: "Identifier Type",
    QueueTimeOutURL: "Queue Timeout URL",
    ResultURL: "Result URL",
    CommandID: "Command ID" /* OPTIONAL */,
    Remarks: "Remarks" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. Initiator - This is the credential/username used to authenticate the transaction request.
  2. CommandID - A unique command passed to the M-Pesa system. Default is AccountBalance
  3. PartyB - The shortcode of the organisation receiving the transaction.
  4. ReceiverIdentifierType - Type of the organisation receiving the transaction.
  5. Remarks - Comments that are sent along with the transaction.
  6. QueueTimeOutURL - The timeout end-point that receives a timeout message.
  7. ResultURL - The end-point that receives a successful transaction.

Transaction Status

Transaction Status API checks the status of a B2B, B2C and C2B APIs transactions.

mpesa
  .transactionStatus({
    Initiator: "Initiator",
    TransactionID: "Transaction ID",
    PartyA: "Party A",
    IdentifierType: "Identifier Type",
    ResultURL: "Result URL",
    QueueTimeOutURL: "Queue Timeout URL",
    CommandID: "Command ID" /* OPTIONAL */,
    Remarks: "Remarks" /* OPTIONAL */,
    Occasion: "Occasion" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. Initiator - The name of Initiator to initiating the request.
  2. CommandID - Unique command for each transaction type, possible values are: TransactionStatusQuery.
  3. TransactionID - Organization Receiving the funds.
  4. Party A - Organization /MSISDN sending the transaction.
  5. IdentifierType - Type of organization receiving the transaction.
  6. ResultURL - The path that stores information of transaction.
  7. QueueTimeOutURL - The path that stores information of time out transaction.
  8. Remarks - Comments that are sent along with the transaction.
  9. Occasion - Optional.

Lipa na mpesa online

Lipa na M-Pesa Online Payment API is used to initiate a M-Pesa transaction on behalf of a customer using STK Push. This is the same technique mySafaricom App uses whenever the app is used to make payments.

mpesa
  .lipaNaMpesaOnline({
    BusinessShortCode: 123456,
    Amount: 1000 /* 1000 is an example amount */,
    PartyA: "Party A",
    PhoneNumber: "Phone Number",
    CallBackURL: "CallBack URL",
    AccountReference: "Account Reference",
    passKey: "Lipa Na Mpesa Pass Key",
    TransactionType: "Transaction Type" /* OPTIONAL */,
    TransactionDesc: "Transaction Description" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. BusinessShortCode - The organization shortcode used to receive the transaction.
  2. Amount - The amount to be transacted.
  3. PartyA - The MSISDN sending the funds.
  4. PartyB - The organization shortcode receiving the funds. Default is the BusinessShorCode.
  5. PhoneNumber - The MSISDN sending the funds.
  6. CallBackURL - The url to where responses from M-Pesa will be sent to.
  7. AccountReference - Used with M-Pesa PayBills.
  8. TransactionDesc - A description of the transaction.
  9. passKey - Lipa Na Mpesa Pass Key.
  10. Transaction Type - Default is CustomerPayBillOnline

Lipa na mpesa online query

mpesa
  .lipaNaMpesaQuery({
    BusinessShortCode: 123456,
    CheckoutRequestID: "Checkout Request ID",
    passKey: "Lipa Na Mpesa Pass Key",
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. BusinessShortCode - Business Short Code
  2. CheckoutRequestID - Checkout RequestID
  3. Lipa Na Mpesa Pass Key

Reversal

Reverses a B2B, B2C or C2B M-Pesa transaction.

mpesa
  .reversal({
    Initiator: "Initiator",
    TransactionID: "Transaction ID",
    Amount: 1000 /* 1000 is an example amount */,
    ReceiverParty: "Reciever Party",
    ResultURL: "Result URL",
    QueueTimeOutURL: "Queue Timeout URL",
    CommandID: "Command ID" /* OPTIONAL */,
    RecieverIdentifierType: 11 /* OPTIONAL */,
    Remarks: "Remarks" /* OPTIONAL */,
    Occasion: "Ocassion" /* OPTIONAL */,
  })
  .then((response) => {
    //Do something with the response
    //eg
    console.log(response);
  })
  .catch((error) => {
    //Do something with the error;
    //eg
    console.error(error);
  });
  1. Initiator - This is the credential/username used to authenticate the transaction request.
  2. TransactionID - Organization Receiving the funds.
  3. Amount - The Amount To Be Reversed
  4. PartyA - Organization/MSISDN sending the transaction.
  5. RecieverIdentifierType - Type of organization receiving the transaction. Default is 11
  6. ResultURL - The path that stores information of transaction.
  7. QueueTimeOutURL - The path that stores information of time out transaction.
  8. Remarks - Comments that are sent along with the transaction.
  9. Occasion - Optional.
  10. Command ID - Default is TransactionReversal

IP Whitelisting

You might need to whitelist Mpesa IPs listed below on the server/firewall that receives the callbacks.

View List
  • 196.201.214.200
  • 196.201.214.206
  • 196.201.213.114
  • 196.201.214.207
  • 196.201.214.208
  • 196.201.213.44
  • 196.201.212.127
  • 196.201.212.128
  • 196.201.212.129
  • 196.201.212.132
  • 196.201.212.136
  • 196.201.212.138

Demo

You can try it out on Runkit

RoadMap

  • Basic Documentation
  • Deploy to Npm
  • Migrate to Typescript
  • Detailed Documentation
  • Write Tests
  • Validators for inputs
  • Tree shaking
  • Migrate from Typescript to JSDoc

Build

If you Wish to build

  1. Clone this repo
  2. CD into repo
  3. run npm install to install dependencies
  4. run npm run build to build
  5. run npm run start:dev to run package in development mode

Contributing

  1. Fork the project then clone the forked project
  2. Create your feature branch: git checkout -b my-new-feature
  3. Make your changes and add name to Contributors list below.
  4. Commit your changes: git commit -m 'Add some feature'
  5. Push to the branch: git push origin my-new-feature
  6. Submit a pull request.

Credits

Name Role
Newton Munene Contributor
Nelson Bwogora Contributor

License

MIT License

Copyright (c) 2018 Newton Munene

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mpesa-api's People

Contributors

briankmaina avatar dependabot[bot] avatar greenkeeper[bot] avatar musebe avatar nelsonblack avatar newtonmunene99 avatar roboflank avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mpesa-api's Issues

version mismatch npm i gets version 2.2.0 , however latest version is 2.3.1

npm i mpesa-api gets a previous version 2.2.0 , however latest version is 2.3.1

$ npm view mpesa-api

 [email protected] | MIT | deps: 1 | versions: 8
An NPM Module built with NodeJs to help you with M-Pesa Daraja API calls.
https://github.com/newtonmunene99/mpesa-api/

keywords: mpesa, nodejs, node, mobile money, money

dist
.tarball: https://registry.npmjs.org/mpesa-api/-/mpesa-api-2.2.0.tgz
.shasum: 28574429cdbb6cd34b530e77c41f2726d4739116
.integrity: sha512-004ASyvfITbj5DkzwgbWw9ayVV5+qzR6pQmqdm+kJp+AXV5v1co4lS1o0u8SHoqG6AeXXf2cbylTUNeZ2ltMOw==
.unpackedSize: 66.1 kB

dependencies:
axios: ^0.19.0

maintainers:
- newtonmunene99 <[email protected]>

dist-tags:
latest: 2.2.0```

Getting fs.readFileSync is not a function

I'm getting fs.readFileSync is not a function when running the library on Node : 12.0.0 and React : 16.10.2

It's occurring when getting the certificates

import { Mpesa } from "mpesa-api";

const credentials = {
  client_key: '',
  client_secret: '',
  initiator_password: '	Safaricom007@',
  certificatepath:null
};
const environment = "sandbox";
const mpesa = new Mpesa(credentials, environment);

Getting "The initiator information is invalid." when Live

I'm getting the error above in production when using the Account Balance API and the B2C. Could it be an error when generating the security credential coz everything else works.
Here's an example of the error (Account Balance)

{"ResultDesc":"The initiator information is invalid.",
"ConversationID":"AG_20200625_0000650ea6a99ae1c0bb",
"TransactionID":"OFP0000000",
"ResultParameters":{"ResultParameter":{"Key":"BOCompletedTime","Value":20200625232427}},
"ResultCode":2001,"ReferenceData":{"ReferenceItem":{"Value":"https://internalapi.safaricom.co.ke/mpesa/abresults/v1/submit","Key":"QueueTimeoutURL"}},
"OriginatorConversationID":"13443-10746354-1",
"ResultType":0} 

B2C API bug :- "Bad Request - Invalid InitiatorName"

On your mpesa-api, while invoking the B2C API in the sandbox, I am getting the below error

"data":{"requestId":"3911-7748949-1","errorCode":"400.002.02","errorMessage":"Bad Request - Invalid InitiatorName"},"service":"user-service"}

even though the InitiatorName is part of the parameters in the code. i.e.

But when checking the payload in the logs, it's actually missing i.e
"data":"{\"SecurityCredential\":\"lAqo9GH\",\"CommandID\":\"BusinessPayment\",\"Amount\":\"10\",\"PartyA\":600638,\"PartyB\":\"2547xxxxxxxx\",\"Remarks\":\"DriverPayment\",\"QueueTimeOutURL\":\"https://test.com/api/callback.php\",\"ResultURL\":\"https://test.com/api/callback.php\",\"Occasion\":\"account\"}"

  // invoking the mpesa api
  mpesa
  .b2c({
    InitiatorName: Constants.initiatorName,
    Amount: req.body.Amount,
    PartyA: Constants.PaybillB2C,
    PartyB: req.body.PhoneNumber,
    QueueTimeOutURL: Constants.QueueTimeOutURL,
    ResultURL: Constants.ResultURL,
    CommandID: Constants.CommandID,
    Occassion: Constants.Occassion,
    Remarks: req.body.TransactionDesc
  })

Initiator Password in Daraja 2.0

Hello Team,
I am trying to access use the mpesa-api to make the request of authorization but gives me a 400 status invalid credentials unAuthorized error.I am trying to confirm the link in the documentation of how to get my initiator
For the initiator_password, use the security credential from the test credentials page.link :https://developer.safaricom.co.ke/test_credentials
As specified in the docs the link to get the initiator password isnt working.I have a page under this link when logged in
https://developer.safaricom.co.ke/Profile
When I view it there is a place to generate security credentials but above it there is a password field I have come to know you can type anything and a key will be generated which password is required to generate a security credentials and is it same as initiator password on sandbox
Thank You

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.