Installation
Prerequisites
- Node.js ≥ 18, Bun, or Deno — the SDK uses the native
fetchandcryptoAPIs - A Safaricom Daraja account (the sandbox is free and instant to register)
ESM only pesafy is a pure ESM package. Your project must either set
"type": "module" in package.json, or use .mjs / .mts file extensions. CommonJS (require()) is not supported. :::
Install
pnpm add pesafynpm install pesafyyarn add pesafybun add pesafyScaffold your .env
The fastest way to get a correct .env is the interactive CLI wizard:
npx pesafy initIt walks you through every required variable and writes the file. Then validate the result:
npx pesafy doctorEnvironment Variables Reference
Here is the full .env template with every variable explained:
# .env
# ── Required for ALL APIs ────────────────────────────────────────────────────
MPESA_ENVIRONMENT=sandbox # sandbox | production
MPESA_CONSUMER_KEY=your_key # Daraja app consumer key
MPESA_CONSUMER_SECRET=your_secret # Daraja app consumer secret
# ── STK Push / M-PESA Express ───────────────────────────────────────────────
# Required for: mpesa.stkPush() and mpesa.stkQuery()
MPESA_SHORTCODE=174379
MPESA_PASSKEY=bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919
MPESA_CALLBACK_URL=https://yourdomain.com/api/mpesa/callback
# ── Initiator credentials ────────────────────────────────────────────────────
# Required for: Account Balance, B2C, B2B Pay Bill/Buy Goods, Reversal,
# Transaction Status, Tax Remittance
MPESA_INITIATOR_NAME=testapi
MPESA_INITIATOR_PASSWORD=Safaricom999!
MPESA_CERTIFICATE_PATH=./SandboxCertificate.cer
# ── Async result endpoints ───────────────────────────────────────────────────
# Required for: Account Balance, Reversal, Transaction Status, B2C, Tax
MPESA_RESULT_URL=https://yourdomain.com/api/mpesa/result
MPESA_QUEUE_TIMEOUT_URL=https://yourdomain.com/api/mpesa/timeout2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Download the Daraja Certificate
Initiator-based APIs (Account Balance, B2C, B2B, Reversal, Tax Remittance, Transaction Status) require a certificate to encrypt the initiator password. Download it from the Daraja portal:
- Log in to developer.safaricom.co.ke
- Go to Tools → Download Sandbox Certificate
- Save as
SandboxCertificate.cerin your project root
Production certificate In production, download the **Production
Certificate** instead — the sandbox certificate will not work in a production environment. :::
Verify your setup
npx pesafy doctorExpected output:
✔ MPESA_CONSUMER_KEY
✔ MPESA_CONSUMER_SECRET
✔ MPESA_ENVIRONMENT
✔ MPESA_SHORTCODE
✔ MPESA_PASSKEY
✔ MPESA_CALLBACK_URL
✔ MPESA_INITIATOR_NAME
✔ MPESA_INITIATOR_PASSWORD
✔ MPESA_CERTIFICATE_PATH (/absolute/path/SandboxCertificate.cer)
✔ MPESA_RESULT_URL
✔ MPESA_QUEUE_TIMEOUT_URL
✔ All checks passed! Your config looks good.2
3
4
5
6
7
8
9
10
11
12
13