Bulk WhatsApp Business API
Send single and bulk WhatsApp messages, track delivery and campaign progress, list approved templates, check wallet credits, and receive signed webhooks.
1. Authentication
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.
2. Endpoint Directory
| 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"}. |
3. Endpoints & JSON Schemas
POST /api/v2/messages/bulk Queue a bulk WhatsApp campaign (personalized or broadcast)
| 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
}
POST /api/v2/messages Send a single template, text, media, quick-reply, or CTA URL message
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"
}
GET /api/v2/messages/{wamid}/status Check delivery status and timestamps by message ID
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"
}
GET /api/v2/campaigns/{campaignId} Retrieve bulk campaign progress and aggregate delivery counters
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"
}
GET /api/v2/templates List approved WhatsApp templates for your account
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"
}
]
}
GET /api/v2/account/balance Check WhatsApp credit balance and per-category message rates
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
}
POST /api/v2/webhooks/test Trigger a live signed test webhook delivery
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"
}
4. Code Examples
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 ?? ""));
5. Signed Outbound Webhooks & Meta Callback
Configure your callback URL, signing secret, and subscribed events inside the WhatsApp Portal under Webhooks.
- Every callback is an HTTP
POSTwith headersX-MSpace-EventandX-MSpace-Signature: sha256=<hex>(HMAC-SHA256 over the exact UTF-8 JSON body). - Subscribed events:
SENT,DELIVERED,READ,FAILED,INBOUND, andTEST. - Return any HTTP
2xxwithin 10 seconds. Failed deliveries automatically retry up to 5 times with exponential backoff (60s,120s,240s...). - Bring-Your-Own Meta App / WABA: Set Meta Developer Console callback URL to
https://smsgateway.mspace.co.ke/whatsapp/api/v2/webhook(verifieshub.challengeandX-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
}
}
6. HTTP Status Codes
| 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. |
7. Key Rules
- Phone numbers accept local Kenyan format (
0712345678) or international E.164 (254712345678) and are normalized automatically. - Template variables in
paramsmust match the exact number of{{1}},{{2}}... placeholders in your approved template. - Media URLs (
mediaUrlandheaderMediaUrl) must be publicly reachable over HTTPS. - If Meta rejects a single send, the deducted credit is automatically refunded to your WhatsApp balance.