UNPKG

mpesa-nodejs-sdk

Version:

Node.Js wrapper for Safaricom's Mpesa API. Written in Typescript

111 lines (110 loc) 5.32 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MpesaApi = void 0; const axios_1 = __importDefault(require("axios")); class MpesaApi { constructor(consumerKey, secret, shortcode, env = 'dev') { this.token = ''; this.consumerKey = consumerKey; this.secret = secret; this.shortcode = shortcode; if (env !== 'production') { this.url = 'https://sandbox.safaricom.co.ke'; } else { this.url = 'https://api.safaricom.co.ke'; } axios_1.default.defaults.baseURL = this.url; } /** * getAccessToken * @returns a promise with the access token and success message. */ getAccessToken() { return __awaiter(this, void 0, void 0, function* () { const authKey = Buffer.from(`${this.consumerKey}:${this.secret}`).toString('base64'); // console.log(axios.defaults.url) const request = yield axios_1.default.get('/oauth/v1/generate?grant_type=client_credentials', { headers: { Authorization: `Basic ${authKey}` } }); if (request.status == 200) { const data = request.data; const { access_token } = data; this.token = access_token; } return Promise.resolve(request.data); }); } /** * registerUrl * Registers the confirmation and validation urls * @param confirmationUrl - the receives the confirmation request from the API upon the * payment completion * @param validationUrl - receives the validation request from the API upon the payment * submission. It is called only if the external validation on the registered shortcode is * enabled.By default the external validation is disabled * @param responseType - specifies what is to happen if for any reason the validation url is not * reachable. It can only have two options 'Completed' or 'Cancelled'. Completed means Mpesa * will automatically complete the transaction whereas cancelled means the transaction will be cancelled if the validation url is not reachable * @returns a promise that contains the OriginatorConversationId, ConversationId and Response Description. */ registerUrl(confirmationUrl, validationUrl, responseType = 'Completed') { return __awaiter(this, void 0, void 0, function* () { const requestData = { "ShortCode": this.shortcode, "ResponseType": responseType, "ConfirmationURL": confirmationUrl, "ValidationURL": validationUrl }; const token = this.token; const registerRequest = yield axios_1.default.post('/mpesa/c2b/v1/registerurl', requestData, { headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" } }); return Promise.resolve(registerRequest.data); }); } /** * c2B - Make payment requests from Client to Business * @param commandId - the unique identifier of the transaction type. Can either be CustomerPayBillOnline for paybill payments or CustomerBuyGoodsOnline for business shortcodes * @param amount - The amount being transacted * @param Msisdn - The phone number initiating the transaction * @param BillRefNumber - Only used for CustomerPayBillOnline. It represents a unique bill identifier e.g. an account number * @returns - a promise which contains originatorConversationId, conversationId and ResponseDescription */ c2B(commandId, amount, Msisdn, BillRefNumber) { return __awaiter(this, void 0, void 0, function* () { const requestData = { "ShortCode": this.shortcode, "CommandID": commandId, "Amount": amount, "Msisdn": Msisdn, "BillRefNumber": commandId == 'CustomerPayBillOnline' ? BillRefNumber : " " }; const request = yield axios_1.default.post('/mpesa/c2b/v1/simulate', requestData, { headers: { "Authorization": `Bearer ${this.token}`, "Content-Type": "application/json" } }); return Promise.resolve(request.data); }); } } exports.MpesaApi = MpesaApi;