Skip to Content
Mpesajs 1.0 is released šŸŽ‰
STK Push

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 tokens
  • 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 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:

  1. Input validation
  2. Security credential generation
  3. Token acquisition
  4. API request
  5. Response handling
  6. 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 to MPESA_BUSINESS_SHORTCODE env var)
  • passkey: The passkey for password generation (defaults to MPESA_PASSKEY env var)
  • phoneNumber: The customer’s phone number in format 251XXXXXXXXX (defaults to MPESA_PHONE_NUMBER env var)
  • callbackUrl: HTTPS URL for receiving transaction results (defaults to MPESA_CALLBACK_URL env var)
Returns

An object containing:

  • MerchantRequestID: Unique identifier for the merchant request
  • CheckoutRequestID: Unique identifier for the checkout/payment request
  • ResponseCode: Response code from M-Pesa API (0 indicates success)
  • ResponseDescription: Description of the response status
  • CustomerMessage: 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:

VariableDescriptionDefault
MPESA_SANDBOXUse sandbox environmentā€trueā€
MPESA_BUSINESS_SHORTCODEBusiness shortcode-
MPESA_PASSKEYPasskey for security credential-
MPESA_PHONE_NUMBERDefault customer phone number-
MPESA_CALLBACK_URLResults notification URL-

Best Practices

  1. Validation: Always validate phone numbers and amounts before sending
  2. Error Handling: Implement comprehensive error handling for all requests
  3. URLs: Use HTTPS URLs for callbacks
  4. Testing: Use sandbox environment for development and testing
  5. User Experience: Provide clear transaction descriptions to customers
  6. 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
Last updated on