M-Pesa STK push in PHP and Laravel

JMSURF PAY guide · updated 23 November 2026

This guide shows how to take M-Pesa payments from a PHP website or app: send an STK push prompt to the customer's phone, receive the result on a webhook, and check the status if you need to. It works with plain PHP and with frameworks such as Laravel. The money goes straight from the customer's M-Pesa to your own till, paybill or bank account; JMSURF PAY sends the request and tells your system what happened.

Before you start

  1. 1Create a free account. Sign up at app.jmsurfpay.co.ke and confirm your email. Your test key is ready at once under API & keys, Test mode.
  2. 2Add a payment channel. Under Payment channels add the till, paybill or bank account the money should go to, and copy its code (it starts with tnnt_).
  3. 3Keep keys on the server. Put the secret key in an environment variable such as JMSURFPAY_SECRET_KEY. Never put it in JavaScript that runs in the browser or in a mobile app.

With a test key nothing reaches M-Pesa: amounts 2, 3 and 4 simulate a wrong PIN, a cancel and no response, and any other amount is paid. See test mode.

Send the STK push prompt

One POST to /api/payments/stkpush sends the prompt. The four fields phoneNumber, amount, accountReference and transactionDesc are required. Add tenantCode when you have more than one payment channel. The Idempotency-Key header makes retries safe: the same key returns the first answer and never sends a second prompt.

PHP with cURL

<?php
// stk.php: send an M-Pesa prompt with JMSURF PAY (PHP 7.4+ with the cURL extension)
$secretKey   = getenv('JMSURFPAY_SECRET_KEY');   // sk_test_... while testing, sk_... when live
$channelCode = getenv('JMSURFPAY_CHANNEL_CODE'); // tnnt_... from Payment channels

$payload = [
    'tenantCode'       => $channelCode,
    'phoneNumber'      => '2547XXXXXXXX',  // 07..., +254... and 254... are all accepted
    'amount'           => 1500,            // whole shillings
    'accountReference' => 'INV1001',
    'transactionDesc'  => 'Invoice 1001',
];

$ch = curl_init('https://jmsurfpay.co.ke/api/payments/stkpush');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'X-API-Key: ' . $secretKey,
        'Content-Type: application/json',
        'Idempotency-Key: invoice-1001',   // a retry never sends a second prompt
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload),
]);
$body   = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($body, true);
if ($status >= 400) {
    // e.g. ['error' => 'VALIDATION_ERROR', 'message' => '...']
    http_response_code(400);
    exit($data['message'] ?? 'Payment request failed');
}
// Save this with the order: the webhook and the status check use it.
$checkoutRequestId = $data['checkoutRequestId'];

A successful answer looks like this. Keep checkoutRequestId: it links the prompt to the webhook and to the status check.

Response (200)

{
  "checkoutRequestId": "ws_CO_...",
  "merchantRequestId": "...",
  "responseCode": "0",
  "responseDescription": "Success. Request accepted for processing",
  "customerMessage": "Success. Request accepted for processing",
  "transactionId": 42,
  "livemode": true
}

Receive the result on a webhook

In the dashboard open Developers, Webhooks, add your HTTPS address and copy the webhook secret (whsec_…). Every delivery carries an X-Webhook-Signature header: sha256= followed by the HMAC-SHA256 of the raw body with your secret. Check it before you trust the body.

PHP webhook receiver

<?php
// webhook.php: receives payment.completed / payment.failed / payment.cancelled
$secret    = getenv('JMSURFPAY_WEBHOOK_SECRET');      // whsec_... from Developers, Webhooks
$raw       = file_get_contents('php://input');         // the raw body, before json_decode
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$expected  = 'sha256=' . hash_hmac('sha256', $raw, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit('bad signature');
}

$event = json_decode($raw, true);
// The same id arrives again on a retry: store it and skip it the second time.
if (alreadyProcessed($event['id'])) { http_response_code(200); exit; }

if ($event['event'] === 'payment.completed' && $event['livemode'] === true) {
    $p = $event['data'];
    markOrderPaid($p['accountReference'], $p['mpesaReceiptNumber'], $p['amount']);
}
rememberProcessed($event['id']);
http_response_code(200);   // answer fast: slow answers are retried
  • Answer with any 2xx code within 8 seconds. Other answers and timeouts are retried after 1 minute, 5 minutes, 30 minutes and 2 hours (5 attempts in all).
  • Each delivery has an id (also in the X-Webhook-Id header) that stays the same on retries. Store it to ignore duplicates.
  • Payments made with a test key arrive with "livemode": false. Never ship goods for those.

Check the status (optional)

Webhooks are the reliable way to learn the result. If your page wants to show the result while the customer waits, ask for the status every 3 to 5 seconds for up to a minute.

PHP status check

<?php
$ch = curl_init('https://jmsurfpay.co.ke/api/payments/status/' . urlencode($checkoutRequestId));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['X-API-Key: ' . getenv('JMSURFPAY_SECRET_KEY')],
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);

switch ($data['status']) {          // pending | completed | failed | cancelled
    case 'completed': markOrderPaid($data['mpesaReceiptNumber']); break;
    case 'failed':
    case 'cancelled': showMessage($data['customerMessage']); break;
    default:          /* still on the phone: check again in a few seconds */ break;
}

Laravel version

The same two calls with Laravel's HTTP client. Remember to leave the webhook route out of CSRF protection, because JMSURF PAY, not a browser, calls it.

Laravel

// routes/api.php (Laravel): exclude this route from CSRF, it is called by JMSURF PAY
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

Route::post('/pay/mpesa', function (Request $request) {
    $res = Http::withHeaders([
        'X-API-Key'       => config('services.jmsurfpay.secret'),
        'Idempotency-Key' => 'order-' . $request->order_id,
    ])->post('https://jmsurfpay.co.ke/api/payments/stkpush', [
        'tenantCode'       => config('services.jmsurfpay.channel'),
        'phoneNumber'      => $request->phone,
        'amount'           => (int) $request->amount,
        'accountReference' => 'ORD' . $request->order_id,
        'transactionDesc'  => 'Order ' . $request->order_id,
    ]);
    return $res->successful()
        ? ['checkoutRequestId' => $res['checkoutRequestId']]
        : response()->json(['message' => $res['message'] ?? 'Could not send the prompt'], 422);
});

Route::post('/webhooks/jmsurfpay', function (Request $request) {
    $expected = 'sha256=' . hash_hmac('sha256', $request->getContent(), config('services.jmsurfpay.webhook_secret'));
    abort_unless(hash_equals($expected, (string) $request->header('X-Webhook-Signature')), 401);
    // ...same handling as webhook.php above
    return response()->noContent();
});

Errors you should handle

Errors come back as JSON with error and message. Show the message to staff, and a simple sentence to the customer.

HTTPerrorWhat to do
400VALIDATION_ERRORA field is missing or wrong. phoneNumber, amount, accountReference and transactionDesc are required; the amount is a whole number from 1 to 250,000.
400CHANNEL_REQUIREDYou have more than one payment channel. Send tenantCode so the money goes to the right one.
401UnauthorizedThe secret key is missing or wrong.
402PLAN_EXPIRED / FREE_LIMIT_REACHEDThe plan has ended or the Free plan's monthly limit is used. The answer carries a renewUrl.
403KYC_REQUIREDA live key was used before the business is verified. Use a test key until then.
429PROMPT_LIMIT / PROMPT_PAUSEDToo many prompts to the same number (3 in 2 minutes), or recent prompts to it did not reach the phone. Wait retryAfterSeconds or use another number.
502MPESA_ERRORM-Pesa returned an error. Read the message field.

Going live

Finish Verification in the dashboard, create a live key under API & keys, Live and swap it in for the test key. Nothing else changes. Using WordPress? The WooCommerce plugin does all of this without code, and WHMCS has its own module.

Start on the Free plan: 1 payment channel, up to KES 50,000 a month, test keys included. Questions? WhatsApp +254 712 504 593.

Read next

© 2026 JMSURF PAY. All rights reserved. · ODPC reg. no. 194-9812-26EBPowered by JMSURF TECHNOLOGIES LTD