M-Pesa STK push in Node.js

JMSURF PAY guide · updated 23 November 2026

This guide adds M-Pesa STK push to a Node.js app with Express: one route sends the prompt, one route receives the signed webhook, and a small helper checks the status while the customer waits. The same calls work from Next.js API routes, NestJS, Fastify or serverless functions, because they are plain HTTPS requests with fetch.

Set up

  • Create a free account at app.jmsurfpay.co.ke and confirm your email. Copy the test secret key from API & keys, Test mode.
  • Add your till, paybill or bank under Payment channels and copy the channel code (tnnt_…).
  • Add a webhook under Developers, Webhooks pointing at https://your-domain/webhooks/jmsurfpay and copy its secret.
  • Put the three values in environment variables. Node.js 18 or newer has fetch built in; nothing else is needed for the API calls.

The whole integration

Node.js + Express

// server.mjs: Node.js 18+ and Express. npm install express
import crypto from "node:crypto";
import express from "express";

const API = "https://jmsurfpay.co.ke/api";
const SECRET_KEY = process.env.JMSURFPAY_SECRET_KEY;        // sk_test_... or sk_...
const CHANNEL = process.env.JMSURFPAY_CHANNEL_CODE;          // tnnt_...
const WEBHOOK_SECRET = process.env.JMSURFPAY_WEBHOOK_SECRET; // whsec_...

const app = express();

// 1) Your checkout calls this: send the M-Pesa prompt.
app.post("/checkout/mpesa", express.json(), async (req, res) => {
  const { orderId, phone, amount } = req.body;
  const r = await fetch(API + "/payments/stkpush", {
    method: "POST",
    headers: {
      "X-API-Key": SECRET_KEY,
      "Content-Type": "application/json",
      "Idempotency-Key": "order-" + orderId,
    },
    body: JSON.stringify({
      tenantCode: CHANNEL,
      phoneNumber: phone,                 // 07..., 2547... or +2547...
      amount: Math.round(Number(amount)),  // whole shillings
      accountReference: "ORD" + orderId,
      transactionDesc: "Order " + orderId,
    }),
  });
  const data = await r.json();
  if (!r.ok) return res.status(r.status).json({ message: data.message });
  await saveCheckout(orderId, data.checkoutRequestId);
  res.json({ checkoutRequestId: data.checkoutRequestId });
});

// 2) JMSURF PAY calls this. Read the RAW body: the signature covers the exact bytes.
app.post("/webhooks/jmsurfpay", express.raw({ type: "application/json" }), async (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", WEBHOOK_SECRET).update(req.body).digest("hex");
  const got = String(req.get("X-Webhook-Signature") || "");
  if (got.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.status(401).end();
  }
  const event = JSON.parse(req.body.toString("utf8"));
  res.status(200).end(); // answer first, work after: deliveries time out after 8 s

  if (await seenBefore(event.id)) return;           // retries reuse the same id
  if (event.event === "payment.completed" && event.livemode) {
    await markPaid(event.data.checkoutRequestId, event.data.mpesaReceiptNumber);
  } else if (event.event === "payment.failed" || event.event === "payment.cancelled") {
    await markUnpaid(event.data.checkoutRequestId);
  }
});

app.listen(3000);

Why the raw body matters

The signature is an HMAC-SHA256 of the exact bytes JMSURF PAY sent. If express.json() parses the body first and you sign JSON.stringify(req.body) again, spacing or key order can differ and the check fails. Use express.raw() on the webhook route only, as above.

What you get back

POST /api/payments/stkpush, 200

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

Webhook body (payment.completed)

{
  "id": "whd_1234",
  "event": "payment.completed",
  "livemode": true,
  "timestamp": "2026-11-23T08:30:12.000Z",
  "data": {
    "id": 42,
    "checkoutRequestId": "ws_CO_...",
    "status": "completed",
    "amount": "1500.00",
    "phoneNumber": "2547XXXXXXXX",
    "mpesaReceiptNumber": "TKN1XXXXXX",
    "accountReference": "INV1001",
    "createdAt": "2026-11-23T08:29:50.000Z",
    "source": "api",
    "channelId": 7,
    "paymentLinkId": null,
    "idempotencyKey": "invoice-1001",
    "livemode": true
  }
}

Status while the customer waits

Status helper

// Ask for the result while the customer waits (every 3-5 s, up to ~60 s).
async function waitForResult(checkoutRequestId) {
  for (let i = 0; i < 15; i++) {
    const r = await fetch("https://jmsurfpay.co.ke/api/payments/status/" + encodeURIComponent(checkoutRequestId), {
      headers: { "X-API-Key": process.env.JMSURFPAY_SECRET_KEY },
    });
    const s = await r.json();
    if (s.status !== "pending") return s; // completed | failed | cancelled
    await new Promise((ok) => setTimeout(ok, 4000));
  }
  return { status: "pending" };            // the webhook will still tell you
}

Statuses are pending, completed, failed and cancelled. A failed answer has customerMessage, one short sentence you can show the payer as it is, and unreachable: true when the prompt never reached the phone (phone off, no network, SIM toolkit not updated).

Other ways to send the key

Besides X-API-Key, the API accepts Authorization: Bearer sk_… and HTTP Basic. Use whichever your HTTP client makes easiest.

Basic auth

// HTTP Basic works too: public key as user name, secret key as password.
const auth = "Basic " + Buffer.from(process.env.JMSURFPAY_PUBLIC_KEY + ":" + process.env.JMSURFPAY_SECRET_KEY).toString("base64");
await fetch("https://jmsurfpay.co.ke/api/payments/stkpush", { method: "POST", headers: { Authorization: auth, "Content-Type": "application/json" }, body });

Errors

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.

Tip

Send the same Idempotency-Key when you retry after a network error. JMSURF PAY answers with the first prompt instead of sending another one, and it never sends a second prompt for the same number and amount while the first is still on the phone.

Next: verify webhook signatures in any language, or read the full API documentation.

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