"""Framework-neutral verifier; pass raw request bytes BEFORE JSON parsing. After verification: transactionally insert event['id'] into a unique inbox, acknowledge 2xx promptly, then process asynchronously. This module does not implement durable deduplication and does not initiate any payment. """ import hashlib import hmac import json import time def verify_webhook(raw_body,headers,secret,*,now=None,tolerance=300): if not isinstance(raw_body,bytes) or not secret:raise ValueError('Raw bytes and signing secret required') h={str(k).lower():str(v) for k,v in headers.items()} timestamp=h.get('x-webhook-timestamp','') if not timestamp.isdigit():raise ValueError('Invalid timestamp') if abs((time.time() if now is None else now)-int(timestamp))>tolerance:raise ValueError('Stale notification') expected='sha256='+hmac.new(secret.encode(),timestamp.encode()+b'.'+raw_body,hashlib.sha256).hexdigest() if not hmac.compare_digest(expected,h.get('x-webhook-signature','')):raise ValueError('Invalid signature') event=json.loads(raw_body) if not isinstance(event,dict) or not event.get('id') or event['id']!=h.get('x-event-id') or event.get('type')!='order.updated' or not isinstance(event.get('data'),dict): raise ValueError('Invalid event envelope') return event