This article is a documentation of how I implemented a lightweight Lipa na M-Pesa endpoint using Safaricom's Daraja API for my final year project. The project is a bus fare collection mobile app built on React Native for the client and Firebase as the Backend. I had to implement an additional endpoint for the payment gateway. That's where NodeJs with Express and Daraja API come in. Enjoy.
From there you will be provided with a Consumer Key and a Consumer Secret. These credentials wil be necessary to interact with Safaricom's Daraja API. Keep them securely.
In your terminal window or text editor of choice, initialize a new nodejs project.
npm init -ycopy
Install necessary dependencies
npm i express axios dotenv nodemoncopy
Create a new file
touch index.jscopy
This is where all the code for our Lipa na M-Pesa endpoint will reside.
On success, you should receive a similar response to:
A this point you will receive an STK Push on your mobile phone. You can either accept or decline the payment (I personally recommend the latter since the refund process is quite the hassle).
The callback url option in the payment request is useful when handling advanced payment operations on your app such as recording transactions i.e, you could store transaction history for one of your users with recipts and transaction IDs. The callback url has to be htps (http secure). If you haven't deployed your application yet you can use nginx which will give you a temporary https endpont and map it to your localhost at a port of your choosing.