{"id":13941714,"url":"https://github.com/safaricom/mpesa-node-library","last_synced_at":"2025-04-04T15:07:42.416Z","repository":{"id":40533564,"uuid":"121874935","full_name":"safaricom/mpesa-node-library","owner":"safaricom","description":"M-Pesa Library for Node.js using REST API","archived":false,"fork":false,"pushed_at":"2024-06-26T10:33:57.000Z","size":4543,"stargazers_count":163,"open_issues_count":21,"forks_count":142,"subscribers_count":31,"default_branch":"master","last_synced_at":"2025-03-28T14:09:23.572Z","etag":null,"topics":["account-balance","b2b","c2b-transaction","lipa","mpesa","mpesa-api","mpesa-library"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/safaricom.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-02-17T17:14:00.000Z","updated_at":"2025-03-04T23:07:37.000Z","dependencies_parsed_at":"2024-11-22T21:45:28.891Z","dependency_job_id":null,"html_url":"https://github.com/safaricom/mpesa-node-library","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/safaricom%2Fmpesa-node-library","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/safaricom%2Fmpesa-node-library/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/safaricom%2Fmpesa-node-library/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/safaricom%2Fmpesa-node-library/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/safaricom","download_url":"https://codeload.github.com/safaricom/mpesa-node-library/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247198450,"owners_count":20900080,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["account-balance","b2b","c2b-transaction","lipa","mpesa","mpesa-api","mpesa-library"],"created_at":"2024-08-08T02:01:25.844Z","updated_at":"2025-04-04T15:07:42.399Z","avatar_url":"https://github.com/safaricom.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# Node.js M-Pesa API\n**M-Pesa Library for Node.js using REST API**\n\n![Node Mpesa Rest API](https://i.imgur.com/PRYk4Q3.jpg)\n\n\u003ca href=\"https://standardjs.com\" style=\"float: right; padding: 0 0 20px 20px;\"\u003e\u003cimg src=\"https://cdn.rawgit.com/feross/standard/master/sticker.svg\" alt=\"JavaScript Standard Style\" width=\"100\" align=\"right\"\u003e\u003c/a\u003e\n[![Build Status](https://travis-ci.org/safaricom/mpesa-node-library.svg?branch=master)](https://travis-ci.org/safaricom/mpesa-node-library)\n[![Made in Africa](https://img.shields.io/badge/Africa's%20Rising-%E2%9C%93-green.svg)](https://github.com/collections/made-in-africa)\n[![Known Vulnerabilities](https://snyk.io/test/github/safaricom/mpesa-node-library/badge.svg?targetFile=package.json)](https://snyk.io/test/github/safaricom/mpesa-node-library?targetFile=package.json)\n\n## Prerequisites\n1. Node v6+, 8+ recommended.\n2. Yarn* (optional) You can still use npm\n3. ES6 knowledge\n\n## Installation\nUse npm/yarn:\n```\nnpm i mpesa-node\n```\n\n### Pre-Usage\n\n**Please make sure you have read the documentation on [Daraja](https://developer.safaricom.co.ke/home) before continuing.**\n\nYou need the following before getting to use this library:\n1. Consumer Key and Consume Secret\n2. Test Credentials *(Optional only for sandbox)*\n\n## Getting Started\nThis library is extremely modular, meaning you can create more than one Mpesa instance\n````js\nconst Mpesa = require('mpesa-node')\nconst mpesaApi = new Mpesa({ consumerKey: '\u003cyour consumer key\u003e', consumerSecret: '\u003cyour consumer secret\u003e' })\n// another instance\n// const instance = new Mpesa({ consumerKey: 'test', consumerSecret: 'test', environment: 'production' })\nmpesaApi\n    .c2bSimulate(\n        254708374149,\n        500,\n        'h6dk0Ue2'\n    )\n    .then((result) =\u003e {\n        //do something\n    })\n    .catch((err) =\u003e {\n        // retry?\n    })\n````\n\nWhile working with the Mpesa Class, you only need two key-value items, ie: consumerKey and consumerSecret.\nNonetheless, prefilling some things means you dont have to re-enter them again. A complete config object looks like this\n````js\nnew Mpesa({\n    consumerKey: '\u003cyour consumer key\u003e',\n    consumerSecret: '\u003cyour consumer secret\u003e',\n    environment: 'sandbox',\n    shortCode: '600111',\n    initiatorName: 'Test Initiator',\n    lipaNaMpesaShortCode: 123456,\n    lipaNaMpesaShortPass: '\u003csome key here\u003e',\n    securityCredential: '\u003ccredential here\u003e',\n    certPath: path.resolve('keys/myKey.cert')\n})\n````\n## API\nPlease note that this library is in active development, use in production with caution.\n\nCurrent API:\n````js\nconst mpesaApi = new Mpesa({ consumerKey: '\u003cyour consumer key\u003e', consumerSecret: '\u003cyour consumer secret\u003e' })\nconst {\n  accountBalance,\n  b2b,\n  b2c,\n  c2bRegister,\n  c2bSimulate,\n  lipaNaMpesaOnline,\n  lipaNaMpesaQuery,\n  reversal,\n  transactionStatus\n} = mpesaApi\n````\nOfcourse you dont need to import all methods, you can import the only ones you need.\n\nAll methods return a `\u003cPromise\u003e`, hence you can use `.then` or `await`.\nAll calls are done by Axios, so for the response structure check Axios documentation.\n\n### Methods\n• [B2C Request](https://developer.safaricom.co.ke/b2c/apis/post/paymentrequest)\n\nThis initiates a business to customer transactions from a company (shortcode) to end users (mobile numbers) of their services.\n````js\n/*\n * b2c(senderParty, receiverParty, amount, queueUrl, resultUrl, commandId = 'BusinessPayment', initiatorName = null, remarks = 'B2C Payment', occasion = null)\n * Example:\n*/\nconst { shortCode } = mpesaApi.configs\nconst testMSISDN = 254708374149\nawait mpesaApi.b2c(shortCode, testMSISDN, 100, URL + '/b2c/timeout', URL + '/b2c/success')\n````\n\n• [B2B Request](https://developer.safaricom.co.ke/b2b/apis/post/paymentrequest)\n\nThis initiates a business to business transaction between one company to another.\n````js\n/*\n * b2c(senderParty, receiverParty, amount, queueUrl, resultUrl, senderType = 4, receiverType = 4, initiator = null, commandId = 'BusinessToBusinessTransfer', accountRef = null, remarks = 'B2B Request')\n * Example:\n*/\nconst { shortCode } = mpesaApi.configs\nconst testShortcode2 = 600000\nawait mpesaApi.b2b(shortCode, testShortcode2, 100, URL + '/b2b/timeout', URL + '/b2b/success')\n````\n• [C2B Register](https://developer.safaricom.co.ke/c2b/apis/post/registerurl)\n\nThis initiates a C2B confirmation and validation registration for a company's URLs\n\n````js\n/*\n * c2bRegister(confirmationUrl, validationUrl, shortCode = null, responseType = 'Completed')\n * Example:\n */\n\nawait mpesaApi.c2bRegister(URL + '/c2b/validation', URL + '/c2b/success')\n\n````\n\n• [C2B Simulate](https://developer.safaricom.co.ke/c2b/apis/post/simulate)\n\nThis initiates a C2B transaction between an end-user and a company (paybill or till number)\n\n````js\n/*\n * c2bSimulate(msisdn, amount, billRefNumber, commandId = 'CustomerPayBillOnline', shortCode = null)\n * Example:\n */\nconst testMSISDN = 254708374149\nawait mPesa.c2bSimulate(testMSISDN, 100, Math.random().toString(35).substr(2, 7))\n\n````\n• [M-Pesa Express Request - Lipa Na M-Pesa Online Payment API](https://developer.safaricom.co.ke/lipa-na-m-pesa-online/apis/post/stkpush/v1/processrequest)\n\nThis initiates a Lipa Na M-Pesa Online Payment transaction using STK Push.\n\n````js\n/*\n * lipaNaMpesaOnline(senderMsisdn, amount, callbackUrl, accountRef, transactionDesc = 'Lipa na mpesa online', transactionType = 'CustomerPayBillOnline', shortCode = null, passKey = null)\n * Example:\n */\n const testMSISDN = 254708374149\n const amount = 100\n const accountRef = Math.random().toString(35).substr(2, 7)\nawait mpesaApi.lipaNaMpesaOnline(testMSISDN, amount, URL + '/lipanampesa/success', accountRef)\n\n````\n• [M-Pesa Express Query Request - Lipa Na M-Pesa Query Request API](https://developer.safaricom.co.ke/lipa-na-m-pesa-online/apis/post/stkpushquery/v1/query)\n\nThis API checks the status of a Lipa Na M-Pesa Online Payment transaction\n\n````js\n/*\n * lipaNaMpesaQuery(checkoutRequestId, shortCode = null, passKey = null)\n * Example:\n */\nconst checkoutRequestId ='ws_co_123456789'\nawait mpesaApi.lipaNaMpesaQuery(checkoutRequestId)\n````\n• [Reversal Request](https://developer.safaricom.co.ke/reversal/apis/post/request)\n\nThis initiates an M-Pesa transaction reversal on B2B, B2C or C2B API\n````js\n/*\n * reversal(transactionId, amount, queueUrl, resultUrl, shortCode = null, remarks = 'Reversal', occasion = 'Reversal', initiator = null, receiverIdType = '11', commandId = 'TransactionReversal')\n * Example:\n */\nawait mpesaApi.reversal('LKXXXX1234', 100, URL + '/reversal/timeout', URL + '/reversal/success')\n````\n• [Transaction Status Request](https://developer.safaricom.co.ke/transaction-status/apis/post/query)\n\nThis API is used to check the status of B2B, B2C and C2B transactions\n\n````js\n/*\n * transactionStatus(transactionId, receiverParty, idType, queueUrl, resultUrl, remarks = 'TransactionReversal', occasion = 'TransactionReversal', initiator = null, commandId = 'TransactionStatusQuery')\n * Example:\n */\nawait mpesaApi.transactionStatus('LKXXXX1234', shortCode, 4, URL + '/transactionstatus/timeout', URL + '/transactionstatus/success')\n````\n• [Account Balance Request](https://developer.safaricom.co.ke/account-balance/apis/post/query)\n\nThis initiates a request for the account balance of a shortcode\n\n````js\n/*\n * accountBalance(shortCode, idType, queueUrl, resultUrl, remarks = 'Checking account balance', initiator = null, commandId = 'AccountBalance')\n * Example:\n */\nconst { shortCode } = mpesaApi.configs\nawait mpesaApi.accountBalance(shortCode, 4, URL + '/accountbalance/timeout', URL + '/accountbalance/success')\n````\n## Testing\nTesting needs you to clone this repo.\n\nThe command below runs both integration and unit test.\n\nIntegration tests launch a ngrok instance and await callbacks (you will need an active internet connection for this).\n\nTo run each separately, check `package.json` for the commands.\n````\nnpm test\n````\n## Going Live/Production\n\nYou will need to first click on \"Going Live\" on [Daraja](https://developer.safaricom.co.ke/user/me/apps)\n\nThe only thing you need to tweek in this Libs config is `environment`:\n````js\nnew Mpesa({\n    consumerKey: '\u003cyour consumer key\u003e',\n    consumerSecret: '\u003cyour consumer secret\u003e',\n    environment: 'production', //\u003c------\n    .....\n    })\n````\n\n## Pending Stuff\n\n- [x] E2E Integration Tests\n- [x] Deploy to Npm\n- [x] Reduce number of args\n- [x] Detailed Documentation\n- [ ] Enumify\n- [ ] Validators for MSISDN and other expected inputs\n- [x] More detailed Unit tests\n- [ ] Handle all Promises\n\n## Contributing\n1. Create your feature branch: `git checkout -b my-new-feature`\n2. Commit your changes: `git commit -m 'Add some feature'`\n3. Push to the branch: `git push origin my-new-feature`\n4. Submit a pull request :D\n\n## Credits\n\n| **Contributor** |\n\u003cbr/\u003e\n| [DGatere](https://github.com/DGatere) |\u003cbr/\u003e\n| [geofmureithi](https://github.com/geofmureithi) |\n\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsafaricom%2Fmpesa-node-library","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsafaricom%2Fmpesa-node-library","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsafaricom%2Fmpesa-node-library/lists"}