Developer guide

How to send SMS from PHP with the JMSURF SMS API

This guide shows working PHP code for sending one SMS, sending a bulk campaign and receiving delivery reports, using plain cURL so it runs on any PHP 7.4+ host, including shared hosting.

Before you start: get an API key

  1. Create a free JMSURF SMS workspace at jmsurfsms.co.ke and confirm your email.
  2. 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.
  3. 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.
  4. 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 with cURL

send.php
<?php
function uuid4(): string {
    $b = random_bytes(16);
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}

function jmsurf_send(string $to, string $message, ?string $reference = null): array {
    $payload = [
        'to'        => $to,
        'message'   => $message,
        'reference' => $reference ?? uuid4(), // store it to retry safely
        'type'      => 'transactional',
    ];
    $ch = curl_init('https://jmsurfsms.co.ke/api/v1/sms/send');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('JMSURF_API_KEY'),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload),
    ]);
    $body   = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['status' => $status, 'body' => json_decode((string) $body, true)];
}

$result = jmsurf_send('07XXXXXXXX', 'Your order #1024 is ready for collection.');
if ($result['status'] === 202) {
    echo 'Queued: ' . $result['body']['id'] . ', cost KES ' . $result['body']['cost_kes'];
} else {
    echo 'Error ' . $result['status'] . ': ' . ($result['body']['error']['message'] ?? 'unknown');
}
202 Accepted
{
  "id": "2b0d7c1e-…",
  "reference": "8f6241c0-24df-4ce2-b39b-9ef85eab198f",
  "to": "+2547XXXXXXXX",
  "status": "queued",
  "segments": 1,
  "encoding": "GSM-7",
  "cost_kes": 0.4,
  "sender_id": "JMSURF",
  "test": false
}

Send a personalised bulk campaign

For many recipients, use POST /api/v1/sms/bulk (scope campaigns:write) instead of a loop. One request queues up to 100,000 recipients, removes duplicates and opted-out numbers, and returns at once with a campaign id.

bulk.php
<?php
$payload = [
    'name'       => 'Fee reminders',
    'message'    => 'Dear {first_name|Parent}, the balance for {learner} is KES {balance}.',
    'recipients' => [
        ['phone' => '07XXXXXXXX', 'name' => 'Parent name', 'fields' => ['learner' => 'Learner name', 'balance' => '4,500']],
        ['phone' => '07XXXXXXXX', 'fields' => ['learner' => 'Learner name', 'balance' => '1,200']],
    ],
    // 'send_at' => '2026-12-01T09:00:00+03:00', // optional schedule
];
$ch = curl_init('https://jmsurfsms.co.ke/api/v1/sms/bulk');
curl_setopt_array($ch, [
    CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('JMSURF_API_KEY'), 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);
$res = json_decode(curl_exec($ch), true);
// { "campaign_id": "…", "recipients": 2, "skipped": {…}, "estimated_cost_kes": 0.8, … }
echo $res['campaign_id'] ?? json_encode($res);

Receive delivery reports in PHP

Add your HTTPS URL under Developers, then Webhooks, and copy the endpoint secret. Each event is a POST with a JSON body and an x-jmsurf-signature header. Check the signature over the raw body before trusting it.

webhook.php
<?php
$raw       = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_JMSURF_SIGNATURE'] ?? '';
$expected  = 'sha256=' . hash_hmac('sha256', $raw, getenv('JMSURF_WEBHOOK_SECRET'));
if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}
$event = json_decode($raw, true);
// $event['event'] is sms.queued, sms.delivered, sms.failed, sms.unknown, sms.inbound or payment.completed
if ($event['event'] === 'sms.delivered') {
    $reference = $event['data']['reference']; // the UUID you sent
    // mark your record as delivered
}
http_response_code(200);

Errors to handle

HTTPerror.codeWhat to do
400invalid_request / invalid_recipientFix the body or phone number; do not retry unchanged
401unauthorized / invalid_keyCheck the key and the Bearer header
402insufficient_creditTop up the wallet
403insufficient_scope / ip_not_allowedAdd the scope or allow your server's IP on the key
409reference_conflictThe reference was used for a different message; generate a new one
422recipient_blocked / sender_not_approvedThe message cannot be sent as requested
429rate_limitedWait 60 seconds (Retry-After header) and retry with the same reference
503provider_credit / sending_pausedHold the message and retry later with the same reference

Checking your balance

GET /api/v1/balance (scope balance:read) returns balance_kes, rate_kes_per_sms and sms_remaining, which is handy for a low-credit warning in your own admin panel.

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].

Make every message count.

Start with a free workspace. Add your audience, top up with M-Pesa and keep your customers in the conversation.

Create your workspace