import hmac
import hashlib
from typing import Optional
from fastapi import Request, Header, HTTPException
async def webhook_handler(
request_obj: Request,
x_webhook_signature: Optional[str] = Header(None, alias="X-Webhook-Signature"),
x_webhook_timestamp: Optional[str] = Header(None, alias="X-Webhook-Timestamp")
):
# Your webhook secret from Dari dashboard
webhook_secret = "wh_live_XDmJ8FidjSgzZTBLxX0U7gKfJSo3baaQUiYcCkeu9Js"
raw_body = await request_obj.body()
payload_str = raw_body.decode('utf-8')
if x_webhook_signature and x_webhook_timestamp:
signature = x_webhook_signature.replace('sha256=', '')
signature_payload = f"{x_webhook_timestamp}.{payload_str}"
expected_signature = hmac.new(
webhook_secret.encode('utf-8'),
signature_payload.encode('utf-8'),
hashlib.sha256
).hexdigest()
is_valid = hmac.compare_digest(signature, expected_signature)
if not is_valid:
raise HTTPException(status_code=401, detail="Invalid webhook signature")
return {"message": "Webhook verified and processed"}
else:
return {"message": "Webhook received without verification"}