Webhooks push events to registered URLs — sign with HMAC and respond 200 fast, process async.
Webhooks
import httpx, json, hmac, hashlib
# Send webhook with HMAC signature
def send_webhook(url, event, data, secret):
payload = json.dumps({"event":event,"data":data})
sig = hmac.new(secret.encode(),payload.encode(),hashlib.sha256).hexdigest()
httpx.post(url, content=payload, headers={
"Content-Type": "application/json",
"X-Signature": "sha256=" + sig,
})
# Receive and verify
@app.post("/webhooks/stripe")
async def receive(req: Request, bg: BackgroundTasks):
body = await req.body()
sig = req.headers.get("X-Signature","")
exp = "sha256=" + hmac.new(SECRET.encode(),body,hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, exp):
raise HTTPException(400,"Invalid signature")
bg.add_task(process, json.loads(body))
return {"received":True} # return 200 fast!