Python Example

Python's default json.dumps() formatting matches Aeropay's serialization, making it the most straightforward implementation.

import hmac
import json
from hashlib import sha256

# Step 1: Extract signature from header
received_signature = request.headers.get('ap-signature')

# Step 2: Parse the webhook body
body = json.loads(request.data)

# Step 3: Build payload for signing
# Include ALL fields from the body + add your registered webhook URL
payload = dict(body)
payload['url'] = 'https://your-registered-webhook-url.com'

# Step 4: Serialize to JSON (Python's default formatting matches Aeropay's)
payload_str = json.dumps(payload)

# Step 5: Compute expected signature
expected_signature = hmac.new(
    signing_key.encode('utf-8'),
    payload_str.encode('utf-8'),
    digestmod=sha256
).hexdigest()

# Step 6: Validate (use constant-time comparison)
is_valid = hmac.compare_digest(received_signature, expected_signature)

if is_valid:
    # Webhook is authentic - safe to process
    process_webhook(body)
else:
    # Invalid signature - reject
    return 'Unauthorized', 401