Logo Lanfrica

ADAMSmugwe/mpesa-API-wrapper-for-node.js

Domaine:

digital infrastructure

Type de record:

software
Créateur:
ADA
Hôte:
MPesa SDK is a comprehensive, developer-friendly Node.js library for integrating Safaricom's MPesa Daraja API into your applications. Built with TypeScript and designed for production use, it provides a clean, intuitive interface for all MPesa payment operations. # mpesa-sdk-js A type-safe Node.js client for Safaricom Daraja API. This library handles OAuth2 token lifecycles, request retries with exponential backoff, and provides middleware for parsing nested callback data. Quick Start • Callback Handling • Error Handling • Configuration --- ## Installation ```bash npm install adams-mpesa-sdk ``` ## Quick Start ### Initialization ```typescript import Mpesa from 'adams-mpesa-sdk'; const mpesa = new Mpesa({ consumerKey: process.env.MPESA_CONSUMER_KEY, consumerSecret: process.env.MPESA_CONSUMER_SECRET, shortcode: process.env.MPESA_SHORTCODE, passkey: process.env.MPESA_PASSKEY, environment: 'sandbox' // or 'production' }); ``` ### STK Push (Lipa Na M-Pesa Online) ```typescript const response = await mpesa.stkPush({ amount: 100, phone: '0712345678', // Automatically normalized to 254712345678 accountReference: 'REF-001', transactionDesc: 'Order Payment', callbackUrl: 'api.example.com' }); console.log(response.CheckoutRequestID); ``` --- ## Callback Handling The SDK includes Express middleware to flatten the standard MPesa response body into a usable object. ```typescript import { mpesaCallbackMiddleware, MpesaRequest } from 'adams-mpesa-sdk'; app.post('/hooks/mpesa', mpesaCallbackMiddleware(), (req: MpesaRequest, res) => { const { mpesa } = req; if (mpesa?.ResultCode === 0) { // Access flattened metadata directly const { Amount, MpesaReceiptNumber, PhoneNumber } = mpesa.metadata; // Process successful transaction logic here } res.status(200).json({ ResultCode: 0, ResultDesc: 'Accepted' }); }); ``` --- ## Error Handling The library exports custom error classes for granular catching. ```typescript try { await mpesa.stkPush({...}); } catch (error) { if (error instanceof MpesaAuthError) { // Issues with Consumer Key/Secret or Daraja availability } else if (error instanceof InvalidPhoneNumberError) { // Phone format failed pre-request validation } else if (error instanceof MpesaResponseError) …