-
Notifications
You must be signed in to change notification settings - Fork 22
/
app.js
220 lines (201 loc) Β· 6.43 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
Author: Alvin Kiveu
Description: Mpesa Daraja API with Node JS
Date: 23/10/2023
Github Link: https://github.com/alvin-kiveu/Mpesa-Daraja-Api-NODE.JS.git
Website: www.umeskiasoftwares.com
Email: [email protected]
Phone: +254113015674
*/
const express = require("express");
const app = express();
const http = require("http");
const bodyParser = require("body-parser");
const axios = require("axios"); // Import 'axios' instead of 'request'
const moment = require("moment");
const apiRouter = require('./api');
const cors = require("cors");
const fs = require("fs");
const port = 5000;
const hostname = "localhost";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use('/', apiRouter);
const server = http.createServer(app);
// ACCESS TOKEN FUNCTION - Updated to use 'axios'
async function getAccessToken() {
const consumer_key = ""; // REPLACE IT WITH YOUR CONSUMER KEY
const consumer_secret = ""; // REPLACE IT WITH YOUR CONSUMER SECRET
const url =
"https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
const auth =
"Basic " +
new Buffer.from(consumer_key + ":" + consumer_secret).toString("base64");
try {
const response = await axios.get(url, {
headers: {
Authorization: auth,
},
});
const dataresponse = response.data;
// console.log(data);
const accessToken = dataresponse.access_token;
return accessToken;
} catch (error) {
throw error;
}
}
app.get("/", (req, res) => {
res.send("MPESA DARAJA API WITH NODE JS BY UMESKIA SOFTWARES");
var timeStamp = moment().format("YYYYMMDDHHmmss");
console.log(timeStamp);
});
//ACCESS TOKEN ROUTE
app.get("/access_token", (req, res) => {
getAccessToken()
.then((accessToken) => {
res.send("π Your access token is " + accessToken);
})
.catch(console.log);
});
//MPESA STK PUSH ROUTE
app.get("/stkpush", (req, res) => {
getAccessToken()
.then((accessToken) => {
const url =
"https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest";
const auth = "Bearer " + accessToken;
const timestamp = moment().format("YYYYMMDDHHmmss");
const password = new Buffer.from(
"174379" +
"bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919" +
timestamp
).toString("base64");
axios
.post(
url,
{
BusinessShortCode: "174379",
Password: password,
Timestamp: timestamp,
TransactionType: "CustomerPayBillOnline",
Amount: "10",
PartyA: "", //phone number to receive the stk push
PartyB: "174379",
PhoneNumber: "",
CallBackURL: "https://dd3d-105-160-22-207.ngrok-free.app/callback",
AccountReference: "UMESKIA PAY",
TransactionDesc: "Mpesa Daraja API stk push test",
},
{
headers: {
Authorization: auth,
},
}
)
.then((response) => {
res.send("π Request is successful done ββ. Please enter mpesa pin to complete the transaction");
})
.catch((error) => {
console.log(error);
res.status(500).send("β Request failed");
});
})
.catch(console.log);
});
//STK PUSH CALLBACK ROUTE
app.post("/callback", (req, res) => {
console.log("STK PUSH CALLBACK");
const CheckoutRequestID = req.body.Body.stkCallback.CheckoutRequestID;
const ResultCode = req.body.Body.stkCallback.ResultCode;
var json = JSON.stringify(req.body);
fs.writeFile("stkcallback.json", json, "utf8", function (err) {
if (err) {
return console.log(err);
}
console.log("STK PUSH CALLBACK JSON FILE SAVED");
});
console.log(req.body);
});
// REGISTER URL FOR C2B
app.get("/registerurl", (req, resp) => {
getAccessToken()
.then((accessToken) => {
const url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl";
const auth = "Bearer " + accessToken;
axios
.post(
url,
{
ShortCode: "174379",
ResponseType: "Complete",
ConfirmationURL: "http://example.com/confirmation",
ValidationURL: "http://example.com/validation",
},
{
headers: {
Authorization: auth,
},
}
)
.then((response) => {
resp.status(200).json(response.data);
})
.catch((error) => {
console.log(error);
resp.status(500).send("β Request failed");
});
})
.catch(console.log);
});
app.get("/confirmation", (req, res) => {
console.log("All transaction will be sent to this URL");
console.log(req.body);
});
app.get("/validation", (req, resp) => {
console.log("Validating payment");
console.log(req.body);
});
// B2C ROUTE OR AUTO WITHDRAWAL
app.get("/b2curlrequest", (req, res) => {
getAccessToken()
.then((accessToken) => {
const securityCredential =
"N3Lx/hisedzPLxhDMDx80IcioaSO7eaFuMC52Uts4ixvQ/Fhg5LFVWJ3FhamKur/bmbFDHiUJ2KwqVeOlSClDK4nCbRIfrqJ+jQZsWqrXcMd0o3B2ehRIBxExNL9rqouKUKuYyKtTEEKggWPgg81oPhxQ8qTSDMROLoDhiVCKR6y77lnHZ0NU83KRU4xNPy0hRcGsITxzRWPz3Ag+qu/j7SVQ0s3FM5KqHdN2UnqJjX7c0rHhGZGsNuqqQFnoHrshp34ac/u/bWmrApUwL3sdP7rOrb0nWasP7wRSCP6mAmWAJ43qWeeocqrz68TlPDIlkPYAT5d9QlHJbHHKsa1NA==";
const url = "https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";
const auth = "Bearer " + accessToken;
axios
.post(
url,
{
InitiatorName: "testapi",
SecurityCredential: securityCredential,
CommandID: "PromotionPayment",
Amount: "1",
PartyA: "600996",
PartyB: "",//phone number to receive the stk push
Remarks: "Withdrawal",
QueueTimeOutURL: "https://mydomain.com/b2c/queue",
ResultURL: "https://mydomain.com/b2c/result",
Occasion: "Withdrawal",
},
{
headers: {
Authorization: auth,
},
}
)
.then((response) => {
res.status(200).json(response.data);
})
.catch((error) => {
console.log(error);
res.status(500).send("β Request failed");
});
})
.catch(console.log);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});