AI-Assisted Coding Lab · Verify Signed Webhooks

45:00left of 45:00

Verify Signed Webhooks

The payment provider posts signed webhooks for every invoice event, and the billing service charges, emails, and writes the ledger on each one. The README has the provider's contract and the operational stakes. Build the receiver with the assistant, and judge each suggestion by what it would do in production as well as by the tests.

webhooks.py1 of 3

Files

webhooks.py

Python · Editable
import hashlib
import hmac
import json
class InvalidWebhook(Exception):
"""The request isn't a genuine, fresh delivery. Answer 400."""
def sign(secret, timestamp, body):
"""The provider's signature: hex HMAC-SHA256 of the timestamp, a dot, and the raw body."""
raise NotImplementedError
class WebhookReceiver:
"""Verifies the payment provider's webhooks and hands each event to handler once."""
def __init__(self, secret, handler, clock, tolerance_s=300):
self.secret = secret # bytes
self.handler = handler
self.clock = clock
self.tolerance_s = tolerance_s
self.seen = set() # ids of events already handled
def receive(self, headers, body):
"""Returns "handled" or "duplicate". Raises InvalidWebhook for a delivery to reject."""
timestamp = headers.get("Webhook-Timestamp", "")
signature = headers.get("Webhook-Signature", "")
expected = sign(self.secret, timestamp, body)
event = json.loads(body)
self.handler(event)
return "handled"
def respond(receiver, headers, body):
"""The HTTP status to answer a delivery with."""
raise NotImplementedError

Test Output

No runs yet.

Assistant

Scripted
  1. Send the first prompt to start.

Next Prompt

Write sign to match the provider's scheme.