@allan70/daraja-package
Version:
A package to middle-man DarajaAPI 2.0 requests to perform M-Pesa transactions
52 lines (41 loc) • 1.97 kB
JavaScript
const mpesa_paybill = (paybillbody) => {
const phoneNumber = paybillbody.phoneNumber; //ensure it starts with 254 eg. 254708374149
const amountFromUser = paybillbody.amountFromUser;
const businessNumber = paybillbody.businessNumber; //your paybill
const mpesaPassword = paybillbody.mpesaPassword;
const merchantEndPoint = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest'; // change the sandbox to api during production
const callBackURL = paybillbody.callback_URL;
const secret = paybillbody.secret;
const consumer = paybillbody.consumer;
// import timestamp
const timestamp = require('./timestamp')
// generate token
const generateToken = require('./generateToken');
const pass = (businessNumber + mpesaPassword + timestamp);
const passwordSaf = Buffer.from(pass,'base64');
const darajaRequestBody = {
"BusinessShortCode": parseInt(businessNumber),
"Password": passwordSaf,
"Timestamp": timestamp,
"TransactionType": "CustomerPayBillOnline",
"Amount": parseInt(amountFromUser),
"PartyA": parseInt(`254${phoneNumber}`),
"PartyB": parseInt(businessNumber),
"PhoneNumber": parseInt(`254${phoneNumber}`),
"CallBackURL": callBackURL,
"AccountReference": (paybillbody.account_reference), //`254${phoneNumber}`
"TransactionDesc": (paybillbody.transaction_desc) //Enter your randomly generated ticket numbers here.
}
let unirest = require('unirest');
let token = generateToken(secret,consumer);
return request = unirest('POST', merchantEndPoint).headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}).send(darajaRequestBody).end(res => {
if (res.error){
return res.error;
}
return res.raw_body;
});
};
module.exports = mpesa_paybill;