Skip to content

Webhooks ​

MsGine posts an event to your URL when a message is sent, delivered, read or fails, and when someone sends you a WhatsApp message. See the event list for every event type.

Register a URL ​

ts
const { webhook, secret } = await msgine.webhooks.create({
  url: 'https://example.com/msgine/webhooks',
  events: ['sms.delivered', 'sms.failed', 'whatsapp.received'],
});
python
created = msgine.webhooks.create(
    url="https://example.com/msgine/webhooks",
    events=["sms.delivered", "sms.failed", "whatsapp.received"],
)
secret = created["secret"]
go
created, err := client.Webhooks.Create(ctx, msgine.CreateWebhookParams{
	URL:    "https://example.com/msgine/webhooks",
	Events: []string{"sms.delivered", "sms.failed", "whatsapp.received"},
})
secret := created.Secret

Save secret where your server can read it. It is shown only once; webhooks.rotateSecret issues a new one. The URL must be public HTTPS or HTTP: private and internal addresses are refused.

webhooks.test(id) sends a webhook.test event, and webhooks.deliveries(id) lists recent attempts with the status code your endpoint returned.

Verify every delivery ​

Each request carries X-MsGine-Signature: t=<timestamp>,v1=<signature>. The verify function checks the signature against the raw request body, refuses deliveries more than five minutes old, and returns the parsed event. Read the body as bytes: a body that was parsed and serialised again will not match.

ts
import express from 'express';
import { verifyWebhook, WebhookVerificationError } from '@msgine/sdk';

const app = express();

app.post('/msgine/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = verifyWebhook(req.body, req.header('x-msgine-signature'), process.env.MSGINE_WEBHOOK_SECRET!);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return res.sendStatus(400);
    throw error;
  }

  if (event.event === 'sms.delivered') markDelivered(event.messageId);
  res.sendStatus(200);
});
python
from fastapi import FastAPI, Header, HTTPException, Request
from msgine import WebhookVerificationError, verify_webhook

app = FastAPI()

@app.post("/msgine/webhooks")
async def msgine_webhook(request: Request, x_msgine_signature: str | None = Header(None)):
    try:
        event = verify_webhook(await request.body(), x_msgine_signature, os.environ["MSGINE_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        raise HTTPException(status_code=400)

    if event["event"] == "sms.delivered":
        mark_delivered(event["messageId"])
    return {"ok": True}
go
http.HandleFunc("/msgine/webhooks", func(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	event, err := msgine.VerifyWebhook(body, r.Header.Get("X-MsGine-Signature"), os.Getenv("MSGINE_WEBHOOK_SECRET"), 0)
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	if event.Event == "sms.delivered" {
		markDelivered(event.MessageID)
	}
	w.WriteHeader(http.StatusOK)
})

Handling events well ​

  • Answer with a 2xx quickly and do slow work afterwards. MsGine waits 10 seconds, then retries with backoff.
  • Expect the same event more than once and handle it once: use X-MsGine-Delivery or the message ID and event type as the key.
  • Events can arrive out of order. A sms.delivered can come before your own record of the send is saved.
  • While you rotate a secret, a header can carry more than one v1 signature; verification accepts the delivery when any of them matches.

Released under the MIT License.