UNPKG

daraja-pie

Version:

A simple JS API built on top of M-Pesa's daraja

114 lines (100 loc) 2.65 kB
import axios from "axios"; import { END_POINTS } from "./constants.js"; // GET ACESS TOKEN export async function getAccessToken() { const config = { headers: { Authorization: `Basic ${process.env.MPESA_CREDS}`, }, }; try { const { data } = await axios.get(END_POINTS.GET_TOKEN, config); return data.access_token; } catch (err) { throw new Error(err); } } // PROCESS STK_PUSH PAYMENTS export async function processRequest(details) { const token = await getAccessToken(); if (token) { const config = { headers: { "Content-type": "application/json", Authorization: `Bearer ${token}`, }, }; const body = JSON.stringify(details); try { const { data } = axios.post(END_POINTS.STK_PUSH, body, config); return data; } catch (err) { throw new Error(err); } } else { throw new Error("Failed to get access token"); } } // REGISTER A URL export async function registerUrl(details) { const token = await getAccessToken(); if (token) { const config = { headers: { "Content-type": "application/json", Authorization: `Bearer ${token}`, }, }; try { const body = JSON.stringify(details); const { data } = await axios.post(END_POINTS.REG_URL, body, config); return data; } catch (err) { throw new Error(err); } } else { throw new Error("Failed to get access token"); } } // B2C PAYMENTS export async function makeB2CRequest(details) { const token = await getAccessToken(); if (token) { const config = { headers: { "Content-type": "application/json", Authorization: `Bearer ${token}`, }, }; try { const body = JSON.stringify(details); const { data } = await axios.post(END_POINTS.B2C, body, config); return data; } catch (err) { throw new Error(err); } } else { throw new Error("Failed to get access token"); } } // GET TRANSACTION STATUS export async function queryTransactionStatus(details) { const token = await getAccessToken(); if (token) { const config = { headers: { "Content-type": "application/json", Authorization: `Bearer ${token}`, }, }; try { const body = JSON.stringify(details); const { data } = await axios.post(END_POINTS.TSC_STATUS, body, config); return data; } catch (err) { throw new Error(err); } } else { throw new Error("Failed to get access token"); } }