Standard Webhooks

1.0.1 · active · verified Sat Apr 11

Standard Webhooks is a Python library for securely handling webhooks conforming to the Standard Webhooks specification. It provides functionalities for signature verification, content encryption, and replay protection, ensuring the authenticity and integrity of incoming webhook payloads. The current version is 1.0.1, with active development and maintenance.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Webhook` class with a secret and verify an incoming webhook request. It shows the expected input types (headers as dict, body as bytes) and how to handle potential `WebhookVerificationError` exceptions, which are critical for secure webhook processing. Remember to load your secret securely from environment variables or a secret manager and ensure it's provided as bytes.

import os
from standardwebhooks import Webhook, WebhookVerificationError

# In a real application, the secret should be securely loaded from environment variables or a secret store.
# It MUST be bytes.
WEBHOOK_SECRET = os.environ.get('STANDARDWEBHOOKS_SECRET', 'whsec_testsecretforlocaldevelopmentonly').encode('utf-8')

# Example incoming webhook data (replace with actual request data)
headers = {
    'Webhook-Id': 'msg_00000000000000000000000000',
    'Webhook-Timestamp': '2024-04-10T12:00:00Z',
    'Webhook-Signature': 'v1,sig_00000000000000000000000000',
    'Content-Type': 'application/json'
}
body = b'{"key": "value"}' # Body must be bytes

# Initialize the Webhook handler with your secret
webhook = Webhook(WEBHOOK_SECRET)

try:
    # Verify the incoming webhook
    # In a web framework, you would pass request.headers and request.body
    verified_data = webhook.verify(headers=headers, body=body)
    print("Webhook verified successfully!")
    print("Payload:", verified_data)
except WebhookVerificationError as e:
    print(f"Webhook verification failed: {e}")
    # Important: Log the error but do not expose details to the client.
    # Return a 400 or 401 status code.
except Exception as e:
    print(f"An unexpected error occurred: {e}")

# To simulate a successful verification, you'd need a valid signature for the given secret, body, id, and timestamp.
# The example above uses placeholder values for demonstration.

view raw JSON →