Python Client
To get the IP to replace the main_url example kindly contact us.
The following methods are for python users.
main_api = "http://main_url/mspaceservice/wr/sms/"
Every API request needs an API key. Don't have an account yet? Sign up here.
Sending SMS can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/sendtext
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<sms>
<username>Your_Username</username>
<senderId>Your_Sender_Id</senderId>
<recipient>0722XXXXXX,254733XXXXXX</recipient>
<message>Your message.</message>
</sms>
https://api.mspace.co.ke/smsapi/v2/sendtext/apikey=<your_api_key>/username=your_username/senderId=your_sender_id/recipient=0722XXXXXX,254733XXXXXX/message=Your message.
The below response applies to both POST and GET requests.
To any errors encountered such as status 400, 404 etc;
Checking delivery report can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/deliveryreport
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<dlr>
<username></username>
<messageId>49032372</messageId>
</dlr>
https://api.mspace.co.ke/smsapi/v2/deliveryreport/apikey=<your_api_key>/username=/messageId=49032372
The below response applies to both POST and GET requests.
To any errors encountered such as status 400, 404 etc;
Checking SMS balance can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/balance
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<user>
<username>your_username</username>
</user>
https://api.mspace.co.ke/smsapi/v2/balance/apikey=<your_api_key>/username=your_username
The below response applies to both POST and GET requests.
The response is an integer value that shows the sms balance.
7628
To any errors encountered such as status 400, 404 etc;
Quering sub users can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/subusers
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<user>
<username>your_username</username>
</user>
https://api.mspace.co.ke/smsapi/v2/subusers/apikey=<your_api_key>/username=your_username
The below response applies to both POST and GET requests.
To any errors encountered such as status 400, 404 etc;
Quering reseller clients can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/resellerclients
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<user>
<username>your_username</username>
</user>
https://api.mspace.co.ke/smsapi/v2/resellerclients/apikey=<your_api_key>/username=your_username
The below response applies to both POST and GET requests.
To any errors encountered such as status 400, 404 etc;
Sub-Account top ups can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/subacctopup
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<subAccTopups>
<username>Your_Username</username>
<subaccname>Sub_Acc_Name</subaccname>
<noOfSms>9000</noOfSms>
</subAccTopups>
https://api.mspace.co.ke/smsapi/v2/subacctopup/apikey=<your_api_key>/username=Your_Username/subaccname=Sub_Acc_Name/noofsms=9000
The below response applies to both POST and GET requests.
The response is a plain string with a success message as below:
Successful Top up of 9000 SMS to <Sub_Acc_Name>
To any errors encountered such as status 400, 404 etc;
Reseller-Client top ups can be done by doing either a POST or a GET Request. Both methods are shown below.
Endpoint: https://api.mspace.co.ke/smsapi/v2/resellerclienttopup
Header: apikey: <Your_api_key>
If you don't have the api key check the API Overview menu and follow the procedure to generate one.
"apikey": "your_api_key"
"Content-Type": "application/json"
"Accept": "application/json"
You can also do a POST request using xml body instead of json. Below is the how to:
"apikey": "your_api_key"
"Content-Type": "application/xml"
"Accept": "application/xml"
<resellerClientTopups>
<username>Your_Username</username>
<clientname>Client_Name</clientname>
<noOfSms>1000</noOfSms>
</resellerClientTopups>
https://api.mspace.co.ke/smsapi/v2/resellerclienttopup/apikey=<your_api_key>/username=your_username/clientname=Client_Name/noofsms=1000
The below response applies to both POST and GET requests.
The response is a plain string with a success message as below:
Successful Top up of 9000 SMS to <Client_Name>
To any errors encountered such as status 400, 404 etc;
This document outlines the technical specifications for integrating with the MSpace Solutions Ltd Shortcode Webhook system. When a subscriber sends an SMS to your assigned shortcode, our gateway will automatically and instantly forward the message details to a registered HTTP webhook endpoint of your choice.
To begin receiving webhook payloads, the endpoint must be registered in the MSpace system:
| Field | Your Entry |
|---|---|
| Shortcode | |
| Keyword | |
| Sender ID (Optional) | |
| Webhook URL | |
| Auto-Response Text (Optional) |
00700).https://api.yoursite.com/webhook).When an incoming SMS matches your rule (or falls into the default catch-all rule for your shortcode), our server will immediately send a request to your Webhook URL.
POSTapplication/json; charset=UTF-8Our system pushes a flat JSON object containing the message properties:
{
"sender": "254712345678",
"shortcode": "00700",
"message": "PROMO Send me the details",
"timestamp": "2026-09-08 14:30:15.123",
"keyword": "PROMO"
}
| Field | Type | Description |
|---|---|---|
sender |
String |
The mobile phone number of the subscriber who sent the SMS, in international format. |
shortcode |
String |
The MSpace shortcode or system number the SMS was sent to. |
message |
String |
The exact, complete text body of the incoming SMS. |
timestamp |
String |
The date and time the message was received by our gateway. |
keyword |
String |
The keyword rule that triggered this webhook. If it matched the default catch-all rule, this will typically indicate a direct match. |
Your endpoint should acknowledge receipt by returning an HTTP 200 OK (or any 2XX status code) as quickly as possible. The response body is currently ignored by our system.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhooks/sms', (req, res) => {
const { sender, shortcode, message, keyword } = req.body;
console.log(`SMS from ${sender} to shortcode ${shortcode}`);
console.log(`Keyword: ${keyword} | Message: ${message}`);
// Process the SMS asynchronously here
// Quickly acknowledge receipt
res.status(200).send('Webhook received');
});
app.listen(3000, () => console.log('Listening for webhooks on port 3000'));
curl -X POST http://localhost:3000/webhooks/sms \
-H "Content-Type: application/json" \
-d '{"sender":"254712345678", "shortcode":"00700", "message":"TEST", "timestamp":"2026-09-08 14:30:15", "keyword":"TEST"}'
| Issue / Error | Cause & Solution |
|---|---|
| Timeout Errors | If your server takes longer than 5 seconds to respond, MSpace will drop the connection. Ensure your endpoint responds with a 200 OK immediately and handles long-running processes asynchronously. |
| HTTP 4xx / 5xx Errors | If your server returns an error code (e.g., 404 Not Found, 500 Internal Server Error), the webhook will fail. Check your application logs to ensure the route exists and does not throw exceptions. |
| Firewall / Access Blocks | Ensure that your server is publicly accessible from the internet and is not blocking incoming HTTP POST requests. Check your firewall, proxy, or Cloudflare settings if payloads are not arriving. |
| Invalid JSON Parsing | If your server does not explicitly accept the application/json Content-Type, the payload body might appear empty in your code. Ensure you have the correct JSON body parser middleware enabled. |
Send single and bulk WhatsApp messages, track delivery and campaign progress, list approved templates, check wallet credits, and receive signed webhooks.
Every /api/v2/** request requires an active WhatsApp-enabled account and API key. Generate or rotate your key in the
WhatsApp Portal under API Docs.
Content-Type: application/json X-Username: YOUR_USERNAME X-API-Key: YOUR_API_KEY
Content-Type: application/json Authorization: Bearer YOUR_USERNAME:YOUR_API_KEY
Notes: GET endpoints also accept ?username=...&apiKey=... query parameters, and POST bodies accept username/apiKey. Parent account API keys can also dispatch on behalf of direct sub-accounts by passing the sub-account username in X-Username.
| Method | Path (prefix: https://smsgateway.mspace.co.ke/whatsapp) |
Auth | Purpose |
|---|---|---|---|
| POST | /api/v2/messages/bulk |
API Key | Queue an asynchronous bulk campaign to multiple recipients with per-recipient template variables. Returns 202 Accepted. |
| POST | /api/v2/messages |
API Key | Send a single message (template, text, media, interactive_buttons, or cta_url). Returns 201 Created. |
| GET | /api/v2/messages/{wamid}/status |
API Key | Check delivery status (SENT, DELIVERED, READ, FAILED, OPTOUT) and timestamps for a message ID. |
| GET | /api/v2/campaigns/{campaignId} |
API Key | Get live bulk campaign totals and delivery counters (total, sent, delivered, read_count, failed). |
| GET | /api/v2/templates |
API Key | List approved Meta templates available on your sender number along with variable counts and header types. |
| GET | /api/v2/account/balance |
API Key | Check remaining WhatsApp credits and per-category KES message rates (costPerMarketing, costPerUtility, costPerAuthentication). |
| POST | /api/v2/webhooks/test |
API Key | Send a signed test delivery event to your configured client webhook URL. |
| GET/POST | /api/v2/webhook |
Meta Verify | Meta Cloud API callback endpoint (hub.challenge handshake & X-Hub-Signature-256 delivery/inbound events) for bring-your-own-WABA setups. |
| GET | /health |
Public | Gateway health check. Returns {"status":"UP","service":"whatsapp-portal"}. |
| Field | Type | Required | Description |
|---|---|---|---|
recipients |
array | Required | Non-empty array of phone strings ("254712345678") or objects ({"to":"254712345678","params":["John","KES 4,500"]}). Accepts 07... or 2547.... |
type |
string | Optional | TEMPLATE (default when templateName is provided), TEXT, MEDIA, INTERACTIVE_BUTTONS, or CTA_URL. |
templateName |
string | Template | Exact approved Meta template name (alias: template). |
language |
string | Optional | Template language code (e.g. en, en_US). Auto-detected if omitted. |
campaignName |
string | Optional | Label for tracking in the portal and campaign status API. |
params / paramsCount |
array / int | Optional | Shared fallback variables for all recipients and variable placeholder count. |
headerType / headerMediaUrl |
string | Optional | For media-header templates: IMAGE, DOCUMENT, or VIDEO plus public HTTPS URL. |
{
"campaignName": "Monthly Statement Run",
"type": "TEMPLATE",
"templateName": "payment_receipt",
"language": "en",
"paramsCount": 2,
"recipients": [
{ "to": "254712345678", "params": ["John", "KES 4,500"] },
{ "to": "254722111000", "params": ["Mary", "KES 8,200"] }
]
}
{
"status": "RUNNING",
"campaignId": 997,
"total": 2
}
type: "template" to message customers anytime (alerts, OTPs, receipts, promotions). Free-form text, media, interactive_buttons, and cta_url can only be sent within 24 hours of the customer's last reply.
| Field | Type | Required | Description |
|---|---|---|---|
to |
string | Required | Recipient phone in E.164 (254712345678) or local (0712345678) format (alias: recipient). |
type |
string | Optional | template, text (default), media, interactive_buttons, or cta_url. |
templateName, language, params |
string / array | Template | Approved template name, language code, and ordered array of body variables. Optional headerType + headerMediaUrl. |
message, previewUrl |
string / bool | Text | Plain text body (up to 4,096 chars) and optional link preview flag. |
mediaType, mediaUrl, caption, filename |
string | Media | image, document, or video with public HTTPS URL, optional caption and PDF filename. |
body, buttons / ctaLabel, ctaUrl |
string / array | Interactive | Up to 3 quick-reply labels (interactive_buttons) or CTA button text & URL (cta_url), plus optional headerText / footerText. |
{
"to": "254712345678",
"type": "template",
"templateName": "order_confirmation",
"language": "en",
"params": ["Amina", "INV-9021"],
"headerType": "IMAGE",
"headerMediaUrl": "https://cdn.example.com/receipt-banner.png"
}
{
"status": "SENT",
"messageId": "wamid.HBgLMjU0NzEyMzQ1Njc4FQIAERgSQk...",
"recipient": "254712345678",
"remainingCredits": 603.0
}
{
"to": "254712345678",
"type": "text",
"message": "Your support ticket #4412 has been resolved.",
"previewUrl": false
}
{
"status": "FAILED",
"errorCode": "131047",
"error": "Re-engagement message outside 24-hour window"
}
{
"to": "254712345678",
"type": "media",
"mediaType": "document",
"mediaUrl": "https://cdn.example.com/statements/inv-9021.pdf",
"caption": "April Account Statement",
"filename": "Statement_INV9021.pdf"
}
{
"to": "254712345678",
"type": "interactive_buttons",
"headerText": "Appointment Reminder",
"body": "Confirm your service visit tomorrow at 10:00 AM.",
"footerText": "Reply below or call support",
"buttons": ["Confirm Visit", "Reschedule"]
}
{
"to": "254712345678",
"type": "cta_url",
"headerText": "Invoice Ready",
"body": "Tap below to review and pay your invoice online.",
"footerText": "MSpace Billing",
"ctaLabel": "Pay Invoice",
"ctaUrl": "https://pay.example.com/inv/9021"
}
curl -H "X-Username: YOUR_USERNAME" \ -H "X-API-Key: YOUR_API_KEY" \ "https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/wamid.HBgLMjU0.../status"
{
"id": 14521,
"campaign_id": 997,
"recipient": "254712345678",
"message_id": "wamid.HBgLMjU0...",
"template_name": "payment_receipt",
"status": "READ",
"error_code": null,
"error_msg": null,
"sent_at": "2026-11-20 10:12:04",
"delivered_at": "2026-11-20 10:12:06",
"read_at": "2026-11-20 10:12:41"
}
curl -H "X-Username: YOUR_USERNAME" \ -H "X-API-Key: YOUR_API_KEY" \ "https://smsgateway.mspace.co.ke/whatsapp/api/v2/campaigns/997"
{
"id": 997,
"campaign_name": "Monthly Statement Run",
"template_name": "payment_receipt",
"message_type": "TEMPLATE",
"total": 250,
"sent": 248,
"delivered": 245,
"read_count": 198,
"replied": 14,
"failed": 2,
"status": "COMPLETED"
}
curl -H "X-Username: YOUR_USERNAME" \ -H "X-API-Key: YOUR_API_KEY" \ "https://smsgateway.mspace.co.ke/whatsapp/api/v2/templates"
{
"whatsappEnabled": true,
"templates": [
{
"name": "payment_receipt",
"templateName": "payment_receipt",
"language": "en",
"category": "UTILITY",
"status": "APPROVED",
"body": "Hi {{1}}, we received {{2}}.",
"paramsCount": 2,
"headerType": "NONE"
}
]
}
curl -H "X-Username: YOUR_USERNAME" \ -H "X-API-Key: YOUR_API_KEY" \ "https://smsgateway.mspace.co.ke/whatsapp/api/v2/account/balance"
{
"username": "YOUR_USERNAME",
"whatsappEnabled": true,
"billingUserId": 1024,
"credits": 1250.0,
"costPerUtility": 1.0,
"costPerMarketing": 4.0,
"costPerAuthentication": 1.0
}
curl -X POST \ -H "X-Username: YOUR_USERNAME" \ -H "X-API-Key: YOUR_API_KEY" \ "https://smsgateway.mspace.co.ke/whatsapp/api/v2/webhooks/test"
{
"success": true,
"httpStatus": 200,
"message": "OK"
}
curl -X POST "https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/bulk" \
-H "Content-Type: application/json" \
-H "X-Username: YOUR_USERNAME" \
-H "X-API-Key: YOUR_API_KEY" \
-d '{
"campaignName": "Invoice Reminders",
"type": "TEMPLATE",
"templateName": "payment_receipt",
"language": "en",
"recipients": [
{ "to": "254712345678", "params": ["John", "KES 4,500"] },
{ "to": "254722111000", "params": ["Mary", "KES 8,200"] }
]
}'
curl -X POST "https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages" \
-H "Content-Type: application/json" \
-H "X-Username: YOUR_USERNAME" \
-H "X-API-Key: YOUR_API_KEY" \
-d '{
"to": "254712345678",
"type": "template",
"templateName": "order_confirmation",
"language": "en",
"params": ["Amina", "INV-9021"]
}'
import requests
BASE_URL = "https://smsgateway.mspace.co.ke/whatsapp"
HEADERS = {
"X-Username": "YOUR_USERNAME",
"X-API-Key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
payload = {
"campaignName": "Invoice Reminders",
"type": "TEMPLATE",
"templateName": "payment_receipt",
"language": "en",
"recipients": [
{"to": "254712345678", "params": ["John", "KES 4,500"]},
{"to": "254722111000", "params": ["Mary", "KES 8,200"]},
],
}
resp = requests.post(f"{BASE_URL}/api/v2/messages/bulk", json=payload, headers=HEADERS, timeout=15)
resp.raise_for_status()
print(resp.json())
import hmac, hashlib
def verify_mspace_signature(raw_body: bytes, header_sig: str, secret: str) -> bool:
expected = "sha256=" + hmac.new(
secret.encode("utf-8"), raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, header_sig or "")
const res = await fetch("https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/bulk", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Username": "YOUR_USERNAME",
"X-API-Key": "YOUR_API_KEY",
},
body: JSON.stringify({
campaignName: "Invoice Reminders",
type: "TEMPLATE",
templateName: "payment_receipt",
language: "en",
recipients: [
{ to: "254712345678", params: ["John", "KES 4,500"] },
{ to: "254722111000", params: ["Mary", "KES 8,200"] },
],
}),
});
if (!res.ok) throw new Error("HTTP " + res.status + ": " + (await res.text()));
console.log(await res.json());
const crypto = require("crypto");
function verifySignature(rawBodyBuffer, signatureHeader, secret) {
const expected = "sha256=" + crypto
.createHmac("sha256", secret)
.update(rawBodyBuffer)
.digest("hex");
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(signatureHeader || "", "utf8");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
<?php
$ch = curl_init("https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/bulk");
$payload = json_encode([
"campaignName" => "Invoice Reminders",
"type" => "TEMPLATE",
"templateName" => "payment_receipt",
"language" => "en",
"recipients" => [
["to" => "254712345678", "params" => ["John", "KES 4,500"]],
["to" => "254722111000", "params" => ["Mary", "KES 8,200"]]
]
]);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"X-Username: YOUR_USERNAME",
"X-API-Key: YOUR_API_KEY"
],
CURLOPT_POSTFIELDS => $payload
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
<?php
$rawBody = file_get_contents("php://input");
$sig = $_SERVER["HTTP_X_MSPACE_SIGNATURE"] ?? "";
$secret = "YOUR_WEBHOOK_SECRET";
$expected = "sha256=" . hash_hmac("sha256", $rawBody, $secret);
if (!hash_equals($expected, $sig)) {
http_response_code(401);
exit("Invalid signature");
}
$event = json_decode($rawBody, true);
http_response_code(200);
import java.net.URI;
import java.net.http.*;
String json = "{"
+ "\"campaignName\":\"Invoice Reminders\","
+ "\"type\":\"TEMPLATE\","
+ "\"templateName\":\"payment_receipt\","
+ "\"language\":\"en\","
+ "\"recipients\":["
+ "{\"to\":\"254712345678\",\"params\":[\"John\",\"KES 4,500\"]}"
+ "]}";
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/bulk"))
.header("Content-Type", "application/json")
.header("X-Username", "YOUR_USERNAME")
.header("X-API-Key", "YOUR_API_KEY")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> res = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] digest = mac.doFinal(rawBodyBytes);
StringBuilder hex = new StringBuilder("sha256=");
for (byte b : digest) hex.append(String.format("%02x", b));
boolean valid = MessageDigest.isEqual(
hex.toString().getBytes(StandardCharsets.UTF_8),
headerSig.getBytes(StandardCharsets.UTF_8)
);
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Username", "YOUR_USERNAME");
client.DefaultRequestHeaders.Add("X-API-Key", "YOUR_API_KEY");
var payload = new {
campaignName = "Invoice Reminders",
type = "TEMPLATE",
templateName = "payment_receipt",
language = "en",
recipients = new[] {
new { to = "254712345678", @params = new[] { "John", "KES 4,500" } }
}
};
var content = new StringContent(
JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
var resp = await client.PostAsync(
"https://smsgateway.mspace.co.ke/whatsapp/api/v2/messages/bulk", content);
string body = await resp.Content.ReadAsStringAsync();
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
byte[] hash = hmac.ComputeHash(rawBodyBytes);
string expected = "sha256=" + Convert.ToHexString(hash).ToLowerInvariant();
bool valid = CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(expected),
Encoding.UTF8.GetBytes(headerSig ?? ""));
Configure your callback URL, signing secret, and subscribed events inside the WhatsApp Portal under Webhooks.
POST with headers X-MSpace-Event and X-MSpace-Signature: sha256=<hex> (HMAC-SHA256 over the exact UTF-8 JSON body).SENT, DELIVERED, READ, FAILED, INBOUND, and TEST.2xx within 10 seconds. Failed deliveries automatically retry up to 5 times with exponential backoff (60s, 120s, 240s...).https://smsgateway.mspace.co.ke/whatsapp/api/v2/webhook (verifies hub.challenge and X-Hub-Signature-256).{
"event": "DELIVERED",
"timestamp": 1795171480000,
"message_id": "wamid.HBgLMjU0NzEyMzQ1Njc4FQIAERgSQk...",
"data": {
"recipient": "254712345678",
"status": "DELIVERED",
"phone_number_id": "104591827364510",
"timestamp": "1795171479"
}
}
{
"event": "INBOUND",
"timestamp": 1795171502000,
"message_id": "wamid.HBgLMjU0NzEyMzQ1Njc4FQIAERgSQk...",
"data": {
"from": "254712345678",
"contact_name": "John Kamau",
"type": "text",
"body": "Confirm Visit",
"phone_number_id": "104591827364510",
"is_opt_out": false
}
}
| HTTP Status | Meaning | When Returned / Action |
|---|---|---|
| 200 / 201 / 202 | Success | 200 query/test succeeded, 201 single message sent, 202 bulk campaign queued. |
| 400 | Bad Request | Missing or invalid to, empty recipients array, or missing required field for the chosen message type. |
| 401 | Unauthorized | Invalid X-Username / X-API-Key or Bearer token. Verify or rotate your key in the portal. |
| 402 | Payment Required | Insufficient WhatsApp credits. Recharge via self-service top-up at mspace.co.ke/buy. |
| 403 | Forbidden | WhatsApp Business API is not yet enabled on the account or sub-account lacks API permission. |
| 404 | Not Found | Unknown wamid or campaignId for your account. |
| 422 | Unprocessable Entity | Recipient has opted out in the Opt-Out Registry; message blocked automatically. |
| 502 | Bad Gateway | Meta rejected the dispatch (credit is automatically refunded) or your webhook test endpoint failed. |
0712345678) or international E.164 (254712345678) and are normalized automatically.params must match the exact number of {{1}}, {{2}}... placeholders in your approved template.mediaUrl and headerMediaUrl) must be publicly reachable over HTTPS.This page illustrates how you, a developer, a technical personnel or any form of our esteemed client can use our bulk SMS services with ease without necessarily logging into our web application. After this illustration you will be able to send texts, query SMS account balance and list your sub- account users in the system. This documentation assumes that you have subscribed for our bulk SMS services. If not please visit our website âwww.mspace.co.keâ or contact our offices to be assisted and be able to enjoy our services.
This is the get balance url =
â http://main_url/mspaceservice/wr/sms/balance /username={username}/password={password}â,
where username is the value of your username and
password the value of your password.
http://main_url/mspaceservice/wr/sms/balance /username=myusername/password=mypassword
You can test this by pasting in your browser and press enter.
âyour sms balance e.g. â50ââ if you are a subscribed user or âError 100: Authentication Failureâ if your credentials are wrong.
NOTE that your URL format should support URL encoding UTF- 8 . Messages that are not properly formatted may be delivered with incorrectly encoded text or not delivered at all.
The request methods are summarized in the table below:
main_url = http://main_url/mspaceservice/wr/sms
| Method | Query SMS Balance |
|---|---|
| Url Structure | main_url/balance/username={username}/password={password} |
| Url example | http://main_url/balance/username=myusername/password=mypassword |
| Response on success | Your current SMS balance e.g. â50â. |
| Response on failure | Authentication failure for wrong user credentials or non-existing user. |
| Method | Send Text |
|---|---|
| Url Structure | main_url/sendtext/username={username}/password={password}/senderid={senderId}/recipient={recipient}/message={message} |
| Url example | http://main_url/sendtext/username=myusername/password=mypassword/senderid=mysenderid/recipient=myrecipient/message=mymessage |
| Response on success | Send action status and the sent message id i.e.â[{"messageId": "12345", "responseTime": "2018-06-2511:12:19:793", "status": "successful"}]â |
| Response on failure | Athentication failure,Insufficient Balance, Invalid sender ID or internal service error. |
| Method | Query sub-account users |
|---|---|
| Url Structure | main_url/subusers/username={username}/password={password} |
| Url example | http://main_url/subusers/username=myusername/password=mypassword |
| Response on success | The username of your sub-account users and their SMS balances respectively i.e. â[{"smsBalance": "20", "subUserName": "subuser1"},{"smsBalance": "18", "subUserName": "subuser2"}]ââ[]â if no subuser exists. |
| Response on failure | Authentication failure. |
| Method | Query Re-Seller users |
|---|---|
| Url Structure | main_url/resellerclients/username={username}/password={password} |
| Url example | http://main_url/resellerclients/username=myusername/password=mypassword |
| Response on success | The username of your clients and their SMS balances respectively i.e. â[{"smsBalance": "20", "clientname": "client1"}, {"smsBalance": "18", "clientname": "client2"}]â |
| Response on failure | Authentication failure. |
| Method | Re-Seller users Top-up |
|---|---|
| Url Structure | main_url/resellerclienttopup/username={username}/password={password} /clientname={clientname}/noofsms={noofsms} |
| Url example | http://main_url/resellerclienttopup/username=myusername/password=mypassword/clientname={myclientname}/noofsms={noofsms} |
| Response on success | Successful Top up of noOfSms SMS to clientname. |
| Response on failure | Athentication failure, Insufficient Balance, You are not Authorized to make this transaction, indly Contact Providers for help, Failed to top up clientname account, Top up not Successful, Failed to deduct your account, or internal service error. |
| Method | Sub-Account users Top-up |
|---|---|
| Url Structure | main_url/subacctopup/username={username}/password={password}/subaccname={subaccname}/noofsms={noofsms} |
| Url example | http://main_url/subacctopup/username=myusername/password=mypassword/subaccname={mysubaccname}/noofsms={noofsms} |
| Response on success | Successful Top up of noOfSms SMS to subAccName. |
| Response on failure | Athentication failure, Insufficient Balance,You are not Authorized to make this transaction,Kindly Contact Providers for help, Failed to top up subAccName account, Top up not Successful, failed to deduct your account, or internal service error. |
| Method | System Login |
|---|---|
| Url Structure | main_url/login/username={username}/password={password} |
| Url example | http://main_url/login/username=myusername/password=mypassword |
| Response on success | User exists. |
| Response on failure | Authentication failure. |
Java developers can be emailed or obtain the java client API jar file bundled with dependencies here and add into the class-path of their project. Having this jar file, your work will be made easier. The API contains all the request methods:
subUsers_JSON(Class responseType, String username, String password, String senderid, String recipient,
String message); Returns JSON object of the returned value by this method, example:
subUsers_XML(Class responseType, String username, String password, String senderid, String recipient,
String message); Returns XML object of the returned value by this method, example:
subUsers_XML(Class responseType, String username, String password);
Returns XML object of the returned value by this method, example:
subUsers_JSON(Class responseType, String username, String password);
Returns JSON object of the returned value by this method,
example: login_TEXT(this.username, this.password);
Returns PLAIN_TEXT object of the returned value by this method, example:
resellerClientTopup_XML(Class responseType, this.reselerUsername, this.resellerPassword, this.clientName, this.noOfsms);
Returns XML object of the returned value by this method,
example: subAccTopup_JSON(Class responseType, this.mainAccname, this.mainAccPassword, this.subAccname, this.noOfsms);
Returns JSON object of the returned value by this method,
example: resellerClients_XML(Class responseType, String username, String password);
Returns XML object of the returned value by this method, example:
resellerClients_JSON(Class responseType, String username, String password);
Returns JSON object of the returned value by this method,
example: getBalance(String username, String password);
Returns PLAIN_TEXT object of the returned value by this method, example:
Closes the client instance.
To view your full request url, method type and request status by the API methods use Response class as the response type. Example:
Output: InboundJaxrsResponse{ ClientResponse{method=GET, uri=http://main_url/mspaceservice/ wr/sms/subusers/username= myusername/password=mypassword, status=200, reason=OK}}
The following methods are for python users.
main_api = "http://main_url/mspaceservice/wr/sms/"
Many website are designed on top of wordpress CRM. MSpace has developed a plugin to enable customers easily integrate their wordpress with Bulk SMS. This plugin supports below:
The widget for the plugin is available on all your widgets areas.
To use the plugin in your PHP code, see below example:
The connection between the application and the SMPP server is SMPP version 3.4.
| NAME | DESCRIPTION |
|---|---|
| system _ id | Provided for each client |
| password | Provided for each client |
| IP address | To be provided |
| port | 2775 |
| timeout (keep alive) | 50 sec |
You are allowed to bind as transmitter or receiver. In order to receive delivery reports, you must bind as receiver.
bind _ transmitter, bind _ reciever, unbind, submit _ sm, deliver _ sm, enquire _ link
“id:<message _ id> sub:<message _ sub> dlvrd:<message _ dlvrd> submit date:<message _ submit _ date> done date:<message _ done _ date> stat:<message _ stat> err:<message _ err>”
DELIVRD, EXPIRED, UNDELIV , ACCEPTD, UNKNOWN, REJECTED
For more information please email info@mspace.co.ke or call +254722962934
For a user to process any USSD request with MSpace Solutions, one needs to setup an account with us. Once that is done, the following follows.
A USSD mobile request must have the MSSDN,SESSION_ID,CALLBACK_URL,
USER_DATA information appended to it. This request will be sent to the third party ia
the endpoint URL provide by the client. This data is JSON formatted
| ELEMENT NAME | DESCRIPTION |
|---|---|
| MSISDN | This is the mobile number that sends the POST request. |
| SESSION_ID | This is the session id. It’s unique to every request send. It represents a single USSD session. |
| CALLBACK_URL | Provided by the client. It will be triggered any time a request is sent. |
| USSD_STRING | This is the information a user enters as he interacts with the USSD menus. This data is stored in a database |
| SERVICE_CODE | This is the code provided by the client that will be used in the API parameters |
USSD is session driven. Generated response represents menus that will be shown to the person dialing the USSD code. USSD uses CON keyword to initiate a connection and END keyword to end a session. In the case of an error, a malformed response will be sent and the USSD session will terminate immediately and the USSD application flow will break.
Leave your details and our team will help you set up SMS, WhatsApp, USSD, or M-Pesa.
Kenya Office
Elysee(Ntashart) Plaza, Kilimani Road, 2nd Floor Suite 4A
Uganda Office
Kampala, Makerere Hill Road, Ham Towers, 3rd floor, Suite No HT 25
Become the premier mobile solutions provider in East Africa.
Provide reliable, affordable mobile messaging and payment tools for businesses.
Manage Bulk SMS, WhatsApp Business, Bulk Email, OmniConnect, USSD & Surveys natively on Android (v1.0.6) and Windows, macOS & Linux Desktop (v1.2.11).
We'd love to help you! Kindly share your contact details below so we can serve you better and get back to you promptly.
Kindly confirm your email and phone number so we can reach you back:
We've sent a 6-digit code to your contact details. Please enter it below.
How satisfied were you with our support?