Verify webhook signatures in Python
The Python SDK has one webhook function, verify_webhook_signature. It checks the X-Webhook-Signature header (sha256=<hex>, an HMAC-SHA256 of the raw body using your webhook secret). It does not create or list webhooks.
What does verify_webhook_signature take?
verify_webhook_signature(payload: str | bytes, signature: str, secret: str) -> boolPass the exact raw request body, not a re-serialized dict. The comparison is constant time. The sha256= prefix is optional. Pass a string for signature: a missing header (None) raises AttributeError, so default it to "".
How do I verify a delivery in Flask?
import json, os
from flask import Flask, request, abort
from socifyr import verify_webhook_signature
app = Flask(__name__)
@app.post("/webhooks/socifyr")
def socifyr_webhook():
raw = request.get_data() # bytes, exactly as received
sig = request.headers.get("X-Webhook-Signature", "")
if not verify_webhook_signature(raw, sig, os.environ["WEBHOOK_SECRET"]):
abort(401)
event = json.loads(raw)
print(event["event"], event["deliveryId"])
return "", 204How do I verify a delivery in FastAPI?
import json, os
from fastapi import FastAPI, Request, HTTPException
from socifyr import verify_webhook_signature
app = FastAPI()
@app.post("/webhooks/socifyr")
async def socifyr_webhook(request: Request):
raw = await request.body()
sig = request.headers.get("x-webhook-signature", "")
if not verify_webhook_signature(raw, sig, os.environ["WEBHOOK_SECRET"]):
raise HTTPException(status_code=401)
event = json.loads(raw)
return {"received": event["event"]}The payload fields are event, payload, timestamp and deliveryId. See webhook events for each event's payload.
How do I create the webhook itself?
The Python SDK cannot. Create it in the dashboard, with the TypeScript SDK, or with the REST API. Store the secret returned at creation.
FAQ
Is there a replay window check?
Not in the SDK. Compare the payload timestamp to the current time yourself, and de-duplicate on deliveryId.