UNPKG

@allan70/daraja-package

Version:

A package to middle-man DarajaAPI 2.0 requests to perform M-Pesa transactions

49 lines (40 loc) 1.98 kB
const mpesa_buy_goods = (buyGoodsBody) => { const phoneNumber = buyGoodsBody.phoneNumber; //ensure it starts with 254 eg. 254708374149 const amountFromUser = buyGoodsBody.amountFromUser; const businessNumber = buyGoodsBody.businessNumber; //your paybill const mpesaPassword = buyGoodsBody.mpesaPassword; const merchantEndPoint = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest'; // change the sandbox to api during production const callBackURL = buyGoodsBody.callback_URL; const secret = buyGoodsBody.secret; const consumer = buyGoodsBody.cosumer; // import timestamp const timestamp = require('./timestamp') // Import generate token // Middleware to generate token const generateToken = require('./generateToken'); const pass = (businessNumber + mpesaPassword + timestamp); const passwordSaf = btoa(pass); const darajaRequestBody = { "BusinessShortCode": parseInt(businessNumber), "Password": passwordSaf, "Timestamp": timestamp, "TransactionType": "CustomerBuyGoodsOnline", "Amount": parseInt(amountFromUser), "PartyA": parseInt(`254${phoneNumber}`), "PartyB": parseInt(businessNumber), "PhoneNumber": parseInt(`254${phoneNumber}`), "CallBackURL": callBackURL, "AccountReference": (buyGoodsBody.account_reference), //`254${phoneNumber}` "TransactionDesc": (buyGoodsBody.transaction_desc) //Enter your randomly generated ticket numbers here. } let unirest = require('unirest'); return request = unirest('POST', merchantEndPoint).headers({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${generateToken(secret, consumer)}` }).send(darajaRequestBody).end(res => { if (res.error) console.log(res.error); console.log(res.raw_body); }); }; module.exports = mpesa_buy_goods;