Connect Mursilat to n8n
Send WhatsApp messages from n8n with the API and receive Mursilat events in a Webhook node with signature checks — with ready-to-import workflows.
Ready-made files
- mursilat-send-from-n8n.json: n8n → Mursilat (List numbers, Send template, Create tracked link).
- mursilat-webhook-to-n8n.json: Mursilat → n8n (Webhook, Verify signature, answer 200 or 401).
In n8n: Workflows → Import from file. Both are tested on n8n 2.47.2.
1. Get an API key
- Your plan must include the API (Developer, Growth or Business), else
403 API_ACCESS_NOT_IN_PLAN. - In Settings → API keys create a key with only the scopes you need:
numbers:read,messages:send,messages:read,links:write, pluswebhooks:readandwebhooks:writeto set the webhook through the API. - The key (
wsl_live_…) is shown once: copy it right away.
2. The n8n credential
| Field | Value |
|---|---|
| Credential type | ValueHeader Auth |
| Name | ValueAuthorization |
| Value | ValueBearer wsl_live_… |
In every HTTP Request node: Authentication = Generic Credential Type → Header Auth. Base URL: https://mursilat.com/api/v2, so GET /v2/me is https://mursilat.com/api/v2/me; try it first.
3. Send from n8n
- Settings: set your
numberId, the customerto(with country code) and the template name and language. - Send template:
POST /v2/messageswithtype: "template"and theIdempotency-Keyheader (required): the workflow usesn8n-{{ $execution.id }}-templateso a retry never sends twice. - Create tracked link:
POST /v2/linksreturns a tracked wa.me link; chats started from it sendconversation.attributed.
{
"numberId": "cm1…",
"to": "201001234567",
"type": "template",
"template": { "name": "order_shipped", "language": "ar", "params": ["Mona", "1042"] }
}Outside the 24-hour window only approved templates can be sent (409 CLOUD_API_WINDOW_CLOSED). For many recipients use POST /v2/campaigns with content.type: "template" instead of an n8n loop. The API has no contacts endpoints (privacy): keep customers in your own store from webhook events.
4. Receive events in n8n
- Webhook node:
POST, pathmursilat, Respond = Using 'Respond to Webhook' Node, and Raw Body = ON. - Activate the workflow and copy the Production URL (public https on port 443; localhost and port 5678 are refused).
- Register it:
PUT /v2/webhookwith{"url": "…/webhook/mursilat", "events": null}(or per number:PUT /v2/numbers/{numberId}/webhook). Thesecretis returned the first time only; lost it?POST /v2/webhook/rotate-secret. - Give n8n the secret: env var
MURSILAT_WEBHOOK_SECRET(self-hosted, withNODE_FUNCTION_ALLOW_BUILTIN=crypto) or inside the Code node (n8n Cloud). - Test with
POST /v2/webhook/testand checkGET /v2/webhooks/deliveries.
5. Verify the signature
Compute HMAC-SHA256 of "<t>.<raw body>" with the secret, compare it with v1 of X-Wasla-Signature in constant time, and reject a t older than 5 minutes. Answer 2xx within 10 seconds and drop duplicates by id.
// Node.js + Express. Use the RAW body: JSON.parse → JSON.stringify changes bytes and breaks the signature.
import crypto from 'node:crypto';
import express from 'express';
const app = express();
const SECRET = process.env.WASLA_WEBHOOK_SECRET;
const seen = new Set(); // use Redis/DB in production
function verifyWaslaSignature(rawBody, header, secret, toleranceSec = 300) {
if (!header || !secret) return false;
const parts = {};
for (const pair of header.split(',')) {
const i = pair.indexOf('=');
if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
}
const t = parts.t;
const v1 = parts.v1;
if (!/^\d+$/.test(t || '') || !/^[0-9a-f]{64}$/i.test(v1 || '')) return false;
// Reject old (replayed) or far-future timestamps.
if (Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > toleranceSec) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(t + '.')
.update(rawBody) // the RAW bytes exactly as received, not re-serialized JSON
.digest();
const received = Buffer.from(v1, 'hex');
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}
app.post('/webhooks/mursilat', express.raw({ type: 'application/json' }), (req, res) => {
if (!verifyWaslaSignature(req.body, req.get('X-Wasla-Signature'), SECRET)) {
return res.status(401).send('invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
res.sendStatus(200); // answer fast (within 10s); do the work after
if (seen.has(event.id)) return; // retries reuse the same event id
seen.add(event.id);
if (event.type === 'interactive.reply') {
console.log(event.data.reference, '→', event.data.reply.id);
}
});
app.listen(3000);<?php
// Use the RAW body (php://input), never a re-encoded json_decode() result.
function wasla_verify_signature(string $rawBody, string $header, string $secret, int $toleranceSec = 300): bool
{
$parts = [];
foreach (explode(',', $header) as $pair) {
$kv = explode('=', trim($pair), 2);
if (count($kv) === 2) {
$parts[$kv[0]] = $kv[1];
}
}
$t = $parts['t'] ?? '';
$v1 = $parts['v1'] ?? '';
if ($secret === '' || !ctype_digit($t) || !preg_match('/^[0-9a-f]{64}$/i', $v1)) {
return false;
}
// Reject old (replayed) or far-future timestamps.
if (abs(time() - (int) $t) > $toleranceSec) {
return false;
}
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
return hash_equals($expected, strtolower($v1)); // constant-time
}
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_WASLA_SIGNATURE'] ?? '';
if (!wasla_verify_signature($rawBody, $header, getenv('WASLA_WEBHOOK_SECRET') ?: '')) {
http_response_code(401);
exit('invalid signature');
}
$event = json_decode($rawBody, true);
http_response_code(200); // answer fast (within 10s)
// Retries reuse the same event id — store it and skip duplicates.
if ($event['type'] === 'interactive.reply') {
error_log($event['data']['reference'] . ' -> ' . $event['data']['reply']['id']);
}# Python 3 + Flask. Use the RAW body (request.get_data()), not request.json re-encoded.
import hashlib
import hmac
import json
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["WASLA_WEBHOOK_SECRET"]
def verify_wasla_signature(raw_body: bytes, header: str, secret: str, tolerance_sec: int = 300) -> bool:
parts = {}
for pair in (header or "").split(","):
key, sep, value = pair.strip().partition("=")
if sep:
parts[key] = value
t, v1 = parts.get("t", ""), parts.get("v1", "")
if not secret or not t.isdigit() or len(v1) != 64:
return False
# Reject old (replayed) or far-future timestamps.
if abs(time.time() - int(t)) > tolerance_sec:
return False
expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1.lower()) # constant-time
@app.post("/webhooks/mursilat")
def mursilat_webhook():
raw = request.get_data() # bytes exactly as received
if not verify_wasla_signature(raw, request.headers.get("X-Wasla-Signature", ""), SECRET):
abort(401)
event = json.loads(raw)
# Retries reuse the same event id — store it and skip duplicates.
if event["type"] == "interactive.reply":
print(event["data"]["reference"], "->", event["data"]["reply"]["id"])
return "", 200 # answer fast (within 10s)# Recompute a signature by hand (debugging). body.json = the raw request body, byte for byte.
# Header: X-Wasla-Signature: t=1760097603,v1=<hex>
T=1760097603
printf '%s.' "$T" | cat - body.json | openssl dgst -sha256 -hmac "$WASLA_WEBHOOK_SECRET" -hex
# → compare the hex digest with v1 (and check that T is within 5 minutes of now)6. Common errors
| Error | Fix |
|---|---|
401 API_KEY_REQUIRED | FixHeader Authorization with value Bearer wsl_live_…. |
403 SCOPE_REQUIRED | FixAdd the missing scope (details.required) to the key. |
403 IP_NOT_ALLOWED | Fixn8n calls from an IP outside the key allowlist. |
400 IDEMPOTENCY_KEY_REQUIRED | FixSend Idempotency-Key on POST /v2/messages, /v2/campaigns and /v2/otp. |
409 CLOUD_API_WINDOW_CLOSED | FixSend a template. |
409 TEMPLATE_NOT_APPROVED | FixWrong template name / language, or not APPROVED yet. |
422 SAFETY_SUPPRESSED | FixThe customer opted out. |
429 RATE_LIMITED | FixWait Retry-After seconds. |
URL_PRIVATE_ADDRESS / URL_PORT_NOT_ALLOWED | FixUse a public https URL on port 443. |
| n8n answers 401 | FixRaw Body is off, the secret is wrong, or the server clock is off. |