About this page · Updated 2026-11-28 00:36 UTC
What this page is: Email delivery webhooks for Motorical — configure endpoints, validate X-Motorical-Signature, process bounce and delivery events.
How far to trust this page: the build checked 1 names, paths, tools, scopes and error codes against the real product (0 do not match). Reviewed claim by claim on 2026-10-22 (documentation truth audit).
Updated 2026-11-28 00:36 UTCLatest change: Webhooks: signed timestamps protect against replayed deliveriesRecently updated pages
Webhooks
Use Motorical delivery webhooks to push real-time email events to your server — deliveries, bounces, complaints, and more.
Managing Webhooks
All webhook endpoints require the webhooks.manage scope.
List Webhooks
curl -H "Authorization: Bearer $TOKEN" \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks"
Response: Array of webhook endpoints with id, url, events, enabled, failure_count, last_delivery_at, and created_at.
Create a Webhook
curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/webhook","events":["message.delivered","message.bounced"]}' \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks"
If events is omitted, the webhook subscribes to all six events listed under Available Events. Pass an explicit events array for a subset — in particular, omit message.processed and message.deferred unless your application handles intermediate states.
The 201 response returns the signing secret once — it is never retrievable again:
{
"success": true,
"data": {
"id": "9c2f0d81-4b6e-4d2a-9f11-3a7e5c0b8d42",
"url": "https://example.com/webhook",
"events": ["message.delivered", "message.bounced"],
"enabled": true,
"created_at": "2026-08-25T12:00:00.000Z",
"secret": "…48 hex chars…",
"secretMasked": "ab12…"
},
"message": "Webhook created. The full \"secret\" is shown once — store it now for signature verification (X-Motorical-Signature)."
}
Store data.secret immediately. It is the key for the HMAC-SHA256 verification below; losing it means deleting and recreating the webhook.
Update a Webhook
curl -X PUT -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/new-url","enabled":true}' \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks/$WEBHOOK_ID"
Updatable fields: url, events (array), enabled (boolean).
Delete a Webhook
curl -X DELETE -H "Authorization: Bearer $TOKEN" \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks/$WEBHOOK_ID"
Test a Webhook
Send a test delivery to verify your endpoint is reachable:
curl -X POST -H "Authorization: Bearer $TOKEN" \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks/$WEBHOOK_ID/test"
Returns 202 Accepted with a queued test delivery.
Delivery History
View recent webhook deliveries with status and latency:
curl -H "Authorization: Bearer $TOKEN" \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks/$WEBHOOK_ID/deliveries?limit=50"
Parameters:
| Parameter | Description |
|---|---|
limit | Max deliveries to return (1–200, default 50) |
Response: Array of deliveries with eventType, status, attempts, error, latencyMs, createdAt, and deliveredAt.
Signature Verification
Every delivery is a POST with these headers:
| Header | Value |
|---|---|
X-Motorical-Timestamp | When the delivery was signed, in Unix seconds |
X-Motorical-Signature-V2 | HMAC-SHA256 of <timestamp>.<raw request body>, keyed with the webhook's secret, hex-encoded. Verify this one. |
X-Motorical-Signature | v1: HMAC-SHA256 of the raw body alone. Still sent so existing receivers keep working; it does not protect against replays. |
X-Motorical-Event | The event type, for example message.delivered |
Content-Type | application/json |
User-Agent | Motorical-Webhooks/1.0 |
Verify the v2 signature before you trust the payload:
- Use the exact bytes you received, not JSON you parsed and serialised again (whitespace, key order or escaping can differ, and a valid delivery would then fail).
- Reject a timestamp more than 300 seconds from your clock. Because the timestamp is signed, a captured delivery cannot be replayed later, and the timestamp cannot be changed without breaking the signature.
- Compare in constant time, and treat a missing or wrong-length header as a failed check, not an error. Answer
401when the check fails.
A delivery that is retried is signed again with a new timestamp, so it passes. Process each event once anyway (remember the message id together with the event type), because a retry after a timeout can repeat an event you already handled.
Each sample below runs in our test suite against the signing code our webhook worker uses, including a replayed and a tampered delivery.
- Node.js
- Python
- Go
- PHP
- Ruby
const crypto = require('crypto');
// rawBody: the exact bytes of the request body (a Buffer), before any JSON parsing.
// Headers: X-Motorical-Timestamp and X-Motorical-Signature-V2. toleranceSeconds: how far the timestamp may be from now.
function verifyMotoricalSignature(rawBody, timestampHeader, signatureHeader, secret, toleranceSeconds = 300) {
const timestamp = Number(timestampHeader);
if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false; // stale or replayed
const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest('hex');
const received = String(signatureHeader || '');
if (received.length !== expected.length) return false;
return crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
}
// Express: keep the raw body for this route.
// app.post('/webhooks/motorical', express.raw({ type: 'application/json' }), (req, res) => {
// const ok = verifyMotoricalSignature(req.body, req.get('X-Motorical-Timestamp'), req.get('X-Motorical-Signature-V2'), process.env.MOTORICAL_WEBHOOK_SECRET);
// if (!ok) return res.status(401).end();
// const event = JSON.parse(req.body.toString('utf8'));
// res.status(200).end(); // answer fast, then process event asynchronously
// });
import hashlib
import hmac
import time
def verify_motorical_signature(raw_body: bytes, timestamp_header: str, signature_header: str, secret: str, tolerance_seconds: int = 300) -> bool:
"""raw_body: the exact request body bytes, before any JSON parsing.
Headers: X-Motorical-Timestamp and X-Motorical-Signature-V2."""
try:
timestamp = int(timestamp_header)
except (TypeError, ValueError):
return False
if abs(time.time() - timestamp) > tolerance_seconds:
return False # stale or replayed
expected = hmac.new(secret.encode(), str(timestamp).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature_header or "")
# Flask:
# @app.post("/webhooks/motorical")
# def receive_webhook():
# h = request.headers
# if not verify_motorical_signature(request.get_data(), h.get("X-Motorical-Timestamp"), h.get("X-Motorical-Signature-V2", ""), SECRET):
# abort(401)
# event = request.get_json()
# return "", 200 # answer fast, then process event asynchronously
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"math"
"strconv"
"time"
)
// rawBody: the exact request body bytes (io.ReadAll(r.Body)), before any JSON decoding.
// Headers: X-Motorical-Timestamp and X-Motorical-Signature-V2.
func VerifyMotoricalSignature(rawBody []byte, timestampHeader, signatureHeader, secret string, toleranceSeconds float64) bool {
ts, err := strconv.ParseInt(timestampHeader, 10, 64)
if err != nil || math.Abs(float64(time.Now().Unix()-ts)) > toleranceSeconds {
return false // stale or replayed
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(ts, 10) + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(signatureHeader))
}
// In an http.HandlerFunc:
// body, _ := io.ReadAll(r.Body)
// if !VerifyMotoricalSignature(body, r.Header.Get("X-Motorical-Timestamp"), r.Header.Get("X-Motorical-Signature-V2"), secret, 300) {
// w.WriteHeader(http.StatusUnauthorized); return
// }
// w.WriteHeader(http.StatusOK) // answer fast, then process the event asynchronously
// $rawBody: the exact request body, file_get_contents('php://input'), before json_decode.
// Headers: X-Motorical-Timestamp and X-Motorical-Signature-V2.
function verifyMotoricalSignature(string $rawBody, string $timestampHeader, string $signatureHeader, string $secret, int $toleranceSeconds = 300): bool
{
if (!ctype_digit($timestampHeader) || abs(time() - (int) $timestampHeader) > $toleranceSeconds) {
return false; // stale or replayed
}
$expected = hash_hmac('sha256', $timestampHeader . '.' . $rawBody, $secret);
return hash_equals($expected, $signatureHeader);
}
// $raw = file_get_contents('php://input');
// $ok = verifyMotoricalSignature($raw, $_SERVER['HTTP_X_MOTORICAL_TIMESTAMP'] ?? '', $_SERVER['HTTP_X_MOTORICAL_SIGNATURE_V2'] ?? '', getenv('MOTORICAL_WEBHOOK_SECRET'));
// if (!$ok) { http_response_code(401); exit; }
// $event = json_decode($raw, true);
// http_response_code(200); // answer fast, then process the event asynchronously
require "openssl"
# raw_body: the exact request body (request.raw_post in Rails, request.body.read in Rack), before JSON parsing.
# Headers: X-Motorical-Timestamp and X-Motorical-Signature-V2.
# In Rails you can compare with ActiveSupport::SecurityUtils.secure_compare instead of the loop below.
def verify_motorical_signature(raw_body, timestamp_header, signature_header, secret, tolerance_seconds = 300)
return false unless timestamp_header.to_s.match?(/\A\d+\z/)
return false if (Time.now.to_i - timestamp_header.to_i).abs > tolerance_seconds # stale or replayed
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp_header}.#{raw_body}")
received = signature_header.to_s
return false unless expected.bytesize == received.bytesize
expected.bytes.zip(received.bytes).reduce(0) { |acc, (a, b)| acc | (a ^ b) }.zero?
end
Available Events
| Event | Description |
|---|---|
message.processed | Accepted by the gateway and handed to delivery — an intermediate event, not a final outcome |
message.deferred | Delivery temporarily delayed; a retry is scheduled |
message.delivered | Accepted by the recipient's server |
message.bounced | Bounced (hard or soft) |
message.failed | Permanent delivery failure |
message.complained | Recipient marked the email as spam |
Monitoring Webhook Health
Check delivery statistics for a webhook endpoint:
curl -H "Authorization: Bearer $TOKEN" \
"$BASE_URL/motor-blocks/$BLOCK_ID/webhooks/$WEBHOOK_ID/stats?hours=24"
Response includes: delivered count, failed count, queued count, failure rate, and average latency.
Best Practices
- Respond quickly — return a
2xxresponse within 10 seconds (the delivery times out after that) - Process asynchronously — queue webhook payloads for background processing
- Verify signatures — always validate
X-Motorical-Signature - Handle retries — Motorical retries a failed delivery after 1, 5, 15 and 60 minutes, and disables the webhook after 10 consecutive failures (a success resets the count)
- Use HTTPS — webhook URLs must use TLS