ربط مرسلات بـ n8n
ابعت رسايل واتساب من n8n بالـ API، واستقبل أحداث مرسلات في Webhook node وتأكد من التوقيع — بـ workflows جاهزة للاستيراد.
الملفات الجاهزة
- mursilat-send-from-n8n.json: من n8n لمرسلات: بيجيب أرقامك (
List numbers)، ويبعت قالب (Send template)، ويعمل رابط متتبَّع (Create tracked link). - mursilat-webhook-to-n8n.json: من مرسلات لـ n8n: بيستقبل الحدث (
Webhook)، ويتأكد من التوقيع (Verify signature)، ويرد بـ 200 أو 401.
في n8n: Workflows ← Import from file. الملفين متجربين على n8n 2.47.2.
1. هات الـ API key
- الباقة لازم يبقى فيها API (Developer أو Growth أو Business)، وإلا هيرجع
403 API_ACCESS_NOT_IN_PLAN. - من الإعدادات ← API keys اعمل مفتاح جديد بالـ Scopes اللي محتاجها بس:
numbers:readوmessages:sendوmessages:readوlinks:write، ولو هتضبط الويب هوك بالـ API:webhooks:readوwebhooks:write. - المفتاح (
wsl_live_…) بيظهر مرة واحدة: انسخه على طول.
2. الـ Credential في n8n
| الحقل | القيمة |
|---|---|
| Credential type | القيمةHeader Auth |
| Name | القيمةAuthorization |
| Value | القيمةBearer wsl_live_… |
في كل HTTP Request node: Authentication = Generic Credential Type ← Header Auth. الـ Base URL: https://mursilat.com/api/v2، يعني GET /v2/me هو https://mursilat.com/api/v2/me؛ جرّبه الأول.
3. n8n يبعت لمرسلات
- Settings: حط
numberIdبتاع رقمك وto(بكود الدولة) واسم ولغة القالب. - Send template:
POST /v2/messagesبـtype: "template"ومعاه HeaderIdempotency-Key(إجباري): الـ workflow بيستخدمn8n-{{ $execution.id }}-templateعشان إعادة المحاولة متبعتش مرتين. - Create tracked link:
POST /v2/linksبيرجع رابط wa.me متتبَّع؛ لما العميل يكتب منه بيوصلكconversation.attributed.
{
"numberId": "cm1…",
"to": "201001234567",
"type": "template",
"template": { "name": "order_shipped", "language": "ar", "params": ["منى", "1042"] }
}برا نافذة الـ 24 ساعة مينفعش غير Template معتمد (409 CLOUD_API_WINDOW_CLOSED). للإرسال لعدد كبير استخدم POST /v2/campaigns بـ content.type: "template" بدل Loop في n8n. الـ API مفيهوش Contacts (خصوصية): خزّن العملاء عندك من أحداث الويب هوك.
4. مرسلات تبعت لـ n8n
- Webhook node:
POST، Pathmursilat، Respond = Using 'Respond to Webhook' Node، و Raw Body = ON. - فعّل الـ workflow وانسخ الـ Production URL (https عام على 443؛ localhost والبورت 5678 مرفوضين).
- اضبطه:
PUT /v2/webhookبـ{"url": "…/webhook/mursilat", "events": null}(أو لرقم:PUT /v2/numbers/{numberId}/webhook). الـsecretبيرجع أول مرة بس؛ لو ضاع:POST /v2/webhook/rotate-secret. - حط الـ secret: متغير بيئة
MURSILAT_WEBHOOK_SECRET(self-hosted، معNODE_FUNCTION_ALLOW_BUILTIN=crypto) أو جوه Code node (n8n Cloud). - جرّب بـ
POST /v2/webhook/testوشوفGET /v2/webhooks/deliveries.
5. التحقق من التوقيع
احسب HMAC-SHA256 على "<t>.<raw body>" بالـ secret، قارن بـ v1 في X-Wasla-Signature بمقارنة ثابتة الوقت، وارفض t أقدم من 5 دقايق. رد بـ 2xx في أقل من 10 ثواني، وتجاهل الأحداث المكررة بالـ 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. أخطاء شائعة
| الخطأ | الحل |
|---|---|
401 API_KEY_REQUIRED | الحلالـ Header اسمه Authorization والقيمة Bearer wsl_live_…. |
403 SCOPE_REQUIRED | الحلضيف الـ Scope الناقص (details.required) للمفتاح. |
403 IP_NOT_ALLOWED | الحلn8n بيطلع من IP مش في الـ allowlist. |
400 IDEMPOTENCY_KEY_REQUIRED | الحلضيف Idempotency-Key في POST /v2/messages و /v2/campaigns و /v2/otp. |
409 CLOUD_API_WINDOW_CLOSED | الحلابعت Template. |
409 TEMPLATE_NOT_APPROVED | الحلاسم/لغة القالب غلط أو لسه مش APPROVED. |
422 SAFETY_SUPPRESSED | الحلالعميل لغى الاشتراك. |
429 RATE_LIMITED | الحلاستنى Retry-After ثانية. |
URL_PRIVATE_ADDRESS / URL_PORT_NOT_ALLOWED | الحلاستخدم رابط https عام على 443. |
| n8n بيرد 401 | الحلRaw Body مقفول أو الـ secret غلط أو ساعة السيرفر مش مظبوطة. |