UNPKG

mds-daraja-sdk

Version:

A simple SDK for integrating with Safaricom's Daraja API for M-Pesa payments.

132 lines (131 loc) 5.95 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.MdsDarajaSdk = void 0; const axios_1 = __importDefault(require("axios")); class MdsDarajaSdk { constructor(consumerKey, consumerSecret, sandbox = true) { this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.baseUrl = sandbox ? "https://sandbox.safaricom.co.ke" : "https://api.safaricom.co.ke"; } getAccessToken() { return __awaiter(this, void 0, void 0, function* () { const url = `${this.baseUrl}/oauth/v1/generate?grant_type=client_credentials`; const credentials = `${this.consumerKey}:${this.consumerSecret}`; const auth = Buffer.from(credentials).toString("base64"); const response = yield axios_1.default.get(url, { headers: { Authorization: `Basic ${auth}`, }, }); return response.data.access_token; }); } initiateStkPush(businessShortCode, password, timestamp, phoneNumber, amount, callbackUrl) { var _a; return __awaiter(this, void 0, void 0, function* () { const accessToken = yield this.getAccessToken(); const url = `${this.baseUrl}/mpesa/stkpush/v1/processrequest`; const requestBody = { BusinessShortCode: businessShortCode, Password: password, Timestamp: timestamp, TransactionType: "CustomerPayBillOnline", Amount: amount, PartyA: phoneNumber, PartyB: businessShortCode, PhoneNumber: phoneNumber, CallBackURL: callbackUrl, AccountReference: (_a = process.env.DARAJA_API_APP_NAME) !== null && _a !== void 0 ? _a : "Test Payment", TransactionDesc: "TestPayment", }; const response = yield axios_1.default.post(url, requestBody, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); return response.data; }); } reverseTransaction(shortCode, password, transactionID) { return __awaiter(this, void 0, void 0, function* () { const accessToken = yield this.getAccessToken(); const url = `${this.baseUrl}/mpesa/reversal/v1/request`; const requestBody = { Initiator: shortCode, SecurityCredential: password, CommandID: "TransactionReversal", TransactionID: transactionID, Amount: 1, ReceiverParty: shortCode, RecieverIdentifierType: "11", Remarks: "Reversal", QueueTimeOutURL: "https://example.com/timeout", ResultURL: "https://example.com/result", }; const response = yield axios_1.default.post(url, requestBody, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); return response.data; }); } initiateB2cPayment(shortCode, password, phoneNumber, amount) { return __awaiter(this, void 0, void 0, function* () { const accessToken = yield this.getAccessToken(); const url = `${this.baseUrl}/mpesa/b2c/v1/paymentrequest`; const requestBody = { InitiatorName: shortCode, SecurityCredential: password, CommandID: "BusinessPayment", Amount: amount, PartyA: shortCode, PartyB: phoneNumber, Remarks: "Payment to customer", QueueTimeOutURL: "https://example.com/timeout", ResultURL: "https://example.com/result", Occassion: "Payment", }; const response = yield axios_1.default.post(url, requestBody, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); return response.data; }); } static generatePassword(businessShortCode, passkey) { const timestamp = MdsDarajaSdk.generateTimeStamp(); const dataToEncode = `${businessShortCode}${passkey}${timestamp}`; return Buffer.from(dataToEncode).toString("base64"); } static generateTimeStamp() { const date = new Date(); const year = date.getFullYear(); const month = `0${date.getMonth() + 1}`.slice(-2); const day = `0${date.getDate()}`.slice(-2); const hours = `0${date.getHours()}`.slice(-2); const minutes = `0${date.getMinutes()}`.slice(-2); const seconds = `0${date.getSeconds()}`.slice(-2); return `${year}${month}${day}${hours}${minutes}${seconds}`; } } exports.MdsDarajaSdk = MdsDarajaSdk;