Pay Lume Pay Lume
key Get API Keys dashboard Dashboard
DEVELOPER API REFERENCE

Pay Lume REST API Engine

High-velocity Safaricom M-Pesa payment infrastructure engineered for Kenyan developers, platforms, and e-commerce applications.

The Pay Lume API enables automated Safaricom M-Pesa STK Push prompts, payment links, custom Daraja Till/Paybill routing, and cryptographically signed realtime webhooks using clean JSON HTTP requests.

bolt

Sub-250ms Latency

Optimized direct connection to Safaricom Daraja API servers with automated connection pooling.

security

Atomic Token Security

Race-condition protected token reservation engine preventing duplicate charges or leaked tokens.

hub

Direct Channel Routing

Funds settle directly into your own Paybill or Till number. Pay Lume never holds your funds.

verified_user

HMAC Signed Webhooks

SHA-256 HMAC signature headers on every event delivery for tamper-proof validation.

Production API Base URL
https://pay.lume.co.ke/api/v1
API STATUS Engine Active
{
  "system": "Pay Lume REST API",
  "version": "v1.0.0",
  "status": "OPERATIONAL",
  "supported_channels": ["STK_PUSH", "TILL", "PAYBILL"],
  "signature_algorithm": "HMAC-SHA256"
}

3-Minute Integration Quickstart

Accept M-Pesa payments in your application with these 4 simple steps:

1

Generate API Credentials

Log in to your merchant dashboard, navigate to API Keys, and click Generate Key Pair to obtain your Secret Key (sk_live_...).

2

Connect Your Payment Channel

Add your Safaricom M-Pesa Till Number (Buy Goods) or Paybill under Till & PayBill in your merchant portal to receive funds directly.

3

Maintain Service Token Balance

Ensure your account has available Service Tokens. Tokens power API STK pushes at a low, predictable flat rate (1 token per successful transaction).

4

Send HTTP POST Request

Make a POST request to /api/v1/stk/push with your Bearer secret key in the authorization header.

Quickstart Request
curl -X POST "https://pay.lume.co.ke/api/v1/stk/push" \
  -H "Authorization: Bearer sk_live_YOUR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "phone_number": "0712345678",
    "amount": 250,
    "reference": "DEMO-001",
    "description": "Store Purchase"
  }'
200 OK STK Prompt Dispatched
{
  "success": true,
  "code": "STK_INITIATED",
  "message": "STK Push initiated successfully.",
  "transaction_id": "e2a184f0-4c81-42cb-b70c-2679f04128f0",
  "checkout_request_id": "ws_CO_20102026210000192837",
  "status": "PENDING",
  "execution_time_ms": 142
}

Authentication & Security Keys

The Pay Lume API relies on Secret Key Bearer Token authentication. All requests must be performed over HTTPS with your Secret Key supplied in the HTTP Authorization header.

security

Key Security Best Practices

Never expose your Secret Key (sk_live_...) in client-side code, mobile applications, or public Git repositories. Keep keys stored securely in server environment variables. You can rotate or revoke keys anytime with zero downtime from the API Keys dashboard.

Required Request Headers

Header Value Description
Authorization Bearer sk_live_... Secret key generated under API Keys dashboard.
Content-Type application/json Required for all POST endpoints.
Accept application/json Defines expected JSON response format.
Header Format Example
Authorization: Bearer sk_live_a1b2c3d4e5f67890abcdef123456
Content-Type: application/json
Accept: application/json

Base URL & Rate Limiting

The base URL for all API resources is structured as follows:

https://pay.lume.co.ke/api/v1

Rate Limiting Policy

To maintain high availability and sub-second response times across all merchants, API endpoints are protected with automated rate limiting:

  • STK Push Requests: Up to 100 requests per second per merchant account.
  • Query Endpoints: Up to 200 requests per second per merchant account.
  • Exceeding limits triggers an HTTP 429 Too Many Requests response.
429 Rate Limit Exceeded
{
  "success": false,
  "code": "RATE_LIMIT_EXCEEDED",
  "message": "Rate limit exceeded. Maximum 100 requests per second allowed."
}

Service Token Gas Fee Engine

Pay Lume uses an atomic Service Token gas fee model to power payment execution. Service Tokens are deducted automatically when STK Push payments settle successfully.

  • Atomic Reservation: 1 token is reserved momentarily before triggering Daraja network calls to prevent race conditions or overdrafts.
  • Automatic Refund on Failure: If a customer cancels the prompt, enters the wrong PIN, or a Safaricom network error occurs, reserved tokens are released back to your balance immediately with 0 loss!
  • Zero-Token Protection: If available token balance is zero or below required tokens, the API returns HTTP 402 Payment Required.
402 Token Protection Response
{
  "success": false,
  "code": "INSUFFICIENT_TOKENS",
  "message": "Insufficient service tokens. Please purchase more service tokens."
}

Direct-to-Merchant Channel Routing

Pay Lume is a non-custodial payment gateway. Customer payments flow directly from Safaricom M-Pesa into your designated Till (Buy Goods) or Paybill number.

hub

Immediate Settlement into Your Account

You don't have to wait for manual withdrawals or hold balances with us. Once the customer enters their PIN, funds appear in your Safaricom business account in real time.

400 Channel Error Example
{
  "success": false,
  "code": "NO_PAYMENT_CHANNEL",
  "message": "No active payment channel found. Please configure an M-Pesa Till or PayBill channel in your Pay Lume dashboard before initiating STK pushes."
}
POST /api/v1/stk/push

Initiate STK Push Request

Triggers a real-time Safaricom M-Pesa STK Push prompt on the customer's phone asking them to authorize payment with their M-Pesa PIN.

Request JSON Body Parameters

Field Type Required Description
phone_number string Required Customer M-Pesa phone number (e.g. 0712345678, 0112345678, or 254712345678). Gateway normalizes automatically.
amount number Required Amount in KES (minimum KES 1.00).
reference string Required Unique order/invoice reference (max 12 alphanumeric characters).
description string Optional Short payment description (max 20 characters, default: API Payment).
curl -X POST "https://pay.lume.co.ke/api/v1/stk/push" \
  -H "Authorization: Bearer sk_live_YOUR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "phone_number": "0712345678",
    "amount": 500,
    "reference": "ORD-9912",
    "description": "Store Purchase"
  }'
const response = await fetch('https://pay.lume.co.ke/api/v1/stk/push', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk_live_YOUR_SECRET_KEY',
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: JSON.stringify({
    phone_number: '0712345678',
    amount: 500,
    reference: 'ORD-9912',
    description: 'Store Purchase'
  })
});

const data = await response.json();
console.log(data);
$ch = curl_init('https://pay.lume.co.ke/api/v1/stk/push');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer sk_live_YOUR_SECRET_KEY',
        'Content-Type: application/json',
        'Accept: application/json'
    ],
    CURLOPT_POSTFIELDS     => json_encode([
        'phone_number' => '0712345678',
        'amount'       => 500,
        'reference'    => 'ORD-9912',
        'description'  => 'Store Purchase'
    ])
]);

$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
import requests

url = "https://pay.lume.co.ke/api/v1/stk/push"
headers = {
    "Authorization": "Bearer sk_live_YOUR_SECRET_KEY",
    "Content-Type": "application/json",
    "Accept": "application/json"
}
payload = {
    "phone_number": "0712345678",
    "amount": 500,
    "reference": "ORD-9912",
    "description": "Store Purchase"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
200 OK Initiation Response
{
  "success": true,
  "code": "STK_INITIATED",
  "message": "STK Push initiated successfully.",
  "transaction_id": "a1b2c3d4-e5f6-7890-1234-56789abcdef0",
  "checkout_request_id": "ws_CO_20102026210000192837",
  "status": "PENDING",
  "execution_time_ms": 142
}
GET /api/v1/stk/query/{checkoutRequestId}

Query Transaction Status (Server-Side)

Check real-time payment status using the checkout_request_id returned during initial push. Requires Bearer API authentication.

Path Parameters

Parameter Type Required Description
checkoutRequestId string Required Safaricom checkout request ID (e.g. ws_CO_20102026210000192837).
Server Query Request
curl -X GET "https://pay.lume.co.ke/api/v1/stk/query/ws_CO_20102026210000192837" \
  -H "Authorization: Bearer sk_live_YOUR_SECRET_KEY" \
  -H "Accept: application/json"
200 OK Completed Response
{
  "success": true,
  "transaction_id": "a1b2c3d4-e5f6-7890-1234-56789abcdef0",
  "checkout_request_id": "ws_CO_20102026210000192837",
  "amount": 500.00,
  "currency": "KES",
  "phone_number": "254712345678",
  "reference": "ORD-9912",
  "status": "SUCCESS",
  "mpesa_receipt": "SJK1928472",
  "result_code": "0",
  "result_desc": "The service request has been processed successfully.",
  "execution_time_ms": 14
}
GET /api/v1/stk/status/{checkoutRequestId}

Frontend Polling Status (Client-Side)

A high-speed, lightweight polling endpoint specifically created for frontend checkout interfaces, modals, and mobile web apps. It does not require exposing your secret API key on the client side.

timer

Recommended Polling Interval

Poll every 2.5 to 3 seconds. Our server includes an intelligent debounce cache to return sub-50ms status updates while the user enters their PIN on their phone.

Frontend Polling (JavaScript)
async function pollStatus(checkoutRequestId) {
  const res = await fetch(`https://pay.lume.co.ke/api/v1/stk/status/${encodeURIComponent(checkoutRequestId)}`);
  const data = await res.json();
  
  if (data.status === 'SUCCESS') {
    console.log('Payment Successful! Receipt:', data.mpesa_receipt);
  } else if (data.status === 'PENDING') {
    setTimeout(() => pollStatus(checkoutRequestId), 2500);
  } else {
    console.log('Payment Failed or Cancelled:', data.result_desc);
  }
}

Webhooks & Event Subscriptions

Pay Lume uses webhooks to notify your backend applications asynchronously when payment events occur. Configure webhook endpoints in your Webhooks Settings.

Supported Event Types

Event Name Trigger Condition
payment.success Fired immediately when an M-Pesa payment is confirmed and cleared by Safaricom.
payment.failed Fired when customer cancels the prompt, enters wrong PIN, or request times out.
Sample Webhook JSON Payload
{
  "id": "evt_4a781b2c9e3f810d",
  "event": "payment.success",
  "created_at": "2026-10-20 21:05:00",
  "data": {
    "transaction_id": 142,
    "transaction_uuid": "a1b2c3d4-e5f6-7890-1234-56789abcdef0",
    "checkout_request_id": "ws_CO_20102026210000192837",
    "amount": "500.00",
    "currency": "KES",
    "phone_number": "254712345678",
    "reference": "ORD-9912",
    "mpesa_receipt": "SJK1928472",
    "status": "SUCCESS"
  }
}

HMAC Signature Verification

Every webhook POST request sent by Pay Lume includes an X-PayLume-Signature HTTP header. Use your endpoint's Secret Signing Key (whsec_...) to compute a SHA-256 HMAC digest of the raw request payload to verify authenticity and prevent spoofing.

Verification Steps

  1. Extract the raw HTTP request body string exactly as delivered.
  2. Compute the HMAC SHA-256 digest using your webhook endpoint's secret key.
  3. Compare the computed hash against the X-PayLume-Signature header value using a timing-safe string comparison.
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_PAYLUME_SIGNATURE'] ?? $_SERVER['HTTP_X_PAYVERA_SIGNATURE'] ?? '';
$secret = 'whsec_your_webhook_secret_here';

$expectedSignature = hash_hmac('sha256', $payload, $secret);

if (hash_equals($expectedSignature, $signature)) {
    // Signature verified - Process event
    $event = json_decode($payload, true);
    http_response_code(200);
    echo json_encode(['received' => true]);
} else {
    // Invalid signature - Reject
    http_response_code(401);
    exit('Invalid signature');
}
const crypto = require('crypto');

function verifyWebhook(req, secret) {
  const signature = req.headers['x-paylume-signature'] || req.headers['x-payvera-signature'];
  const rawBody = req.rawBody || JSON.stringify(req.body);
  
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  return crypto.timingSafeEqual(Buffer.from(signature || ''), Buffer.from(expected));
}
import hmac
import hashlib

def verify_webhook(raw_payload, signature_header, secret):
    expected = hmac.new(
        secret.encode('utf-8'),
        raw_payload.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(expected, signature_header or '')

Webhook Retry Policy

Your webhook listener must respond with an HTTP 200 OK status code within 5 seconds. If your listener returns an error (4xx/5xx) or times out, Pay Lume retries event delivery automatically with exponential backoff:

Attempt Backoff Delay
Attempt 1Immediate
Attempt 21 minute
Attempt 35 minutes
Attempt 415 minutes
Attempt 51 hour
Attempt 66 hours (Final Attempt)
update

Idempotent Webhook Processing

Always design your webhook handlers to be idempotent using transaction_id or checkout_request_id so repeated deliveries do not create duplicate order fulfillments.

Response & Error Codes Reference

Pay Lume uses standard HTTP status codes accompanied by explicit machine-readable error strings in response bodies:

Error Code HTTP Status Description
INVALID_PARAMETERS 400 Required body field missing or invalid phone number / amount format.
NO_PAYMENT_CHANNEL 400 No active M-Pesa Till or PayBill configured in merchant settings.
UNAUTHORIZED 401 Invalid, missing, or revoked API secret key supplied.
INSUFFICIENT_TOKENS 402 Account Service Token balance is empty. Purchase more tokens in dashboard.
NOT_FOUND 404 The requested transaction or payment link was not found.
RATE_LIMIT_EXCEEDED 429 Request threshold exceeded (100 req/sec limit).
DARAJA_ERROR 500 Safaricom M-Pesa gateway error or network timeout.
MAINTENANCE_MODE 503 API Gateway is undergoing scheduled maintenance. Transactions paused.
Standard Error Schema
{
  "success": false,
  "code": "INVALID_PARAMETERS",
  "message": "phone_number, amount, and reference parameters are required."
}

Language SDK Quickstarts

Ready-to-use, production-tested integration snippets for popular backend frameworks and runtimes.

<?php
class PayLumeClient {
    private $apiKey;
    private $baseUrl = 'https://pay.lume.co.ke/api/v1';

    public function __construct(string $apiKey) {
        $this->apiKey = $apiKey;
    }

    public function initiateStk(string $phone, float $amount, string $reference) {
        $ch = curl_init("{$this->baseUrl}/stk/push");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer {$this->apiKey}",
                "Content-Type: application/json"
            ],
            CURLOPT_POSTFIELDS     => json_encode([
                'phone_number' => $phone,
                'amount'       => $amount,
                'reference'    => $reference
            ])
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }
}
class PayLumeClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://pay.lume.co.ke/api/v1';
  }

  async initiateStk(phoneNumber, amount, reference) {
    const res = await fetch(`${this.baseUrl}/stk/push`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        phone_number: phoneNumber,
        amount,
        reference
      })
    });
    return await res.json();
  }
}
import requests

class PayLumeClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://pay.lume.co.ke/api/v1"

    def initiate_stk(self, phone: str, amount: float, reference: str):
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        payload = {
            "phone_number": phone,
            "amount": amount,
            "reference": reference
        }
        r = requests.post(f"{self.base_url}/stk/push", json=payload, headers=headers)
        return r.json()