Webhooks
A webhook is an address on your server that SemaLink calls when something happens: a message is delivered, a message fails, a sender ID is approved. Your system hears about it in seconds, without asking.
How it works
- You add an endpoint: an HTTPS address and the events you want.
- When an event happens, SemaLink sends a
POSTto that address with the event as JSON, signed with your endpoint's secret. - Your server checks the signature, answers
200quickly, then does its work. - If your server doesn't answer with a
2xxin time, SemaLink tries again later.
Events
| Event | When | data.object |
|---|---|---|
message.sent | A message was handed to the network | Message |
message.delivered | The network confirmed delivery | Message |
message.failed | It wasn't delivered: the network couldn't deliver it or refused it | Message |
message.held | A message is held for a check by SemaLink | Message |
message.released | A held message was released and is on its way | Message |
batch.completed | Every message of an API batch was handed over | Batch |
sender_id.approved | A sender ID was approved | Sender ID |
sender_id.rejected | A sender ID was rejected | Sender ID |
campaign.completed | A campaign sent from the app finished | An older shape: below |
Message events cover every message, sent through the API or from the app. There's no event when a message expires.
The payload
Every event (except campaign.completed) has the same envelope. data.object is the full object, exactly as the API returns it:
{
"id": "evt_9d8c7b6a5f4e4d3c2b1a0f9e8d7c6b5a",
"object": "event",
"type": "message.delivered",
"livemode": true,
"created_at": "2026-12-01T07:30:06.000Z",
"data": {
"object": {
"id": "msg_3b9f6c2a1d4e4f5a8b7c6d5e4f3a2b1c",
"object": "message",
"livemode": true,
"to": "+254712345678",
"from": "GREENHILL",
"text": "Your order 1042 is ready for collection at Greenhill Shop, Moi Avenue. Call 0712 345 678.",
"type": "service",
"status": "delivered",
"network": "safaricom",
"parts": 1,
"encoding": "gsm7",
"cost": { "amount": 80, "currency": "KES", "display": "KES 0.80" },
"reference": "invoice-1042",
"batch": null,
"send_at": null,
"created_at": "2026-12-01T07:30:00.000Z",
"sent_at": "2026-12-01T07:30:02.000Z",
"delivered_at": "2026-12-01T07:30:06.000Z",
"failure": null,
"refunded": false
}
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Each request also carries these headers:
| Header | Value |
|---|---|
Content-Type | application/json |
X-SemaLink-Event | The event type, such as message.delivered |
X-SemaLink-Event-Id | The event's ID (evt_...), the same in every delivery of it |
X-SemaLink-Delivery-Attempt | 1 for the first try, 2 for the first retry, and so on |
X-SemaLink-Signature-256 | The signature: t=<unix time>,v1=<hex> |
X-SemaLink-Signature | The older signature: the hex HMAC-SHA256 of the body alone, with no timestamp. Kept for endpoints built on it; use the one above. |
campaign.completed
campaign.completed keeps the shape it had before the API, for the endpoints already built on it. It goes to live endpoints only, its id is a plain UUID (also in X-SemaLink-Event-Id), and it is signed the same way:
{
"id": "0b6f3c1e-8d2a-4f5b-9c7e-1a2b3c4d5e6f",
"event": "campaign.completed",
"data": {
"id": "9e8d7c6b-5a4f-4e3d-2c1b-0a9f8e7d6c5b",
"name": "Term 1 fees reminder",
"totalRecipients": 412,
"completedAt": "2026-12-02T08:02:41.000Z",
"messages": { "delivered": 398, "failed": 9, "expired": 5 }
},
"timestamp": "2026-12-02T08:02:41.000Z"
}2
3
4
5
6
7
8
9
10
11
12
Campaigns sent through the API (batches and single messages) don't send campaign.completed; a batch sends batch.completed.
Test and live endpoints
Every endpoint is either test or live:
- Test endpoints get sandbox events only (
"livemode": false). - Live endpoints get live events only (
"livemode": true).
A test key manages test endpoints and a live key manages live ones; the endpoint's livemode says which it is. Point your test endpoint at a development server, and only your live endpoint at production.
Add an endpoint
In the dashboard, open Developer, then Webhooks, then Add endpoint. Or use the API:
curl https://api.semalink.africa/v1/webhooks \
-H "Authorization: Bearer $SEMALINK_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{
"url": "https://example.co.ke/webhooks/semalink",
"events": ["message.delivered", "message.failed"],
"description": "Delivery reports for the billing system"
}'2
3
4
5
6
7
8
9
const response = await fetch('https://api.semalink.africa/v1/webhooks', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SEMALINK_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': crypto.randomUUID(),
},
body: JSON.stringify({
url: 'https://example.co.ke/webhooks/semalink',
events: ['message.delivered', 'message.failed'],
description: 'Delivery reports for the billing system',
}),
});
const endpoint = await response.json();
console.log(response.status, endpoint.id, endpoint.secret); // 201; store the secret now: it is shown once2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
import uuid
import requests
response = requests.post(
"https://api.semalink.africa/v1/webhooks",
headers={
"Authorization": f"Bearer {os.environ['SEMALINK_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={
"url": "https://example.co.ke/webhooks/semalink",
"events": ["message.delivered", "message.failed"],
"description": "Delivery reports for the billing system",
},
timeout=30,
)
endpoint = response.json()
print(endpoint["id"], endpoint["secret"]) # store the secret now: it is shown once2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$ch = curl_init('https://api.semalink.africa/v1/webhooks');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('SEMALINK_API_KEY'),
'Content-Type: application/json',
'Idempotency-Key: ' . bin2hex(random_bytes(16)),
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://example.co.ke/webhooks/semalink',
'events' => ['message.delivered', 'message.failed'],
'description' => 'Delivery reports for the billing system',
]),
]);
$endpoint = json_decode(curl_exec($ch), true);
echo $endpoint['id'], ' ', $endpoint['secret'], PHP_EOL; // store the secret now: it is shown once2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
201 Created, with the endpoint:
{
"id": "whe_5e4d3c2b1a0f4e9d8c7b6a5f4e3d2c1b",
"object": "webhook_endpoint",
"livemode": true,
"url": "https://example.co.ke/webhooks/semalink",
"description": "Delivery reports for the billing system",
"events": ["message.delivered", "message.failed"],
"enabled": true,
"failing_since": null,
"created_at": "2026-12-01T10:00:00.000Z",
"updated_at": "2026-12-01T10:00:00.000Z",
"secret": "whsec_5b0e7c1d9a3f42e68b1c0d7e9f2a4b6c8d0e1f3a5b7c9d1e"
}2
3
4
5
6
7
8
9
10
11
12
13
The secret is shown once. Keep it with your other secrets; you need it to verify signatures. The url must be public and start with https:// (url_not_https, url_private_address).
To pause deliveries, PATCH the endpoint with "enabled": false: what was waiting is cancelled. failing_since shows when deliveries started failing in a row, and is null while they succeed. Creating, changing and testing endpoints is limited to 20 a minute per organisation.
Verify signatures
Anyone can send a POST to your address. The signature proves a request came from SemaLink and wasn't changed on the way. Check it on every request before you trust the body.
The X-SemaLink-Signature-256 header looks like this:
X-SemaLink-Signature-256: t=1796195732,v1=f91da006502224dd845dd1232a0f66d5f256eaea1a72463026afdcdf6ce6ed39tis when SemaLink sent this delivery attempt, in Unix seconds. A retry is signed again with its ownt.v1is the HMAC-SHA256 oft, a full stop, and the raw request body, keyed with your endpoint's secret, in hex.
To check it:
- Read the raw body exactly as it arrived. Don't parse and re-encode the JSON first: any change of spacing or order breaks the signature.
- Split the header on commas and read
tand everyv1. - Reject the request if
tis more than 5 minutes from your server's clock. This stops someone replaying an old request. - Compute
HMAC-SHA256(secret, t + "." + raw_body)as hex. Use the whole secret, includingwhsec_. - Compare it with each
v1using a constant-time comparison. If one matches, the request is genuine.
// verify-semalink.js
import crypto from 'node:crypto';
const TOLERANCE_SECONDS = 5 * 60;
/**
* Checks an X-SemaLink-Signature-256 header ("t=<unix time>,v1=<hex>") against the raw request body.
* rawBody must be the exact bytes received (a Buffer or string), before any JSON parsing.
*/
export function verifySemaLinkSignature(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
if (!header) return false;
let timestamp = null;
const signatures = [];
for (const part of header.split(',')) {
const [key, value] = part.trim().split('=', 2);
if (key === 't') timestamp = value;
else if (key === 'v1' && value) signatures.push(value);
}
if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false;
if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false;
const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest();
return signatures.some((signature) => {
const given = Buffer.from(signature, 'hex');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# verify_semalink.py
import hashlib
import hmac
import time
TOLERANCE_SECONDS = 5 * 60
def verify_semalink_signature(raw_body: bytes, header: str, secret: str, now=None) -> bool:
"""Checks an X-SemaLink-Signature-256 header ("t=<unix time>,v1=<hex>") against the raw request body."""
if not header:
return False
timestamp = None
signatures = []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t":
timestamp = value
elif key == "v1" and value:
signatures.append(value)
if not timestamp or not timestamp.isdigit() or not signatures:
return False
now = int(time.time()) if now is None else now
if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
return False
signed = timestamp.encode() + b"." + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected.encode(), s.encode()) for s in signatures)2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// verify-semalink.php
const SEMALINK_TOLERANCE_SECONDS = 300;
/** Checks an X-SemaLink-Signature-256 header ("t=<unix time>,v1=<hex>") against the raw request body. */
function verifySemaLinkSignature(string $rawBody, string $header, string $secret, ?int $now = null): bool
{
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
$pair = explode('=', trim($part), 2);
if (count($pair) !== 2) {
continue;
}
[$key, $value] = $pair;
if ($key === 't') {
$timestamp = $value;
} elseif ($key === 'v1' && $value !== '') {
$signatures[] = $value;
}
}
if ($timestamp === null || !ctype_digit($timestamp) || !$signatures) {
return false;
}
$now = $now ?? time();
if (abs($now - (int) $timestamp) > SEMALINK_TOLERANCE_SECONDS) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return true;
}
}
return false;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Package webhooks checks SemaLink webhook signatures.
package webhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
"time"
)
const tolerance = 5 * time.Minute
// VerifySignature checks an X-SemaLink-Signature-256 header ("t=<unix time>,v1=<hex>")
// against the raw request body.
func VerifySignature(rawBody []byte, header, secret string, now time.Time) bool {
var timestamp string
var signatures [][]byte
for _, part := range strings.Split(header, ",") {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok {
continue
}
switch key {
case "t":
timestamp = value
case "v1":
if sig, err := hex.DecodeString(value); err == nil {
signatures = append(signatures, sig)
}
}
}
ts, err := strconv.ParseUint(timestamp, 10, 63)
if err != nil || len(signatures) == 0 {
return false
}
age := now.Sub(time.Unix(int64(ts), 0))
if age > tolerance || age < -tolerance {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp + "."))
mac.Write(rawBody)
expected := mac.Sum(nil)
for _, sig := range signatures {
if hmac.Equal(expected, sig) {
return true
}
}
return false
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
The header can carry more than one v1 (for example while a secret is being replaced). The code accepts the request if any of them matches.
Use it in your handler
import express from 'express';
import { verifySemaLinkSignature } from './verify-semalink.js';
const app = express();
// express.raw keeps the exact bytes: the signature is over the body as sent.
app.post('/webhooks/semalink', express.raw({ type: 'application/json' }), (req, res) => {
const header = req.get('X-SemaLink-Signature-256');
if (!verifySemaLinkSignature(req.body, header, process.env.SEMALINK_WEBHOOK_SECRET)) {
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(req.body);
res.sendStatus(200); // answer first, then do the work
handleEvent(event).catch(console.error);
});
async function handleEvent(event) {
if (event.type === 'message.delivered') {
// e.g. mark invoice event.data.object.reference as reminded
}
}
app.listen(3000);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import json
import os
from flask import Flask, request
from verify_semalink import verify_semalink_signature
app = Flask(__name__)
@app.post("/webhooks/semalink")
def semalink_webhook():
raw = request.get_data() # the exact bytes, before parsing
header = request.headers.get("X-SemaLink-Signature-256", "")
if not verify_semalink_signature(raw, header, os.environ["SEMALINK_WEBHOOK_SECRET"]):
return "Invalid signature", 400
event = json.loads(raw)
if event["type"] == "message.delivered":
pass # e.g. queue a job to mark event["data"]["object"]["reference"] as reminded
return "", 2002
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
require __DIR__ . '/verify-semalink.php';
$rawBody = file_get_contents('php://input'); // the exact bytes, before parsing
$header = $_SERVER['HTTP_X_SEMALINK_SIGNATURE_256'] ?? '';
if (!verifySemaLinkSignature($rawBody, $header, getenv('SEMALINK_WEBHOOK_SECRET'))) {
http_response_code(400);
exit('Invalid signature');
}
$event = json_decode($rawBody, true);
if ($event['type'] === 'message.delivered') {
// e.g. queue a job to mark $event['data']['object']['reference'] as reminded
}
http_response_code(200);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"encoding/json"
"io"
"net/http"
"os"
"time"
"example.com/yourapp/webhooks"
)
func semalinkWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // the exact bytes, before parsing
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
header := r.Header.Get("X-SemaLink-Signature-256")
if !webhooks.VerifySignature(body, header, os.Getenv("SEMALINK_WEBHOOK_SECRET"), time.Now()) {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
var event struct {
ID string `json:"id"`
Type string `json:"type"`
}
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK) // then hand the event to a worker
}
func main() {
http.HandleFunc("/webhooks/semalink", semalinkWebhook)
http.ListenAndServe(":3000", nil)
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Check your code with this example
Your function should return true for this request when "now" is 1796195732 (and false if you change one character of the body):
| Part | Value |
|---|---|
| Secret | whsec_5b0e7c1d9a3f42e68b1c0d7e9f2a4b6c8d0e1f3a5b7c9d1e |
| Header | t=1796195732,v1=f91da006502224dd845dd1232a0f66d5f256eaea1a72463026afdcdf6ce6ed39 |
| Body | the line below, exactly, with no line break at the end |
{"id":"evt_9d8c7b6a5f4e4d3c2b1a0f9e8d7c6b5a","object":"event","type":"message.delivered","livemode":false,"created_at":"2026-12-02T07:15:31.000Z","data":{"object":{"id":"msg_3b9f6c2a1d4e4f5a8b7c6d5e4f3a2b1c","object":"message","status":"delivered"}}}Then send a real one: in the dashboard choose Send test event on the endpoint, or call POST /v1/webhooks/{id}/test. It posts one signed webhook.test event straight away (never retried) and answers with how your endpoint replied: success, status_code, error and duration_ms.
Answer quickly
Answer with any 2xx status within 10 seconds. Anything else counts as a failure: a 3xx, 4xx or 5xx, a timeout, or a connection error. Redirects aren't followed, so give the final address.
Do slow work (database updates, emails, other API calls) after you answer, or put the event on a queue.
Retries
When a delivery fails, SemaLink tries again after:
| Attempt | Waits after the last failure |
|---|---|
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 6 hours |
| 7 | 12 hours |
24 hours after the event, SemaLink gives up on it. Every attempt is in the endpoint's delivery log in the dashboard, with the status your server answered. When an endpoint keeps failing, we email you, and failing_since on the endpoint shows since when.
Missed something while your server was down? Fetch the event with GET /v1/events/{id} (for 30 days), or list messages with GET /v1/messages to catch up.
Duplicates and order
- The same event can arrive more than once, for example when your server handled it but its answer was lost. Store each event's
idand skip ones you've already handled. - Events can arrive out of order. Up to four deliveries to one endpoint can be in flight at once, and retries wait. Use the message's
statusandstatus_history, not the order of arrival, to decide what's current.
Good endpoints
- Use a public HTTPS address.
http://and private or local addresses are refused. - Verify the signature and the timestamp on every request.
- Answer within 10 seconds; queue the work.
- Handle duplicates with the event
id. - Use a different secret, and a different endpoint, for test and live.