Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions templates/mpesa-nextjs-express/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
MPESA_SHORTCODE="174379"
MPESA_PASSKEY="bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919"
MPESA_CONSUMER_KEY=""
MPESA_CONSUMER_SECRET=""

CALLBACK_URL="https://example.com"
57 changes: 37 additions & 20 deletions templates/mpesa-nextjs-express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,50 @@

A <%= api %> API built with `create-daraja-app` platform for <%= framework %>. This project was bootstrapped with `create-daraja-api`

## Setup

- Run `npm install` on the root of this project to install dependencies.
- Run `npm run dev` to start the project

## API
## API Structure

The API exposes two endpoints:

- `/api/example/stk` - A `POST` endpoint that Handles the STK push and takes in `phone` and `amount` in the request body.
- `/api/example/stk` - A `POST` endpoint that handles the STK push and takes in `phone` and `amount` in the request body.
- `/api/example/callback` - A `POST` endpoint that acts as a hook to listen to callbacks from the Daraja platform.

## Extending functionality
## Setup

### Prerequisites

1. Create an account on [Safaricom developers portal (Daraja)](https://developer.safaricom.co.ke/)
2. Create a new app under [My Apps](https://developer.safaricom.co.ke/MyApps) section ensuring to check all the fields. You will be able to see consumer key and consumer secret under each app
3. Have `node.js` installed (or reuse the implementation in your favorite programming language or framework)
4. (Optional) Have `ngrok` installed - Use this to simulate https on our localhost server. If you already have `node.js` then you can install it by running `npm install -g ngrok` or run it directly on `npx`. Otherwise, download it from ngrok download page.
5. Have Postman or any other API testing tool installed
1. Create an account on [Safaricom developers portal (Daraja)](https://developer.safaricom.co.ke/).
2. Create a new app under [My Apps](https://developer.safaricom.co.ke/MyApps) section ensuring to check all the fields. You will be able to see `consumer key` and `consumer secret` under each app.
3. Have [Node.js](https://nodejs.org/) installed.

### Setup
### Test the app

1. Run `ngrok http 5000` in a terminal in the project root
2. Fill in the `.env` with the necessary information. Replace the `CALLBACK_URL` with the https version of the link provided on the ngrok terminal in step 1
3. Start the project by running `node index.js`
4. In Postman, create a `POST` request with the body containing the `phone` and `amount`
5. Press send and “fingers crossed” you should receive a push on your phone
6. On the `node.js` terminal, you should see a console logging once you either accept or decline the push.
- Rename the `.env.example` to `.env` and populate the `consumer key` and `consumer secret`.
- Run `npm install` on the root of this project to install dependencies.
- Run `npm run dev` to start the project.
- Send a `POST` request to `/api/example/stk` with the request body below:

```json
{
"phone": 254700000000,
"amount": 1
}
```

- The response will look like this:

```json
{
"MerchantRequestID": "1c5b-4ba8-815c-ac45c57a3db0570513",
"CheckoutRequestID": "ws_CO_17052024122600366799055101",
"ResponseCode": "0",
"ResponseDescription": "Success. Request accepted for processing",
"CustomerMessage": "Success. Request accepted for processing"
}
```

### Callback

1. Run `npx ngrok http 5000` in a terminal in the project root
2. Replace the `CALLBACK_URL` in the `.env` with the https version of the link provided on the ngrok terminal inthe previous step.
3. Next.js will reload to pick up the new `CALLBACK_URL` in the `.env`.
4. Resend the request and once you action on the prompt, you should see on the running terminal, a console log with the callback info.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default async function POST(request: Request) {
export async function POST(request: Request) {
const body = await request.json()

console.info(`
Expand All @@ -12,5 +12,5 @@ export default async function POST(request: Request) {

`)

Response.json({ success: true })
return Response.json({ success: true })
}
4 changes: 2 additions & 2 deletions templates/mpesa-nextjs-express/app/api/example/stk/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import getMpesaPassword from '@/utilities/getMpesaPassword'
import variables from '@/utilities/variables'
import axios from 'axios'

export default async function POST(request: Request) {
export async function POST(request: Request) {
const { phone, amount } = await request.json()
const { access_token } = await getMpesaCredentials()

Expand Down Expand Up @@ -31,7 +31,7 @@ export default async function POST(request: Request) {
headers: { Authorization: `Bearer ${access_token}` },
}

axios
return await axios
.post(
'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest',
data,
Expand Down
15 changes: 7 additions & 8 deletions templates/mpesa-nextjs-express/utilities/getMpesaCredentials.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import variables from './variables.js'
import variables from './variables'
import axios from 'axios'

const getMpesaCredentials = async () => {
let credential = {}

const config = {
headers: {
Authorization: `Basic ${Buffer.from(
Expand All @@ -12,15 +10,16 @@ const getMpesaCredentials = async () => {
},
}

await axios
return await axios
.get(
'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials',
config
)
.then((resp) => (credential = resp.data))
.catch((error) => console.error({ error: error.message }))

return credential
.then((resp) => resp.data)
.catch((error) => {
console.error('getMpesaCredentials: ', { error: error.message })
return {}
})
}

export default getMpesaCredentials
5 changes: 0 additions & 5 deletions templates/mpesa-nodejs-express/.env

This file was deleted.

6 changes: 6 additions & 0 deletions templates/mpesa-nodejs-express/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
MPESA_SHORTCODE="174379"
MPESA_PASSKEY="bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919"
MPESA_CONSUMER_KEY=""
MPESA_CONSUMER_SECRET=""

CALLBACK_URL="https://example.com"
57 changes: 37 additions & 20 deletions templates/mpesa-nodejs-express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,50 @@

A <%= api %> API built with `create-daraja-app` platform for <%= framework %>. This project was bootstrapped with `create-daraja-api`

## Setup

- Run `npm install` on the root of this project to install dependencies.
- Run `npm run dev` to start the project

## API
## API Structure

The API exposes two endpoints:

- `/api/example/stk` - A `POST` endpoint that Handles the STK push and takes in `phone` and `amount` in the request body.
- `/api/example/stk` - A `POST` endpoint that handles the STK push and takes in `phone` and `amount` in the request body.
- `/api/example/callback` - A `POST` endpoint that acts as a hook to listen to callbacks from the Daraja platform.

## Extending functionality
## Setup

### Prerequisites

1. Create an account on [Safaricom developers portal (Daraja)](https://developer.safaricom.co.ke/)
2. Create a new app under [My Apps](https://developer.safaricom.co.ke/MyApps) section ensuring to check all the fields. You will be able to see consumer key and consumer secret under each app
3. Have `node.js` installed (or reuse the implementation in your favorite programming language or framework)
4. (Optional) Have `ngrok` installed - Use this to simulate https on our localhost server. If you already have `node.js` then you can install it by running `npm install -g ngrok` or run it directly on `npx`. Otherwise, download it from ngrok download page.
5. Have Postman or any other API testing tool installed
1. Create an account on [Safaricom developers portal (Daraja)](https://developer.safaricom.co.ke/).
2. Create a new app under [My Apps](https://developer.safaricom.co.ke/MyApps) section ensuring to check all the fields. You will be able to see `consumer key` and `consumer secret` under each app.
3. Have [Node.js](https://nodejs.org/) installed.

### Setup
### Test the app

1. Run `ngrok http 5000` in a terminal in the project root
2. Fill in the `.env` with the necessary information. Replace the `CALLBACK_URL` with the https version of the link provided on the ngrok terminal in step 1
3. Start the project by running `node index.js`
4. In Postman, create a `POST` request with the body containing the `phone` and `amount`
5. Press send and “fingers crossed” you should receive a push on your phone
6. On the `node.js` terminal, you should see a console logging once you either accept or decline the push.
- Rename the `.env.example` to `.env` and populate the `consumer key` and `consumer secret`.
- Run `npm install` on the root of this project to install dependencies.
- Run `npm run dev` to start the project.
- Send a `POST` request to `/api/example/stk` with the request body below:

```json
{
"phone": 254700000000,
"amount": 1
}
```

- The response will look like this:

```json
{
"MerchantRequestID": "1c5b-4ba8-815c-ac45c57a3db0570513",
"CheckoutRequestID": "ws_CO_17052024122600366799055101",
"ResponseCode": "0",
"ResponseDescription": "Success. Request accepted for processing",
"CustomerMessage": "Success. Request accepted for processing"
}
```

### Callback

1. Run `npx ngrok http 5000` in a terminal in the project root
2. Replace the `CALLBACK_URL` in the `.env` with the https version of the link provided on the ngrok terminal inthe previous step.
3. Rerun the project to pick up the new `CALLBACK_URL` in the `.env`.
4. Resend the request and once you action on the prompt, you should see on the running terminal, a console log with the callback info.
5 changes: 4 additions & 1 deletion templates/mpesa-nodejs-express/controllers/stkController.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@ export const stk = async (req, res, next) => {
config
)
.then((resp) => res.send(resp.data))
.catch((error) => res.status(400).send({ message: error?.message }));
.catch((error) => {
console.error('stkController', { message: error?.message });
res.status(400).send({ message: error?.message });
});
};
Loading