Before you start: get an API key
- Create a free JMSURF SMS workspace at jmsurfsms.co.ke and confirm your email.
- Open Developers, then API keys, and create a test key (starts with jms_test_). Test keys behave like live keys but never deliver or charge; messages are recorded with the status sandbox.
- When your code works, create a live key (jms_live_) with only the scopes you need, for example sms:send and sms:read, and top up your wallet with M-Pesa.
- Store the key in an environment variable such as JMSURF_API_KEY. Never put it in front-end code or a public repository.
The request in brief
- POST https://jmsurfsms.co.ke/api/v1/sms/send with header Authorization: Bearer <your key> and a JSON body.
- to: the phone number, local (07XXXXXXXX or 01XXXXXXXX) or international (+2547XXXXXXXX).
- message: the text, up to 1,600 characters. 160 plain characters = 1 SMS.
- reference: a UUID you generate. Sending again with the same reference never sends twice, so retries are safe.
- sender_id (optional): your approved sender ID; omit it to use your default sender.
- type (optional): "transactional" for OTPs, receipts and alerts that must reach people who opted out of marketing; "marketing" otherwise.
A successful request returns 202 Accepted with the message id, status queued, number of SMS parts, encoding and cost_kes. A message the network refuses immediately returns 422 with status failed and is refunded. Errors return { "error": { "code": "...", "message": "..." } }.
Send one SMS
import { randomUUID } from "node:crypto";
export async function sendSms(to, message, reference = randomUUID()) {
const res = await fetch("https://jmsurfsms.co.ke/api/v1/sms/send", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.JMSURF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ to, message, reference, type: "transactional" }),
signal: AbortSignal.timeout(30_000),
});
const body = await res.json();
if (!res.ok && res.status !== 422) {
throw new Error(`${res.status} ${body.error?.code}: ${body.error?.message}`);
}
return body; // { id, reference, to, status, segments, encoding, cost_kes, sender_id, test }
}
const sms = await sendSms("07XXXXXXXX", "Your order #1024 is out for delivery.");
console.log(sms.id, sms.status, sms.cost_kes);Retry safely
Save the reference with your own record before calling the API. If the request times out or you get a 429 or 503, call again with the same reference: JMSURF SMS returns the original message instead of sending a second one. A reference reused for a different message returns 409 reference_conflict.
async function sendWithRetry(to, message, reference, attempts = 3) {
for (let i = 1; ; i++) {
try {
return await sendSms(to, message, reference);
} catch (error) {
if (i >= attempts || !/^(429|503|5\d\d)/.test(error.message)) throw error;
await new Promise((r) => setTimeout(r, 60_000)); // Retry-After is 60 s
}
}
}Bulk campaign
const res = await fetch("https://jmsurfsms.co.ke/api/v1/sms/bulk", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.JMSURF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Weekend offer",
message: "Hi {first_name|there}, 10% off this weekend: {link}",
recipients: customers.map((c) => ({ phone: c.phone, name: c.name, fields: { link: c.link } })),
shorten_links: true,
}),
});
const campaign = await res.json();
// 202: { campaign_id, recipients, skipped: { duplicates, invalid, blocked, unsupported_destination }, estimated_cost_kes, send_at, test }Follow progress with GET /api/v1/campaigns/{id}, which returns recipients, pending, accepted, delivered, failed and cost so far.
Express webhook for delivery reports and replies
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
const app = express();
app.post("/jmsurf/webhook", express.raw({ type: "application/json" }), (req, res) => {
const expected = "sha256=" + createHmac("sha256", process.env.JMSURF_WEBHOOK_SECRET)
.update(req.body).digest("hex");
const given = req.get("x-jmsurf-signature") ?? "";
if (given.length !== expected.length || !timingSafeEqual(Buffer.from(given), Buffer.from(expected))) {
return res.sendStatus(401);
}
const { id, event, data } = JSON.parse(req.body.toString("utf8"));
// de-duplicate on id (also sent as x-jmsurf-event-id), then handle:
if (event === "sms.delivered") markDelivered(data.reference);
if (event === "sms.inbound") saveReply(data.from, data.message);
res.sendStatus(200);
});
app.listen(3000);Errors to handle
| HTTP | error.code | What to do |
|---|---|---|
| 400 | invalid_request / invalid_recipient | Fix the body or phone number; do not retry unchanged |
| 401 | unauthorized / invalid_key | Check the key and the Bearer header |
| 402 | insufficient_credit | Top up the wallet |
| 403 | insufficient_scope / ip_not_allowed | Add the scope or allow your server's IP on the key |
| 409 | reference_conflict | The reference was used for a different message; generate a new one |
| 422 | recipient_blocked / sender_not_approved | The message cannot be sent as requested |
| 429 | rate_limited | Wait 60 seconds (Retry-After header) and retry with the same reference |
| 503 | provider_credit / sending_paused | Hold the message and retry later with the same reference |
Start sending today
Create a free workspace, top up with M-Pesa and send your first message at KES 0.40 per SMS. Questions first? Call or WhatsApp +254 712 504 593 or email [email protected].
Related pages
- API referenceEvery endpoint, request and response of the REST API.
- SMS webhooksReceive SMS delivery reports (DLR), inbound replies and payment events as signed webhooks from JMSURF SMS. Event list, payloads, signature check and retries.
- OTP SMS APISend one-time passwords and verification codes by SMS in Kenya with the JMSURF SMS API: transactional type, safe retries, rate limits and security tips.
- SMS API in PHPSend SMS from PHP with the JMSURF SMS REST API: cURL example for single and bulk SMS, idempotent references, error handling and webhook signature checks.