├── .babelrc
├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── keys
└── sandbox-cert.cer
├── package.json
├── src
├── endpoints
│ ├── account-balance.js
│ ├── b2b.js
│ ├── b2c.js
│ ├── c2b-register.js
│ ├── c2b-simulate.js
│ ├── index.js
│ ├── lipa-na-mpesa-online.js
│ ├── lipa-na-mpesa-query.js
│ ├── oauth.js
│ ├── reversal.js
│ └── transaction-status.js
├── helpers
│ ├── index.js
│ ├── request.js
│ └── security.js
└── m-pesa.js
├── tests
├── helpers
│ ├── app.js
│ ├── callbacksemitter.js
│ ├── instance.js
│ ├── ngrok.js
│ └── tests.env
├── integrations
│ ├── _before.test.js
│ ├── _init.js
│ ├── accountbalance.test.js
│ ├── b2b.test.js
│ ├── b2c.test.js
│ ├── c2b.test.js
│ ├── lipa-na-mpesa.test.js
│ ├── reversal.test.js
│ └── transactionstatus.test.js
└── unit
│ └── index.test.js
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["env"]
3 | }
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 |
5 | ---
6 |
7 | **Describe the bug**
8 | A clear and concise description of what the bug is.
9 |
10 | **To Reproduce**
11 | Steps to reproduce the behavior:
12 | 1. Go to '...'
13 | 2. Click on '....'
14 | 3. Scroll down to '....'
15 | 4. See error
16 |
17 | **Expected behavior**
18 | A clear and concise description of what you expected to happen.
19 |
20 | **Screenshots**
21 | If applicable, add screenshots to help explain your problem.
22 |
23 | **Desktop (please complete the following information):**
24 | - OS: [e.g. iOS]
25 | - Browser [e.g. chrome, safari]
26 | - Version [e.g. 22]
27 |
28 | **Smartphone (please complete the following information):**
29 | - Device: [e.g. iPhone6]
30 | - OS: [e.g. iOS8.1]
31 | - Browser [e.g. stock browser, safari]
32 | - Version [e.g. 22]
33 |
34 | **Additional context**
35 | Add any other context about the problem here.
36 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Runtime data
3 | pids
4 | *.pid
5 | *.seed
6 | *.pid.lock
7 |
8 | # Directory for instrumented libs generated by jscoverage/JSCover
9 | lib-cov
10 |
11 | # Coverage directory used by tools like istanbul
12 | coverage
13 |
14 | # nyc test coverage
15 | .nyc_output
16 |
17 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
18 | .grunt
19 |
20 | # Bower dependency directory (https://bower.io/)
21 | bower_components
22 |
23 | # node-waf configuration
24 | .lock-wscript
25 |
26 | # Compiled binary addons (http://nodejs.org/api/addons.html)
27 | build/Release
28 |
29 | # Dependency directories
30 | node_modules/
31 | jspm_packages/
32 |
33 | # Typescript v1 declaration files
34 | typings/
35 |
36 | # Optional npm cache directory
37 | .npm
38 |
39 | # Optional eslint cache
40 | .eslintcache
41 |
42 | # Optional REPL history
43 | .node_repl_history
44 |
45 | # Output of 'npm pack'
46 | *.tgz
47 |
48 | # Yarn Integrity file
49 | .yarn-integrity
50 |
51 | # dotenv environment variables file
52 | .env
53 |
54 | # yarn error-log
55 | yarn-error.log
56 |
57 | # idea
58 | .idea/
59 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | sudo: false
3 | node_js:
4 | - "8.6"
5 | install:
6 | - npm install
7 | script:
8 | - npm test
9 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at apifeedback@safaricom.co.ke. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Node.js M-Pesa API
2 | **M-Pesa Library for Node.js using REST API**
3 |
4 | 
5 |
6 |
7 | [](https://travis-ci.org/safaricom/mpesa-node-library)
8 | [](https://github.com/collections/made-in-africa)
9 | [](https://snyk.io/test/github/safaricom/mpesa-node-library?targetFile=package.json)
10 |
11 | ## Prerequisites
12 | 1. Node v6+, 8+ recommended.
13 | 2. Yarn* (optional) You can still use npm
14 | 3. ES6 knowledge
15 |
16 | ## Installation
17 | Use npm/yarn:
18 | ```
19 | npm i mpesa-node
20 | ```
21 |
22 | ### Pre-Usage
23 |
24 | **Please make sure you have read the documentation on [Daraja](https://developer.safaricom.co.ke/home) before continuing.**
25 |
26 | You need the following before getting to use this library:
27 | 1. Consumer Key and Consume Secret
28 | 2. Test Credentials *(Optional only for sandbox)*
29 |
30 | ## Getting Started
31 | This library is extremely modular, meaning you can create more than one Mpesa instance
32 | ````js
33 | const Mpesa = require('mpesa-node')
34 | const mpesaApi = new Mpesa({ consumerKey: '', consumerSecret: '' })
35 | // another instance
36 | // const instance = new Mpesa({ consumerKey: 'test', consumerSecret: 'test', environment: 'production' })
37 | mpesaApi
38 | .c2bSimulate(
39 | 254708374149,
40 | 500,
41 | 'h6dk0Ue2'
42 | )
43 | .then((result) => {
44 | //do something
45 | })
46 | .catch((err) => {
47 | // retry?
48 | })
49 | ````
50 |
51 | While working with the Mpesa Class, you only need two key-value items, ie: consumerKey and consumerSecret.
52 | Nonetheless, prefilling some things means you dont have to re-enter them again. A complete config object looks like this
53 | ````js
54 | new Mpesa({
55 | consumerKey: '',
56 | consumerSecret: '',
57 | environment: 'sandbox',
58 | shortCode: '600111',
59 | initiatorName: 'Test Initiator',
60 | lipaNaMpesaShortCode: 123456,
61 | lipaNaMpesaShortPass: '',
62 | securityCredential: '',
63 | certPath: path.resolve('keys/myKey.cert')
64 | })
65 | ````
66 | ## API
67 | Please note that this library is in active development, use in production with caution.
68 |
69 | Current API:
70 | ````js
71 | const mpesaApi = new Mpesa({ consumerKey: '', consumerSecret: '' })
72 | const {
73 | accountBalance,
74 | b2b,
75 | b2c,
76 | c2bRegister,
77 | c2bSimulate,
78 | lipaNaMpesaOnline,
79 | lipaNaMpesaQuery,
80 | reversal,
81 | transactionStatus
82 | } = mpesaApi
83 | ````
84 | Ofcourse you dont need to import all methods, you can import the only ones you need.
85 |
86 | All methods return a ``, hence you can use `.then` or `await`.
87 | All calls are done by Axios, so for the response structure check Axios documentation.
88 |
89 | ### Methods
90 | • [B2C Request](https://developer.safaricom.co.ke/b2c/apis/post/paymentrequest)
91 |
92 | This initiates a business to customer transactions from a company (shortcode) to end users (mobile numbers) of their services.
93 | ````js
94 | /*
95 | * b2c(senderParty, receiverParty, amount, queueUrl, resultUrl, commandId = 'BusinessPayment', initiatorName = null, remarks = 'B2C Payment', occasion = null)
96 | * Example:
97 | */
98 | const { shortCode } = mpesaApi.configs
99 | const testMSISDN = 254708374149
100 | await mpesaApi.b2c(shortCode, testMSISDN, 100, URL + '/b2c/timeout', URL + '/b2c/success')
101 | ````
102 |
103 | • [B2B Request](https://developer.safaricom.co.ke/b2b/apis/post/paymentrequest)
104 |
105 | This initiates a business to business transaction between one company to another.
106 | ````js
107 | /*
108 | * b2c(senderParty, receiverParty, amount, queueUrl, resultUrl, senderType = 4, receiverType = 4, initiator = null, commandId = 'BusinessToBusinessTransfer', accountRef = null, remarks = 'B2B Request')
109 | * Example:
110 | */
111 | const { shortCode } = mpesaApi.configs
112 | const testShortcode2 = 600000
113 | await mpesaApi.b2b(shortCode, testShortcode2, 100, URL + '/b2b/timeout', URL + '/b2b/success')
114 | ````
115 | • [C2B Register](https://developer.safaricom.co.ke/c2b/apis/post/registerurl)
116 |
117 | This initiates a C2B confirmation and validation registration for a company's URLs
118 |
119 | ````js
120 | /*
121 | * c2bRegister(confirmationUrl, validationUrl, shortCode = null, responseType = 'Completed')
122 | * Example:
123 | */
124 |
125 | await mpesaApi.c2bRegister(URL + '/c2b/validation', URL + '/c2b/success')
126 |
127 | ````
128 |
129 | • [C2B Simulate](https://developer.safaricom.co.ke/c2b/apis/post/simulate)
130 |
131 | This initiates a C2B transaction between an end-user and a company (paybill or till number)
132 |
133 | ````js
134 | /*
135 | * c2bSimulate(msisdn, amount, billRefNumber, commandId = 'CustomerPayBillOnline', shortCode = null)
136 | * Example:
137 | */
138 | const testMSISDN = 254708374149
139 | await mPesa.c2bSimulate(testMSISDN, 100, Math.random().toString(35).substr(2, 7))
140 |
141 | ````
142 | • [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)
143 |
144 | This initiates a Lipa Na M-Pesa Online Payment transaction using STK Push.
145 |
146 | ````js
147 | /*
148 | * lipaNaMpesaOnline(senderMsisdn, amount, callbackUrl, accountRef, transactionDesc = 'Lipa na mpesa online', transactionType = 'CustomerPayBillOnline', shortCode = null, passKey = null)
149 | * Example:
150 | */
151 | const testMSISDN = 254708374149
152 | const amount = 100
153 | const accountRef = Math.random().toString(35).substr(2, 7)
154 | await mpesaApi.lipaNaMpesaOnline(testMSISDN, amount, URL + '/lipanampesa/success', accountRef)
155 |
156 | ````
157 | • [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)
158 |
159 | This API checks the status of a Lipa Na M-Pesa Online Payment transaction
160 |
161 | ````js
162 | /*
163 | * lipaNaMpesaQuery(checkoutRequestId, shortCode = null, passKey = null)
164 | * Example:
165 | */
166 | const checkoutRequestId ='ws_co_123456789'
167 | await mpesaApi.lipaNaMpesaQuery(checkoutRequestId)
168 | ````
169 | • [Reversal Request](https://developer.safaricom.co.ke/reversal/apis/post/request)
170 |
171 | This initiates an M-Pesa transaction reversal on B2B, B2C or C2B API
172 | ````js
173 | /*
174 | * reversal(transactionId, amount, queueUrl, resultUrl, shortCode = null, remarks = 'Reversal', occasion = 'Reversal', initiator = null, receiverIdType = '11', commandId = 'TransactionReversal')
175 | * Example:
176 | */
177 | await mpesaApi.reversal('LKXXXX1234', 100, URL + '/reversal/timeout', URL + '/reversal/success')
178 | ````
179 | • [Transaction Status Request](https://developer.safaricom.co.ke/transaction-status/apis/post/query)
180 |
181 | This API is used to check the status of B2B, B2C and C2B transactions
182 |
183 | ````js
184 | /*
185 | * transactionStatus(transactionId, receiverParty, idType, queueUrl, resultUrl, remarks = 'TransactionReversal', occasion = 'TransactionReversal', initiator = null, commandId = 'TransactionStatusQuery')
186 | * Example:
187 | */
188 | await mpesaApi.transactionStatus('LKXXXX1234', shortCode, 4, URL + '/transactionstatus/timeout', URL + '/transactionstatus/success')
189 | ````
190 | • [Account Balance Request](https://developer.safaricom.co.ke/account-balance/apis/post/query)
191 |
192 | This initiates a request for the account balance of a shortcode
193 |
194 | ````js
195 | /*
196 | * accountBalance(shortCode, idType, queueUrl, resultUrl, remarks = 'Checking account balance', initiator = null, commandId = 'AccountBalance')
197 | * Example:
198 | */
199 | const { shortCode } = mpesaApi.configs
200 | await mpesaApi.accountBalance(shortCode, 4, URL + '/accountbalance/timeout', URL + '/accountbalance/success')
201 | ````
202 | ## Testing
203 | Testing needs you to clone this repo.
204 |
205 | The command below runs both integration and unit test.
206 |
207 | Integration tests launch a ngrok instance and await callbacks (you will need an active internet connection for this).
208 |
209 | To run each separately, check `package.json` for the commands.
210 | ````
211 | npm test
212 | ````
213 | ## Going Live/Production
214 |
215 | You will need to first click on "Going Live" on [Daraja](https://developer.safaricom.co.ke/user/me/apps)
216 |
217 | The only thing you need to tweek in this Libs config is `environment`:
218 | ````js
219 | new Mpesa({
220 | consumerKey: '',
221 | consumerSecret: '',
222 | environment: 'production', //<------
223 | .....
224 | })
225 | ````
226 |
227 | ## Pending Stuff
228 |
229 | - [x] E2E Integration Tests
230 | - [x] Deploy to Npm
231 | - [x] Reduce number of args
232 | - [x] Detailed Documentation
233 | - [ ] Enumify
234 | - [ ] Validators for MSISDN and other expected inputs
235 | - [x] More detailed Unit tests
236 | - [ ] Handle all Promises
237 |
238 | ## Contributing
239 | 1. Create your feature branch: `git checkout -b my-new-feature`
240 | 2. Commit your changes: `git commit -m 'Add some feature'`
241 | 3. Push to the branch: `git push origin my-new-feature`
242 | 4. Submit a pull request :D
243 |
244 | ## Credits
245 |
246 | | **Contributor** |
247 |
248 | | [DGatere](https://github.com/DGatere) |
249 | | [geofmureithi](https://github.com/geofmureithi) |
250 |
251 |
252 | ## License
253 |
254 | MIT
255 |
--------------------------------------------------------------------------------
/keys/sandbox-cert.cer:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIGgDCCBWigAwIBAgIKMvrulAAAAARG5DANBgkqhkiG9w0BAQsFADBbMRMwEQYK
3 | CZImiZPyLGQBGRYDbmV0MRkwFwYKCZImiZPyLGQBGRYJc2FmYXJpY29tMSkwJwYD
4 | VQQDEyBTYWZhcmljb20gSW50ZXJuYWwgSXNzdWluZyBDQSAwMjAeFw0xNDExMTIw
5 | NzEyNDVaFw0xNjExMTEwNzEyNDVaMHsxCzAJBgNVBAYTAktFMRAwDgYDVQQIEwdO
6 | YWlyb2JpMRAwDgYDVQQHEwdOYWlyb2JpMRAwDgYDVQQKEwdOYWlyb2JpMRMwEQYD
7 | VQQLEwpUZWNobm9sb2d5MSEwHwYDVQQDExhhcGljcnlwdC5zYWZhcmljb20uY28u
8 | a2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCotwV1VxXsd0Q6i2w0
9 | ugw+EPvgJfV6PNyB826Ik3L2lPJLFuzNEEJbGaiTdSe6Xitf/PJUP/q8Nv2dupHL
10 | BkiBHjpQ6f61He8Zdc9fqKDGBLoNhNpBXxbznzI4Yu6hjBGLnF5Al9zMAxTij6wL
11 | GUFswKpizifNbzV+LyIXY4RR2t8lxtqaFKeSx2B8P+eiZbL0wRIDPVC5+s4GdpFf
12 | Y3QIqyLxI2bOyCGl8/XlUuIhVXxhc8Uq132xjfsWljbw4oaMobnB2KN79vMUvyoR
13 | w8OGpga5VoaSFfVuQjSIf5RwW1hitm/8XJvmNEdeY0uKriYwbR8wfwQ3E0AIW1Fl
14 | MMghAgMBAAGjggMkMIIDIDAdBgNVHQ4EFgQUwUfE+NgGndWDN3DyVp+CAiF1Zkgw
15 | HwYDVR0jBBgwFoAU6zLUT35gmjqYIGO6DV6+6HlO1SQwggE7BgNVHR8EggEyMIIB
16 | LjCCASqgggEmoIIBIoaB1mxkYXA6Ly8vQ049U2FmYXJpY29tJTIwSW50ZXJuYWwl
17 | MjBJc3N1aW5nJTIwQ0ElMjAwMixDTj1TVkRUM0lTU0NBMDEsQ049Q0RQLENOPVB1
18 | YmxpYyUyMEtleSUyMFNlcnZpY2VzLENOPVNlcnZpY2VzLENOPUNvbmZpZ3VyYXRp
19 | b24sREM9c2FmYXJpY29tLERDPW5ldD9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0
20 | P2Jhc2U/b2JqZWN0Q2xhc3M9Y1JMRGlzdHJpYnV0aW9uUG9pbnSGR2h0dHA6Ly9j
21 | cmwuc2FmYXJpY29tLmNvLmtlL1NhZmFyaWNvbSUyMEludGVybmFsJTIwSXNzdWlu
22 | ZyUyMENBJTIwMDIuY3JsMIIBCQYIKwYBBQUHAQEEgfwwgfkwgckGCCsGAQUFBzAC
23 | hoG8bGRhcDovLy9DTj1TYWZhcmljb20lMjBJbnRlcm5hbCUyMElzc3VpbmclMjBD
24 | QSUyMDAyLENOPUFJQSxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2
25 | aWNlcyxDTj1Db25maWd1cmF0aW9uLERDPXNhZmFyaWNvbSxEQz1uZXQ/Y0FDZXJ0
26 | aWZpY2F0ZT9iYXNlP29iamVjdENsYXNzPWNlcnRpZmljYXRpb25BdXRob3JpdHkw
27 | KwYIKwYBBQUHMAGGH2h0dHA6Ly9jcmwuc2FmYXJpY29tLmNvLmtlL29jc3AwCwYD
28 | VR0PBAQDAgWgMD0GCSsGAQQBgjcVBwQwMC4GJisGAQQBgjcVCIfPjFaEwsQDhemF
29 | NoTe0Q2GoIgIZ4bBx2yDublrAgFkAgEMMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggr
30 | BgEFBQcDATAnBgkrBgEEAYI3FQoEGjAYMAoGCCsGAQUFBwMCMAoGCCsGAQUFBwMB
31 | MA0GCSqGSIb3DQEBCwUAA4IBAQBMFKlncYDI06ziR0Z0/reptIJRCMo+rqo/cUuP
32 | KMmJCY3sXxFHs5ilNXo8YavgRLpxJxdZMkiUIVuVaBanXkz9/nMriiJJwwcMPjUV
33 | 9nQqwNUEqrSx29L1ARFdUy7LhN4NV7mEMde3MQybCQgBjjOPcVSVZXnaZIggDYIU
34 | w4THLy9rDmUIasC8GDdRcVM8xDOVQD/Pt5qlx/LSbTNe2fekhTLFIGYXJVz2rcsj
35 | k1BfG7P3pXnsPAzu199UZnqhEF+y/0/nNpf3ftHZjfX6Ws+dQuLoDN6pIl8qmok9
36 | 9E/EAgL1zOIzFvCRYlnjKdnsuqL1sIYFBlv3oxo6W1O+X9IZ
37 | -----END CERTIFICATE-----
38 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mpesa-node",
3 | "version": "0.1.3",
4 | "description": "Node M-Pesa Library",
5 | "repository": {
6 | "type": "git",
7 | "url": "https://github.com/safaricom/mpesa-node-library"
8 | },
9 | "main": "src/m-pesa.js",
10 | "dependencies": {
11 | "axios": "^0.19.0"
12 | },
13 | "devDependencies": {
14 | "body-parser": "^1.18.2",
15 | "dotenv": "^5.0.1",
16 | "expect.js": "^0.3.1",
17 | "express": "^4.16.3",
18 | "got": "^8.3.0",
19 | "jsdoc": "^3.5.5",
20 | "mocha": "^5.0.1",
21 | "ngrok": "^3.0.0",
22 | "nyc": "^12.0.2",
23 | "standard": "^11.0.0",
24 | "supertest": "^3.0.0"
25 | },
26 | "scripts": {
27 | "test": "npm run test-unit && npm run test-integration",
28 | "test-unit": "mocha tests/unit/*.test.js",
29 | "test-integration": "nyc --reporter=text mocha --exit tests/integrations/*.js"
30 | },
31 | "keywords": [
32 | "mpesa",
33 | "mpesa-node",
34 | "mpesa-api"
35 | ],
36 | "standard": {
37 | "globals": [
38 | "describe",
39 | "context",
40 | "before",
41 | "beforeEach",
42 | "after",
43 | "afterEach",
44 | "it",
45 | "expect"
46 | ]
47 | },
48 | "author": "Geoffrey Mureithi",
49 | "license": "MIT"
50 | }
51 |
--------------------------------------------------------------------------------
/src/endpoints/account-balance.js:
--------------------------------------------------------------------------------
1 | /**
2 | * AccountBalance - Use this API to enquire the balance on an M-Pesa BuyGoods (Till Number)
3 | * @name AccountBalance
4 | * @function
5 | * @see {@link https://developer.safaricom.co.ke/account-balance/apis/post/query|Account Balance Request}
6 | * @param {integer} shortCode The organisation shortCode
7 | * @param {integer} idType Type of organization receiving the transaction
8 | * @param {String} queueUrl The path that stores information of a time out transaction
9 | * @param {String} resultUrl The path that stores information of transaction
10 | * @param {String} [remarks='Checking account balance'] Comments that are sent along with the transaction.
11 | * @param {String} [initiator=null] The name of Initiator to initiating the request
12 | * @param {String} [commandId='AccountBalance'] Takes only 'AccountBalance' CommandID
13 | * @return {Promise} This returns a promise that resolves to the account balance
14 | */
15 | module.exports = async function accountBalance (shortCode, idType, queueUrl, resultUrl, remarks = 'Checking account balance', initiator = null, commandId = 'AccountBalance') {
16 | const securityCredential = this.security()
17 | const req = await this.request()
18 | return req.post('/mpesa/accountbalance/v1/query', {
19 | 'Initiator': initiator || this.configs.initiatorName,
20 | 'SecurityCredential': securityCredential,
21 | 'CommandID': commandId,
22 | 'PartyA': shortCode,
23 | 'IdentifierType': idType,
24 | 'Remarks': remarks,
25 | 'QueueTimeOutURL': queueUrl,
26 | 'ResultURL': resultUrl
27 | })
28 | }
29 |
--------------------------------------------------------------------------------
/src/endpoints/b2b.js:
--------------------------------------------------------------------------------
1 | /**
2 | * B2B Request
3 | * @name B2BRequest
4 | * @function
5 | * @see {@link https://developer.safaricom.co.ke/b2b/apis/post/paymentrequest|Account Balance Request}
6 | * @description - Use this api to transit Mpesa Transaction from one company to another.
7 | * @param {number} senderParty Organization Sending the transaction
8 | * @param {number} receiverParty Organization Receiving the funds
9 | * @param {number} amount The amount been transacted
10 | * @param {string} queueUrl The path that stores information of time out transactions
11 | * @param {string} resultUrl The path that receives results from M-Pesa.
12 | * @param {number} [senderType=4] Type of organization sending the transaction[ default Shortcode]
13 | * @param {number} [receiverType=4] Type of organization receiving the transaction [ default Shortcode]
14 | * @param {string} [initiator=null] This is the credential/username used to authenticate the transaction request.
15 | * @param {String} [commandId='BusinessToBusinessTransfer'] The command id used to carry out a B2B payment[BusinessPayBill,BusinessBuyGoods, DisburseFundsToBusiness, BusinessToBusinessTransfer, MerchantToMerchantTransfer]
16 | * @param {string} [accountRef=null] Account Reference mandatory for "BussinessPaybill" CommandID
17 | * @param {String} [remarks='B2B Request'] Comments that are sent along with the transaction.
18 | * @return {Promise}
19 | */
20 | module.exports = async function (senderParty, receiverParty, amount, queueUrl, resultUrl, senderType = 4, receiverType = 4, initiator = null, commandId = 'BusinessToBusinessTransfer', accountRef = null, remarks = 'B2B Request') {
21 | const req = await this.request()
22 | const securityCredential = this.security()
23 | return req.post('/mpesa/b2b/v1/paymentrequest', {
24 | 'Initiator': initiator || this.configs.initiatorName,
25 | 'SecurityCredential': securityCredential,
26 | 'CommandID': commandId,
27 | 'SenderIdentifierType': senderType,
28 | 'RecieverIdentifierType': receiverType,
29 | 'Amount': amount,
30 | 'PartyA': senderParty,
31 | 'PartyB': receiverParty,
32 | 'AccountReference': accountRef,
33 | 'Remarks': remarks,
34 | 'QueueTimeOutURL': queueUrl,
35 | 'ResultURL': resultUrl
36 | })
37 | }
38 |
--------------------------------------------------------------------------------
/src/endpoints/b2c.js:
--------------------------------------------------------------------------------
1 | /**
2 | * B2C Payment Request
3 | * @name B2CRequest
4 | * @function
5 | * @description Use this API to transact between an M-Pesa short code to a phone number registered on M-Pesa.
6 | * @see {@link https://developer.safaricom.co.ke/b2c/apis/post/paymentrequest|B2C Payment Request}
7 | * @param {number} senderParty Organization /MSISDN sending the transaction
8 | * @param {number} receiverParty MSISDN receiving the transaction
9 | * @param {number} amount The amount being transacted
10 | * @param {string} queueUrl The path that stores information of time out transaction
11 | * @param {string} resultUrl The path that stores information of transaction
12 | * @param {string} [commandId='BusinessPayment'] Unique command for each transaction type [SalaryPayment|BusinessPayment|PromotionPayment]
13 | * @param {string} [initiatorName=null] The name of the initiator initiating the request
14 | * @param {String} [remarks='B2C Payment'] Comments that are sent along with the transaction.
15 | * @param {string} occasion
16 | * @return {Promise}
17 | */
18 | module.exports = async function (senderParty, receiverParty, amount, queueUrl, resultUrl, commandId = 'BusinessPayment', initiatorName = null, remarks = 'B2C Payment', occasion) {
19 | const securityCredential = this.security()
20 | const req = await this.request()
21 | return req.post('/mpesa/b2c/v1/paymentrequest', {
22 | 'InitiatorName': initiatorName || this.configs.initiatorName,
23 | 'SecurityCredential': securityCredential,
24 | 'CommandID': commandId,
25 | 'Amount': amount,
26 | 'PartyA': senderParty,
27 | 'PartyB': receiverParty,
28 | 'Remarks': remarks,
29 | 'QueueTimeOutURL': queueUrl,
30 | 'ResultURL': resultUrl,
31 | 'Occasion': occasion
32 | })
33 | }
34 |
--------------------------------------------------------------------------------
/src/endpoints/c2b-register.js:
--------------------------------------------------------------------------------
1 | /**
2 | * C2B Register URL
3 | * @name C2BRegister
4 | * @function
5 | * @description Use this API to register validation and confirmation URLs on M-Pesa
6 | * @see {@link https://developer.safaricom.co.ke/c2b/apis/post/registerurl| C2B Register URL}
7 | * @param {string} confirmationUrl Validation URL for the client
8 | * @param {string} validationUrl Confirmation URL for the client
9 | * @param {number} [shortCode=null] The short code of the organization.
10 | * @param {string} [responseType='Completed'] Default response type for timeout. Incase a tranaction times out, Mpesa will by default Complete or Cancel the transaction
11 | * @return {Promise}
12 | */
13 | module.exports = async function (confirmationUrl, validationUrl, shortCode = null, responseType = 'Completed') {
14 | const req = await this.request()
15 | return req.post('/mpesa/c2b/v1/registerurl', {
16 | 'ShortCode': shortCode || this.configs.shortCode,
17 | 'ResponseType': responseType,
18 | 'ConfirmationURL': confirmationUrl,
19 | 'ValidationURL': validationUrl
20 | })
21 | }
22 |
--------------------------------------------------------------------------------
/src/endpoints/c2b-simulate.js:
--------------------------------------------------------------------------------
1 | /**
2 | * C2B Simulate Transaction
3 | * @name C2BSimulate
4 | * @function
5 | * @description Use this API to simulate a C2B transaction
6 | * @see {@link https://developer.safaricom.co.ke/c2b/apis/post/simulate | C2B Simulate Transaction }
7 | * @param {number} msisdn Phone number (msisdn) initiating the transaction
8 | * @param {number} amount The amount being transacted
9 | * @param {string} billRefNumber Bill Reference Number
10 | * @param {string} [commandId='CustomerPayBillOnline'] Unique command for each transaction type. For C2B dafult
11 | * @param {number} [shortCode=null] Short Code receiving the amount being transacted
12 | * @return {Promise}
13 | */
14 | module.exports = async function (msisdn, amount, billRefNumber, commandId = 'CustomerPayBillOnline', shortCode = null) {
15 | const req = await this.request()
16 | return req.post('/mpesa/c2b/v1/simulate', {
17 | 'ShortCode': shortCode || this.configs.shortCode,
18 | 'CommandID': commandId,
19 | 'Amount': amount,
20 | 'Msisdn': msisdn,
21 | 'BillRefNumber': billRefNumber
22 | })
23 | }
24 |
--------------------------------------------------------------------------------
/src/endpoints/index.js:
--------------------------------------------------------------------------------
1 | const accountBalance = require('./account-balance')
2 | const b2b = require('./b2b')
3 | const b2c = require('./b2c')
4 | const c2bRegister = require('./c2b-register')
5 | const c2bSimulate = require('./c2b-simulate')
6 | const lipaNaMpesaOnline = require('./lipa-na-mpesa-online')
7 | const lipaNaMpesaQuery = require('./lipa-na-mpesa-query')
8 | const oAuth = require('./oauth')
9 | const reversal = require('./reversal')
10 | const transactionStatus = require('./transaction-status')
11 |
12 | module.exports = {
13 | accountBalance,
14 | b2b,
15 | b2c,
16 | c2bRegister,
17 | c2bSimulate,
18 | lipaNaMpesaOnline,
19 | lipaNaMpesaQuery,
20 | reversal,
21 | transactionStatus,
22 | oAuth
23 | }
24 |
--------------------------------------------------------------------------------
/src/endpoints/lipa-na-mpesa-online.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Lipa Na M-Pesa Online Payment API
3 | * @name lipaNaMpesaOnline
4 | * @description Use this API to initiate online payment on behalf of a customer.
5 | * @see {@link https://developer.safaricom.co.ke/lipa-na-m-pesa-online/apis/post/stkpush/v1/processrequest|Lipa Na M-Pesa Online Payment API }
6 | * @param {number} senderMsisdn The MSISDN sending the funds
7 | * @param {number} amount The amount to be transacted
8 | * @param {string} callbackUrl Call Back URL
9 | * @param {string} accountRef Account Reference
10 | * @param {string} [transactionDesc='Lipa na mpesa online'] any string of less then 20 characters
11 | * @param {string} [transactionType='CustomerPayBillOnline'] The transaction type to be used for the request 'CustomerPayBillOnline'
12 | * @param {number} [shortCode=null] The organization shortcode used to receive the transaction
13 | * @param {string} [passKey=null] Lipa na mpesa passKey
14 | * @return {Promise}
15 | */
16 | module.exports = async function (senderMsisdn, amount, callbackUrl, accountRef, transactionDesc = 'Lipa na mpesa online', transactionType = 'CustomerPayBillOnline', shortCode = null, passKey = null) {
17 | const _shortCode = shortCode || this.configs.lipaNaMpesaShortCode
18 | const _passKey = passKey || this.configs.lipaNaMpesaShortPass
19 | const timeStamp = (new Date()).toISOString().replace(/[^0-9]/g, '').slice(0, -3)
20 | const password = Buffer.from(`${_shortCode}${_passKey}${timeStamp}`).toString('base64')
21 | const req = await this.request()
22 | return req.post('/mpesa/stkpush/v1/processrequest', {
23 | 'BusinessShortCode': _shortCode,
24 | 'Password': password,
25 | 'Timestamp': timeStamp,
26 | 'TransactionType': transactionType,
27 | 'Amount': amount,
28 | 'PartyA': senderMsisdn,
29 | 'PartyB': _shortCode,
30 | 'PhoneNumber': senderMsisdn,
31 | 'CallBackURL': callbackUrl,
32 | 'AccountReference': accountRef,
33 | 'TransactionDesc': transactionDesc
34 | })
35 | }
36 |
--------------------------------------------------------------------------------
/src/endpoints/lipa-na-mpesa-query.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Lipa Na M-Pesa Query Request API
3 | * @name LipaNaMpesaQuery
4 | * @description Use this API to check the status of a Lipa Na M-Pesa Online Payment.
5 | * @param {string} checkoutRequestId Checkout RequestID
6 | * @param {number} [shortCode=null] Business Short Code
7 | * @param {number} [timeStamp=null] timeStamp
8 | * @param {string} [passKey=null] lipaNaMpesa Pass Key
9 | * @return {Promise}
10 | */
11 | module.exports = async function (checkoutRequestId, shortCode = null, passKey = null) {
12 | const _shortCode = shortCode || this.configs.lipaNaMpesaShortCode
13 | const _passKey = passKey || this.configs.lipaNaMpesaShortPass
14 | const timeStamp = (new Date()).toISOString().replace(/[^0-9]/g, '').slice(0, -3)
15 | const password = Buffer.from(`${_shortCode}${_passKey}${timeStamp}`).toString('base64')
16 | const req = await this.request()
17 | return req.post('/mpesa/stkpushquery/v1/query', {
18 | 'BusinessShortCode': _shortCode,
19 | 'Password': password,
20 | 'Timestamp': timeStamp,
21 | 'CheckoutRequestID': checkoutRequestId
22 | })
23 | }
24 |
--------------------------------------------------------------------------------
/src/endpoints/oauth.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios')
2 | module.exports = function (consumerKey, consumerSecret, baseURL = null) {
3 | const auth = Buffer.from(consumerKey + ':' + consumerSecret).toString('base64')
4 | return axios.get((baseURL || this.baseURL) + '/oauth/v1/generate?grant_type=client_credentials', {
5 | headers: {
6 | 'Authorization': 'Basic ' + auth,
7 | 'content-type': 'application/json'
8 | }
9 | })
10 | }
11 |
--------------------------------------------------------------------------------
/src/endpoints/reversal.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Reversal Request
3 | * @name ReversalRequest
4 | * @description Transaction Reversal API reverses a M-Pesa transaction.
5 | * @function
6 | * @see {@link https://developer.safaricom.co.ke/reversal/apis/post/request| Reversal Request}
7 | * @param {string} transactionId The transaction id for reversal eg LKXXXX1234
8 | * @param {string} queueUrl The path that stores information of time out transaction
9 | * @param {string} resultUrl The path that stores information of transaction
10 | * @param {string} [shortCode=null] Organization receiving the transaction
11 | * @param {String} [remarks='Reversal'] Comments that are sent along with the transaction.
12 | * @param {String} [occasion='Reversal'] Optional Parameter
13 | * @param {[type]} [initiator=null] The name of Initiator to initiating the request
14 | * @param {String} [receiverIdType='11'] Type of organization receiving the transaction
15 | * @param {String} [commandId='TransactionReversal'] Takes only 'TransactionReversal' Command id
16 | * @return {Promise}
17 | */
18 | module.exports = async function (transactionId, amount, queueUrl, resultUrl, shortCode = null, remarks = 'Reversal', occasion = 'Reversal', initiator = null, receiverIdType = '11', commandId = 'TransactionReversal') {
19 | const securityCredential = this.security()
20 | const req = await this.request()
21 | return req.post('/mpesa/reversal/v1/request', {
22 | 'Initiator': initiator || this.configs.initiatorName,
23 | 'SecurityCredential': securityCredential,
24 | 'CommandID': commandId,
25 | 'TransactionID': transactionId,
26 | 'Amount': amount,
27 | 'ReceiverParty': shortCode || this.configs.shortCode,
28 | 'RecieverIdentifierType': receiverIdType,
29 | 'ResultURL': resultUrl,
30 | 'QueueTimeOutURL': queueUrl,
31 | 'Remarks': remarks,
32 | 'Occasion': occasion
33 | })
34 | }
35 |
--------------------------------------------------------------------------------
/src/endpoints/transaction-status.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Transaction Status Request
3 | * @name TransactionStatus
4 | * @description Use this api to check the transaction status.
5 | * @function
6 | * @see {@link https://developer.safaricom.co.ke/transaction-status/apis/post/query| Transaction Status Request }
7 | * @param {string} transactionId Unique identifier to identify a transaction on M-Pesa
8 | * @param {number} receiverParty Organization/MSISDN receiving the transaction
9 | * @param {number} idType Type of organization receiving the transaction
10 | * @param {string} queueUrl The path that stores information of time out transaction
11 | * @param {string} resultUrl The path that stores information of transaction
12 | * @param {String} [remarks='TransactionReversal'] Comments that are sent along with the transaction
13 | * @param {String} [occasion='TransactionReversal'] Optional Parameter
14 | * @param {[type]} [initiator=null] The name of Initiator to initiating the request
15 | * @param {String} [commandId='TransactionStatusQuery'] Takes only 'TransactionStatusQuery' command id
16 | * @return {Promise}
17 | */
18 | module.exports = async function (transactionId, receiverParty, idType, queueUrl, resultUrl, remarks = 'TransactionReversal', occasion = 'TransactionReversal', initiator = null, commandId = 'TransactionStatusQuery') {
19 | const securityCredential = this.security()
20 | const req = await this.request()
21 | return req.post('/mpesa/transactionstatus/v1/query', {
22 | 'Initiator': initiator || this.configs.initiatorName,
23 | 'SecurityCredential': securityCredential,
24 | 'CommandID': commandId,
25 | 'TransactionID': transactionId,
26 | 'PartyA': receiverParty,
27 | 'IdentifierType': idType,
28 | 'ResultURL': resultUrl,
29 | 'QueueTimeOutURL': queueUrl,
30 | 'Remarks': remarks,
31 | 'Occasion': occasion
32 | })
33 | }
34 |
--------------------------------------------------------------------------------
/src/helpers/index.js:
--------------------------------------------------------------------------------
1 | const request = require('./request')
2 | const security = require('./security')
3 |
4 | module.exports = {
5 | request,
6 | security
7 | }
8 |
--------------------------------------------------------------------------------
/src/helpers/request.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios')
2 | module.exports = async function (_baseURL = null) {
3 | const credentials = await this.oAuth()
4 | const instance = axios.create({
5 | baseURL: _baseURL || this.baseURL,
6 | timeout: 5000,
7 | headers: {
8 | 'Authorization': 'Bearer ' + credentials.data['access_token'],
9 | 'Content-Type': 'application/json'
10 | }
11 | })
12 | return instance
13 | }
14 |
--------------------------------------------------------------------------------
/src/helpers/security.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | const path = require('path')
3 | const crypto = require('crypto')
4 |
5 | module.exports = (certPath, shortCodeSecurityCredential) => {
6 | const bufferToEncrypt = Buffer.from(shortCodeSecurityCredential)
7 | const data = fs.readFileSync(path.resolve(certPath))
8 | const privateKey = String(data)
9 | const encrypted = crypto.publicEncrypt({
10 | key: privateKey,
11 | padding: crypto.constants.RSA_PKCS1_PADDING
12 | }, bufferToEncrypt)
13 | const securityCredential = encrypted.toString('base64')
14 | return securityCredential
15 | }
16 |
--------------------------------------------------------------------------------
/src/m-pesa.js:
--------------------------------------------------------------------------------
1 | const {
2 | accountBalance,
3 | b2b,
4 | b2c,
5 | c2bRegister,
6 | c2bSimulate,
7 | lipaNaMpesaOnline,
8 | lipaNaMpesaQuery,
9 | oAuth,
10 | reversal,
11 | transactionStatus
12 | } = require('./endpoints')
13 | const {
14 | request,
15 | security
16 | } = require('./helpers')
17 |
18 | /**
19 | * Class representing the Mpesa instance
20 | */
21 | class Mpesa {
22 | /**
23 | * Introduce Mpesa Configuration
24 | * @constructor
25 | * @param {Object} [config={}] The Configuration to use for mPesa
26 | */
27 | constructor (config = {}) {
28 | if (!config.consumerKey) throw new Error('Consumer Key is Missing')
29 | if (!config.consumerSecret) throw new Error('Consumer Secret is Missing')
30 | this.configs = { ...config }
31 | this.enviroment = config.environment === 'production' ? 'production' : 'sandbox'
32 | this.request = request.bind(this)
33 | this.security = () => {
34 | return security(this.configs.certPath, this.configs.securityCredential)
35 | }
36 | this.baseURL = `https://${this.enviroment === 'production' ? 'api' : 'sandbox'}.safaricom.co.ke`
37 | }
38 |
39 | /**
40 | * AccountBalance via instance
41 | * @borrows AccountBalance as accountBalanceCall
42 | */
43 | accountBalance () {
44 | return accountBalance.bind(this)(...arguments)
45 | }
46 |
47 | /**
48 | * B2B Request via instance
49 | * @name b2bCall
50 | */
51 | b2b () {
52 | return b2b.bind(this)(...arguments)
53 | }
54 |
55 | /**
56 | * B2C Request
57 | * @borrows B2CRequest as b2c
58 | */
59 | b2c () {
60 | return b2c.bind(this)(...arguments)
61 | }
62 |
63 | c2bRegister () {
64 | return c2bRegister.bind(this)(...arguments)
65 | }
66 | c2bSimulate () {
67 | if(this.enviroment === 'production'){
68 | throw new Error('Cannot call C2B simulate in production.')
69 | }
70 | return c2bSimulate.bind(this)(...arguments)
71 | }
72 |
73 | lipaNaMpesaOnline () {
74 | return lipaNaMpesaOnline.bind(this)(...arguments)
75 | }
76 |
77 | lipaNaMpesaQuery () {
78 | return lipaNaMpesaQuery.bind(this)(...arguments)
79 | }
80 |
81 | oAuth () {
82 | const { consumerKey, consumerSecret } = this.configs
83 | return oAuth.bind(this)(consumerKey, consumerSecret)
84 | }
85 |
86 | reversal () {
87 | return reversal.bind(this)(...arguments)
88 | }
89 |
90 | transactionStatus () {
91 | return transactionStatus.bind(this)(...arguments)
92 | }
93 | }
94 |
95 | module.exports = Mpesa
--------------------------------------------------------------------------------
/tests/helpers/app.js:
--------------------------------------------------------------------------------
1 | /***
2 | * This is a sample express of how to handle callbacks
3 | * @see {@link https://github.com/safaricom/mpesa_listener| Mpesa Lister Example}
4 | */
5 |
6 | const express = require('express')
7 | const app = express()
8 | const bodyParser = require('body-parser')
9 |
10 | const emitter = require('./callbacksemitter')
11 |
12 | app.use(bodyParser.json())
13 | app.get('/', (req, res) => {
14 | emitter.emit('hello', 'From CallbacksEmitter')
15 | res.send('Hello World!')
16 | })
17 | // AccountBalance
18 | app.post('/accountbalance/timeout', (req, res) => {
19 | emitter.emit('accountBalanceTimeout', { simulation: true, success: true })
20 | res.json({
21 | 'ResponseCode': '00000000',
22 | 'ResponseDesc': 'success'
23 | })
24 | })
25 | app.post('/accountbalance/success', (req, res) => {
26 | emitter.emit('accountBalanceCallback', req.body)
27 | res.json({
28 | 'ResponseCode': '00000000',
29 | 'ResponseDesc': 'success'
30 | })
31 | })
32 |
33 | // B2B Call
34 | app.post('/b2b/timeout', (req, res) => {
35 | emitter.emit('b2bTimeout', { simulation: true, success: true })
36 | res.json({
37 | 'ResponseCode': '00000000',
38 | 'ResponseDesc': 'success'
39 | })
40 | })
41 | app.post('/b2b/success', (req, res) => {
42 | emitter.emit('b2bSuccessCallback', req.body)
43 | res.json({
44 | 'ResponseCode': '00000000',
45 | 'ResponseDesc': 'success'
46 | })
47 | })
48 | // B2C Call
49 | app.post('/b2c/timeout', (req, res) => {
50 | emitter.emit('b2cTimeout', { simulation: true, success: true })
51 | res.json({
52 | 'ResponseCode': '00000000',
53 | 'ResponseDesc': 'success'
54 | })
55 | })
56 | app.post('/b2c/success', (req, res) => {
57 | emitter.emit('b2cSuccessCallback', req.body)
58 | res.json({
59 | 'ResponseCode': '00000000',
60 | 'ResponseDesc': 'success'
61 | })
62 | })
63 | // C2B
64 | app.post('/c2b/confirmation', (req, res) => {
65 | res.json({
66 | 'ResponseCode': '00000000',
67 | 'ResponseDesc': 'success'
68 | })
69 | })
70 | app.post('/c2b/success', (req, res) => {
71 | emitter.emit('c2bSuccessCallback', req.body)
72 | res.json({
73 | 'ResponseCode': '00000000',
74 | 'ResponseDesc': 'success'
75 | })
76 | })
77 |
78 | // Lipa na mpesa
79 | app.post('/lipanampesa/success', (req, res) => {
80 | emitter.emit('lipaNaMpesaOnlineSuccessCallback', req.body)
81 | res.json({
82 | 'ResponseCode': '00000000',
83 | 'ResponseDesc': 'success'
84 | })
85 | })
86 |
87 | // Reversal
88 | app.post('/reversal/timeout', (req, res) => {
89 | emitter.emit('reversalTimeout', { simulation: true, success: true })
90 | res.json({
91 | 'ResponseCode': '00000000',
92 | 'ResponseDesc': 'success'
93 | })
94 | })
95 | app.post('/reversal/success', (req, res) => {
96 | emitter.emit('reversalSuccessCallback', req.body)
97 | res.json({
98 | 'ResponseCode': '00000000',
99 | 'ResponseDesc': 'success'
100 | })
101 | })
102 |
103 | // Transaction Status
104 | app.post('/transactionstatus/timeout', (req, res) => {
105 | emitter.emit('transactionStatusTimeout', { simulation: true, success: true })
106 | res.json({
107 | 'ResponseCode': '00000000',
108 | 'ResponseDesc': 'success'
109 | })
110 | })
111 | app.post('/transactionstatus/success', (req, res) => {
112 | emitter.emit('transactionStatusSuccessCallback', req.body)
113 | res.json({
114 | 'ResponseCode': '00000000',
115 | 'ResponseDesc': 'success'
116 | })
117 | })
118 |
119 | module.exports = app
120 |
--------------------------------------------------------------------------------
/tests/helpers/callbacksemitter.js:
--------------------------------------------------------------------------------
1 | const util = require('util')
2 | const events = require('events')
3 | function CallbacksEmitter () {
4 | events.EventEmitter.call(this)
5 | }
6 |
7 | util.inherits(CallbacksEmitter, events.EventEmitter)
8 |
9 | module.exports = new CallbacksEmitter()
10 |
--------------------------------------------------------------------------------
/tests/helpers/instance.js:
--------------------------------------------------------------------------------
1 | const path = require('path')
2 | const Mpesa = require('../.././src/m-pesa')
3 | require('dotenv').config({path: path.resolve('tests/helpers/tests.env')})
4 | const {
5 | CONSUMER_KEY,
6 | CONSUMER_SECRET,
7 | SHORTCODE,
8 | INITIATOR_NAME,
9 | LIPA_NA_MPESA_SHORTCODE,
10 | LIPA_NA_MPESA_SHORTPASS,
11 | SECURITY_CREDENTIAL
12 | } = process.env
13 | const testInstance = new Mpesa({
14 | consumerKey: CONSUMER_KEY,
15 | consumerSecret: CONSUMER_SECRET,
16 | environment: 'sandbox',
17 | shortCode: SHORTCODE,
18 | initiatorName: INITIATOR_NAME,
19 | lipaNaMpesaShortCode: LIPA_NA_MPESA_SHORTCODE,
20 | lipaNaMpesaShortPass: LIPA_NA_MPESA_SHORTPASS,
21 | securityCredential: SECURITY_CREDENTIAL,
22 | certPath: path.resolve('keys/sandbox-cert.cer')
23 | })
24 |
25 | module.exports = testInstance
26 |
--------------------------------------------------------------------------------
/tests/helpers/ngrok.js:
--------------------------------------------------------------------------------
1 | const http = require('http')
2 | const ngrok = require('ngrok')
3 | function ngrokify (server) {
4 | if (typeof server === 'function') server = http.createServer(server)
5 |
6 | // let ngroked = Object.create(server)
7 | let ngrokURL
8 |
9 | server.once('close', function () {
10 | console.log('Closing time :)')
11 | ngrokURL && ngrok.disconnect(ngrokURL)
12 | })
13 |
14 | let addr = server.address()
15 | if (!addr) server.listen(0)
16 | addr = server.address()
17 | console.log('Using Port ' + addr.port)
18 | return ngrok.connect(addr.port).then(function (url) {
19 | ngrokURL = url
20 | return url
21 | })
22 | }
23 | module.exports = ngrokify
24 |
--------------------------------------------------------------------------------
/tests/helpers/tests.env:
--------------------------------------------------------------------------------
1 | CONSUMER_KEY = OT13kmfq1I8GcD2D4JIcyrHO7C3IAM81
2 | CONSUMER_SECRET= nxKU4f4Zq6h1urLD
3 | SHORTCODE = 600111
4 | INITIATOR_NAME = testapi111
5 | LIPA_NA_MPESA_SHORTCODE = 174379
6 | LIPA_NA_MPESA_SHORTPASS = bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919
7 | SECURITY_CREDENTIAL = Safaricom111!
8 |
--------------------------------------------------------------------------------
/tests/integrations/_before.test.js:
--------------------------------------------------------------------------------
1 | const app = require('.././helpers/app')
2 | const ngrokify = require('.././helpers/ngrok')
3 | const ngrok = require('ngrok')
4 |
5 | before(async function () {
6 | this.timeout(15000)
7 | console.log('Setting up the callback server')
8 | await ngrok.disconnect()
9 | global.NGROK_URL = await ngrokify(app)
10 | console.log('Connected to ' + global.NGROK_URL)
11 | })
12 |
--------------------------------------------------------------------------------
/tests/integrations/_init.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | describe('Callbacks', function () {
5 | it('should have a NGROK_URL', function () {
6 | const URL = global.NGROK_URL
7 | expect(URL.length).to.be.greaterThan(5)
8 | })
9 | it('throws an event and handles it', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.on('hello', function (payload) {
13 | expect(payload).to.be('From CallbacksEmitter')
14 | done()
15 | })
16 | if (!URL) { throw new Error('Missing URL') }
17 | got(URL).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | })
22 |
--------------------------------------------------------------------------------
/tests/integrations/accountbalance.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | const testInstance = require('.././helpers/instance')
5 | describe('Account Callbacks', function () {
6 | /**
7 | * Simulates timeouts coz lol, apparently there is no such way in Daraja
8 | */
9 | it('simulates a timeout', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.once('accountBalanceTimeout', function (payload) {
13 | expect(payload.simulation).to.be(true)
14 | expect(payload.success).to.be(true)
15 | done()
16 | })
17 | got.post(URL + '/accountbalance/timeout', { data: 'test' }).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | it('gets an account balance callback from Daraja', function (done) {
22 | this.timeout(15000)
23 | const URL = global.NGROK_URL
24 | const { shortCode } = testInstance.configs
25 | this.retries(3)
26 | testInstance.accountBalance(shortCode, 4, URL + '/accountbalance/timeout', URL + '/accountbalance/success').catch(e => {
27 | throw new Error('Something went wrong. Message: ' + e.message)
28 | })
29 | emitter.once('accountBalanceCallback', function (payload) {
30 | expect(payload['Result']['ResultDesc']).to.match(/The service request is processed successfully/)
31 | done()
32 | })
33 | })
34 | })
35 |
--------------------------------------------------------------------------------
/tests/integrations/b2b.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | const testInstance = require('.././helpers/instance')
5 | describe('B2B Callbacks', function () {
6 | /**
7 | * Simulates timeouts coz lol, apparently there is no such way in Daraja
8 | */
9 | it('simulates a timeout', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.once('b2bTimeout', function (payload) {
13 | expect(payload.simulation).to.be(true)
14 | expect(payload.success).to.be(true)
15 | done()
16 | })
17 | got.post(URL + '/b2b/timeout', { data: 'test' }).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | it('gets an b2b success callback from Daraja', function (done) {
22 | this.timeout(15000)
23 | const URL = global.NGROK_URL
24 | const { shortCode } = testInstance.configs
25 | const testShortcode2 = 600000
26 | testInstance.b2b(shortCode, testShortcode2, 100, URL + '/b2b/timeout', URL + '/b2b/success').catch(e => {
27 | throw new Error('Something went wrong. Message: ' + e.message)
28 | })
29 | emitter.once('b2bSuccessCallback', function (payload) {
30 | expect(payload['Result']['ResultDesc']).to.match(/The service request is processed successfully/)
31 | done()
32 | })
33 | })
34 | })
35 |
--------------------------------------------------------------------------------
/tests/integrations/b2c.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | const testInstance = require('.././helpers/instance')
5 | describe('B2C Callbacks', function () {
6 | /**
7 | * Simulates timeouts coz lol, apparently there is no such way in Daraja
8 | */
9 | it('simulates a timeout', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.once('b2cTimeout', function (payload) {
13 | expect(payload.simulation).to.be(true)
14 | expect(payload.success).to.be(true)
15 | done()
16 | })
17 | got.post(URL + '/b2c/timeout', { data: 'test' }).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | it('gets an b2c success callback from Daraja', function (done) {
22 | this.timeout(15000)
23 | this.retries(3)
24 | const URL = global.NGROK_URL
25 | const { shortCode } = testInstance.configs
26 | const testMSISDN = 254708374149
27 | testInstance.b2c(shortCode, testMSISDN, 100, URL + '/b2c/timeout', URL + '/b2c/success').catch(e => {
28 | throw new Error('Something went wrong. Message: ' + e.message)
29 | })
30 | emitter.once('b2cSuccessCallback', function (payload) {
31 | expect(payload['Result']['ResultDesc']).to.match(/The service request is processed successfully/)
32 | done()
33 | })
34 | })
35 | })
36 |
--------------------------------------------------------------------------------
/tests/integrations/c2b.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const emitter = require('.././helpers/callbacksemitter')
3 | const testInstance = require('.././helpers/instance')
4 | describe('c2b Callbacks', function () {
5 | it('gets an c2b success callback from Daraja', function (done) {
6 | this.timeout(25000)
7 | const URL = global.NGROK_URL
8 | const { shortCode } = testInstance.configs
9 | const testMSISDN = 254708374149
10 | testInstance.c2bRegister(URL + '/c2b/validation', URL + '/c2b/success')
11 | .then(() => {
12 | testInstance.c2bSimulate(testMSISDN, 100, Math.random().toString(35).substr(2, 7)).catch(e => {
13 | throw new Error('Something went wrong. Message: ' + e.message + ' ' + e.response.message)
14 | })
15 | })
16 | .catch(e => {
17 | throw new Error('Something went wrong. Message: ' + e.message + ' ' + e.response.message)
18 | })
19 | emitter.on('c2bSuccessCallback', function (payload) {
20 | expect(payload['BusinessShortCode']).to.be(`${shortCode}`)
21 | expect(payload['MSISDN']).to.be(`${testMSISDN}`)
22 | done()
23 | })
24 | })
25 | })
26 |
--------------------------------------------------------------------------------
/tests/integrations/lipa-na-mpesa.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const emitter = require('.././helpers/callbacksemitter')
3 | const testInstance = require('.././helpers/instance')
4 | let checkoutRequestId = null
5 | describe('Lipa Na Mpesa Online Callbacks', function () {
6 | const testMSISDN = 254708374149
7 | const amount = 100
8 | it('gets a lipaNaMpesa success callback from Daraja', function (done) {
9 | // Since we have to wait for a time out and das sad and
10 | this.timeout(200 * 1000) // 200s
11 | const URL = global.NGROK_URL
12 | testInstance.lipaNaMpesaOnline(testMSISDN, amount, URL + '/lipanampesa/success', Math.random().toString(35).substr(2, 7))
13 | .then(({ data }) => {
14 | checkoutRequestId = data['CheckoutRequestID']
15 | })
16 | .catch(e => {
17 | throw new Error('Something went wrong. Message: ' + e.message + ' ' + e.response.message)
18 | })
19 | emitter.on('lipaNaMpesaOnlineSuccessCallback', function (payload) {
20 | expect(payload).to.be.ok()
21 | done()
22 | })
23 | })
24 |
25 | it(`allows checking of lipaNaMpesa status for ${checkoutRequestId}`, function (done) {
26 | this.timeout(5000)
27 | testInstance.lipaNaMpesaQuery(checkoutRequestId).then(({ data }) => {
28 | expect(data['ResponseDescription']).to.match(/The service request has been accepted successsfully/)
29 | done()
30 | }).catch(e => {
31 | throw new Error('Something went wrong. Message: ' + e.message + ' ' + e.response.message)
32 | })
33 | })
34 | })
35 |
--------------------------------------------------------------------------------
/tests/integrations/reversal.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | const testInstance = require('.././helpers/instance')
5 | describe('Reversal Callbacks', function () {
6 | /**
7 | * Simulates timeouts coz lol, apparently there is no such way in Daraja
8 | */
9 | it('simulates a timeout', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.once('reversalTimeout', function (payload) {
13 | expect(payload.simulation).to.be(true)
14 | expect(payload.success).to.be(true)
15 | done()
16 | })
17 | got.post(URL + '/reversal/timeout', { data: 'test' }).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | it('gets an reversal success callback from Daraja', function (done) {
22 | this.timeout(15000)
23 | this.retries(3)
24 | const URL = global.NGROK_URL
25 | testInstance.reversal('LKXXXX1234', 100, URL + '/reversal/timeout', URL + '/reversal/success').catch(e => {
26 | throw new Error('Something went wrong. Message: ' + e.message)
27 | })
28 | emitter.once('reversalSuccessCallback', function (payload) {
29 | expect(payload['Result']['ResultDesc']).to.match(/The OriginalTransactionID is invalid./)
30 | done()
31 | })
32 | })
33 | })
34 |
--------------------------------------------------------------------------------
/tests/integrations/transactionstatus.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const got = require('got')
3 | const emitter = require('.././helpers/callbacksemitter')
4 | const testInstance = require('.././helpers/instance')
5 | describe('TransactionStatus Callbacks', function () {
6 | /**
7 | * Simulates timeouts coz lol, apparently there is no such way in Daraja
8 | */
9 | it('simulates a timeout', function (done) {
10 | this.timeout(15000)
11 | const URL = global.NGROK_URL
12 | emitter.once('transactionStatusTimeout', function (payload) {
13 | expect(payload.simulation).to.be(true)
14 | expect(payload.success).to.be(true)
15 | done()
16 | })
17 | got.post(URL + '/transactionstatus/timeout', { data: 'test' }).then(r => r).catch(e => {
18 | throw new Error('Something went wrong. Message: ' + e.message)
19 | })
20 | })
21 | it('gets a transactionStatus success callback from Daraja', function (done) {
22 | this.timeout(15000)
23 | this.retries(3)
24 | const URL = global.NGROK_URL
25 | const { shortCode } = testInstance.configs
26 | testInstance.transactionStatus('LKXXXX1234', shortCode, 4, URL + '/transactionstatus/timeout', URL + '/transactionstatus/success').catch(e => {
27 | throw new Error('Something went wrong. Message: ' + e.message)
28 | })
29 | emitter.once('transactionStatusSuccessCallback', function (payload) {
30 | expect(payload['Result']['ResultDesc']).to.match(/The format of parameter null is invalid./)
31 | done()
32 | })
33 | })
34 | })
35 |
--------------------------------------------------------------------------------
/tests/unit/index.test.js:
--------------------------------------------------------------------------------
1 | const expect = require('expect.js')
2 | const Mpesa = require('../.././src/m-pesa')
3 | const instance = new Mpesa({ consumerKey: 'test', consumerSecret: 'test' })
4 | const {
5 | accountBalance,
6 | b2b,
7 | b2c,
8 | c2bRegister,
9 | c2bSimulate,
10 | lipaNaMpesaOnline,
11 | lipaNaMpesaQuery,
12 | oAuth,
13 | reversal,
14 | transactionStatus
15 | } = instance
16 |
17 | describe('All Methods are Callble', function () {
18 | [
19 | accountBalance,
20 | b2b,
21 | b2c,
22 | c2bRegister,
23 | c2bSimulate,
24 | lipaNaMpesaOnline,
25 | lipaNaMpesaQuery,
26 | oAuth,
27 | reversal,
28 | transactionStatus ].map(f => {
29 | it(f.name, function () {
30 | expect(typeof f).to.be('function')
31 | })
32 | })
33 | })
34 |
35 | describe('C2B', function () {
36 | const productionInstance = new Mpesa({
37 | consumerKey: 'test',
38 | consumerSecret: 'test',
39 | environment: 'production'
40 | })
41 |
42 | it('should throw error in production', function () {
43 | let threwError = false
44 |
45 | try {
46 | productionInstance.c2bSimulate()
47 | } catch (e) {
48 | threwError = true
49 | expect(e.message).to.be('Cannot call C2B simulate in production.')
50 | } finally {
51 | expect(threwError).to.be(true)
52 | }
53 | })
54 | })
55 |
--------------------------------------------------------------------------------