Skip to Content
Mpesajs 1.0 is released 🎉
Payout initiation

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 generation
  • initiatorName: Name of the initiator making the request. Defaults to MPESA_INITIATOR_NAME environment variable.
  • securityCredential: Encrypted security credential. Defaults to MPESA_SECURITY_CREDENTIAL environment variable.
  • sandbox: Boolean flag to determine the environment. Defaults to MPESA_SANDBOX environment 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:

  1. Input validation
  2. Token generation
  3. Payload construction
  4. API request
  5. Response handling
  6. 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 to MPESA_PAYOUT_COMMAND_ID env var)
  • shortCode: Organization’s shortcode (defaults to MPESA_BUSINESS_SHORTCODE env var)
  • phoneNumber: Recipient’s phone number (defaults to MPESA_PHONE_NUMBER env var)
  • queueTimeoutUrl: Timeout URL for failed requests (defaults to MPESA_QUEUE_TIMEOUT_URL env var)
  • resultUrl: URL for receiving results (defaults to MPESA_RESULT_URL env var)
Returns

An object containing:

  • ConversationID: Unique identifier for tracking the transaction
  • OriginatorConversationID: The unique request identifier from your system
  • ResponseCode: Response code from M-Pesa
  • ResponseDescription: 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:

VariableDescriptionDefault
MPESA_INITIATOR_NAMEName of the initiator-
MPESA_SECURITY_CREDENTIALEncrypted credential-
MPESA_SANDBOXUse sandbox environment”true”
MPESA_PAYOUT_COMMAND_IDType of payout-
MPESA_BUSINESS_SHORTCODEBusiness shortcode-
MPESA_PHONE_NUMBERDefault recipient number-
MPESA_QUEUE_TIMEOUT_URLTimeout notification URL-
MPESA_RESULT_URLResult notification URL-

Best Practices

  1. Validation: Always validate phone numbers and amounts before sending
  2. Error Handling: Implement comprehensive error handling
  3. URLs: Use HTTPS URLs for callbacks
  4. Testing: Use sandbox environment for testing
  5. 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
Last updated on