# 💰 M-Pesa Node.js Integration Class
A complete, single-class solution for integrating Safaricom M-Pesa APIs into your Node.js applications. Supports all major transaction types with minimal setup.
```bash
npm install axios
```
# 🔐 Environment Variables Setup
Create a .env file with these credentials:
```env
# REQUIRED CREDENTIALS
MPESA_SHORT_CODE=YOUR_BUSINESS_SHORT_CODE
MPESA_CONSUMER_KEY=YOUR_APP_CONSUMER_KEY
MPESA_CONSUMER_SECRET=YOUR_APP_CONSUMER_SECRET
MPESA_PASS_KEY=YOUR_LIPA_NA_MPESA_PASSKEY
MPESA_INITIATOR=YOUR_INITIATOR_NAME
MPESA_SECURITY_CREDENTIALS=ENCRYPTED_CREDENTIALS
# API ENDPOINTS (Sandbox)
MPESA_AUTH_URL=
sandbox.safaricom.co.ke
MPESA_STK_PUSH_URL=
sandbox.safaricom.co.ke
MPESA_B2C_REQUEST_URL=
sandbox.safaricom.co.ke
MPESA_ACCOUNT_BAL_URL=
sandbox.safaricom.co.ke
MPESA_REVERSAL_URL=
sandbox.safaricom.co.ke
```
# 🚀 Initialization
```js
const Mpesa = require("./mpesa.js");
const mpesa = new Mpesa();
```
# 💸 1. STK Push (Customer to Business)
Collect payments from customers
```js
try {
const response = await mpesa.initiateStkPush({
amount: 10, // KES
phone: "254722000000", // Format: 2547XXXXXXXX
callbackUrl: "
your-domain.com",
accountReference: "#Invoice12348",
transactionDesc: "Payment for order #12348",
});
console.log("STK Push Response:", response);
} catch (err) {
console.error("STK Error:", err.message);
}
```
# 💳 2. B2C Payments (Business to Customer)
Send money to customers or employees
```js
try {
const result = await mpesa.sendB2CPayment({
amount: 20,
phone: "254745137129",
remarks: "Refund for order #45679",
transactionDesc: "Withdraw earnings",
queueTimeOutURL: "
your-domain.com",
resultURL: "
your-domain.com", …