Payout
The payout module provides functionality to handle Business-to-Customer (B2C) payments through the M-Pesa API. This documentation covers the Payout class and its methods for managing payment disbursements.
Payout Class
The Payout class is responsible for handling B2C payments, allowing businesses to send money to customer phone numbers through M-Pesa.
Constructor
Creates a new instance of the Payout class. The parameters can be automatically populated from environment variables when using the CLI tool for initialization.
Parameters:
auth: Instance of Auth class for token generationinitiatorName: Name of the initiator making the request. Defaults toMPESA_INITIATOR_NAMEenvironment variable.securityCredential: Encrypted security credential. Defaults toMPESA_SECURITY_CREDENTIALenvironment variable.sandbox: Boolean flag to determine the environment. Defaults toMPESA_SANDBOXenvironment variable.
Example
// When project is initialized using CLI, environment variables are automatically used
const auth = new Auth();
const payout = new Payout(
auth,
process.env.MPESA_INITIATOR_NAME,
process.env.MPESA_SECURITY_CREDENTIAL,
process.env.MPESA_SANDBOX === 'true'
);
// Direct initialization with credentials
const payout = new Payout(
auth,
'your-initiator-name',
'your-security-credential',
true // true for sandbox, false for production
);Methods
send()
public async send(
amount: number,
remarks: string,
occasion?: string,
commandId?: 'BusinessPayment' | 'SalaryPayment' | 'PromotionPayment',
shortCode?: string,
phoneNumber?: string,
queueTimeoutUrl?: string,
resultUrl?: string
): Promise<PayoutResponse>Sends a B2C payment to a customerâs phone number. This method handles:
- Input validation
- Token generation
- Payload construction
- API request
- Response handling
- Rate limiting
Parameters
amount: Amount to be sent (required)remarks: Comments about the transaction (required)occasion: Optional comments about the transaction (defaults to âPayoutâ)commandId: Type of B2C payment (defaults toMPESA_PAYOUT_COMMAND_IDenv var)shortCode: Organizationâs shortcode (defaults toMPESA_BUSINESS_SHORTCODEenv var)phoneNumber: Recipientâs phone number (defaults toMPESA_PHONE_NUMBERenv var)queueTimeoutUrl: Timeout URL for failed requests (defaults toMPESA_QUEUE_TIMEOUT_URLenv var)resultUrl: URL for receiving results (defaults toMPESA_RESULT_URLenv var)
Returns
An object containing:
ConversationID: Unique identifier for tracking the transactionOriginatorConversationID: The unique request identifier from your systemResponseCode: Response code from M-PesaResponseDescription: Description of the response status
Example
try {
const payout = new Payout(auth);
const result = await payout.send(
1000, // amount
'Salary payment', // remarks
'December Salary', // occasion
'SalaryPayment', // commandId
'123456', // shortCode
'251912345678', // phoneNumber
'https://example.com/timeout',
'https://example.com/result'
);
console.log('Payment sent:', result);
} catch (error) {
console.error('Payment failed:', error.message);
}Error Handling
The payout module includes comprehensive error handling:
ValidationError
Thrown for invalid input parameters:
- Invalid phone numbers
- Non-HTTPS URLs
- Invalid amounts
PayoutError
Specific to payout operation failures:
- API response errors
- Transaction processing issues
- System errors
Example Error Handling
try {
const result = await payout.send(1000, 'Test payment');
console.log('Success:', result);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else if (error instanceof PayoutError) {
console.error('Payout failed:', error.message);
} else {
console.error('Unexpected error:', error.message);
}
}Rate Limiting
The payout module includes built-in rate limiting through the RateLimiter class to prevent:
- Excessive API calls
- Account blocking
- Service throttling
Environment Variables
The Payout module uses these environment variables:
| Variable | Description | Default |
|---|---|---|
MPESA_INITIATOR_NAME | Name of the initiator | - |
MPESA_SECURITY_CREDENTIAL | Encrypted credential | - |
MPESA_SANDBOX | Use sandbox environment | âtrueâ |
MPESA_PAYOUT_COMMAND_ID | Type of payout | - |
MPESA_BUSINESS_SHORTCODE | Business shortcode | - |
MPESA_PHONE_NUMBER | Default recipient number | - |
MPESA_QUEUE_TIMEOUT_URL | Timeout notification URL | - |
MPESA_RESULT_URL | Result notification URL | - |
Best Practices
- Validation: Always validate phone numbers and amounts before sending
- Error Handling: Implement comprehensive error handling
- URLs: Use HTTPS URLs for callbacks
- Testing: Use sandbox environment for testing
- Security: Keep credentials secure using environment variables
API Endpoints
The module uses these endpoints based on environment:
- Sandbox:
https://apisandbox.safaricom.et/mpesa/b2c/v2/paymentrequest - Production:
https://api.safaricom.et/mpesa/b2c/v2/paymentrequest