STK Push
The STK Push module provides functionality to initiate Mobile Money payment requests to customers via the Safaricom M-Pesa STK Push API. This documentation covers the StkPush
class and its methods for managing payment requests.
StkPush Class
The StkPush
class is responsible for initiating STK Push payment requests to M-Pesa customers, triggering a payment prompt on the customerās phone to securely authorize transactions.
Constructor
Creates a new instance of the StkPush class. The parameters can be automatically populated from environment variables when using the CLI tool for initialization.
Parameters:
auth
: An instance of the Auth class for generating M-Pesa API tokenssandbox
: Boolean flag to determine the environment. Defaults toMPESA_SANDBOX
environment variable.
Example
// When project is initialized using CLI, environment variables are automatically used
const auth = new Auth();
const stkPush = new StkPush(
auth,
process.env.MPESA_SANDBOX === 'true'
);
// Direct initialization
const stkPush = new StkPush(
auth,
true // true for sandbox, false for production
);
Methods
sendStkPush()
async sendStkPush(
amount: number,
transactionDesc: string,
accountReference: string,
businessShortCode?: string,
passkey?: string,
phoneNumber?: string,
callbackUrl?: string,
): Promise<StkPushResponse>
Initiates an STK Push transaction to request payment from a customer. This method handles:
- Input validation
- Security credential generation
- Token acquisition
- API request
- Response handling
- Rate limiting
Parameters
amount
: The amount to be paid (required, must be > 0)transactionDesc
: Description of the transaction (required, max 13 chars)accountReference
: Reference identifier for the transaction (required, max 12 chars)businessShortCode
: The business short code (defaults toMPESA_BUSINESS_SHORTCODE
env var)passkey
: The passkey for password generation (defaults toMPESA_PASSKEY
env var)phoneNumber
: The customerās phone number in format 251XXXXXXXXX (defaults toMPESA_PHONE_NUMBER
env var)callbackUrl
: HTTPS URL for receiving transaction results (defaults toMPESA_CALLBACK_URL
env var)
Returns
An object containing:
MerchantRequestID
: Unique identifier for the merchant requestCheckoutRequestID
: Unique identifier for the checkout/payment requestResponseCode
: Response code from M-Pesa API (0 indicates success)ResponseDescription
: Description of the response statusCustomerMessage
: Message that can be displayed to the customer
Example
try {
const auth = new Auth();
const stkPush = new StkPush(auth);
const result = await stkPush.sendStkPush(
1, // amount
"Test Payment", // transactionDesc
"TestAccount", // accountReference
"123456", // businessShortCode (optional)
"passkey123", // passkey (optional)
"251912345678", // phoneNumber (optional)
"https://example.com/callback" // callbackUrl (optional)
);
console.log('STK Push initiated:', result);
} catch (error) {
console.error('STK Push failed:', error.message);
}
Error Handling
The STK Push module includes comprehensive error handling:
ValidationError
Thrown when input parameters are invalid:
- Invalid phone number format
- Non-positive amount
- Non-HTTPS callback URL
- Exceeding character limits for descriptions or references
StkPushError
Specific to STK Push operation failures:
- API response errors
- Transaction processing issues
- Payment request failures
NetworkError
Thrown for network-related issues:
- Connection failures
- Timeout errors
- No response from API
AuthenticationError
Thrown when token generation fails:
- Invalid credentials
- API authentication failures
Example Error Handling
try {
const result = await stkPush.sendStkPush(1, "Test Payment", "TestAccount");
console.log('Success:', result);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message, 'Field:', error.field);
} else if (error instanceof StkPushError) {
console.error('STK Push failed:', error.message, 'Code:', error.responseCode);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message, 'Code:', error.errorCode);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
} else if (error instanceof MpesaError) {
console.error('General M-Pesa Error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
Rate Limiting
The STK Push module includes built-in rate limiting through the RateLimiter
class to prevent:
- Excessive payment requests
- API throttling
- Account blocking
The rate limiter automatically manages request frequency, ensuring your application stays within M-Pesaās API limits.
Environment Variables
The StkPush module uses these environment variables:
Variable | Description | Default |
---|---|---|
MPESA_SANDBOX | Use sandbox environment | ātrueā |
MPESA_BUSINESS_SHORTCODE | Business shortcode | - |
MPESA_PASSKEY | Passkey for security credential | - |
MPESA_PHONE_NUMBER | Default customer phone number | - |
MPESA_CALLBACK_URL | Results notification URL | - |
Best Practices
- Validation: Always validate phone numbers and amounts before sending
- Error Handling: Implement comprehensive error handling for all requests
- URLs: Use HTTPS URLs for callbacks
- Testing: Use sandbox environment for development and testing
- User Experience: Provide clear transaction descriptions to customers
- Security: Store passkeys securely using environment variables
API Endpoints
The module uses these endpoints based on environment:
- Sandbox:
https://apisandbox.safaricom.et/mpesa/stkpush/v1/processrequest
- Production:
https://api.safaricom.et/mpesa/stkpush/v1/processrequest