Stripe Webhook Signature Verification Handler – Timestamp Header
Clear professional description of the code solution
Task: Create a complete, production‑ready Stripe webhook signature verification handler in Python 3.11 (or a language of your choice, but default to Python). The handler must securely verify incoming Stripe webhook requests, parse the event payload, and provide clear error handling. Include comprehensive inline documentation, type hints, and a usage example. Additionally, supply a full suite of unit tests (using pytest) that cover all success and failure scenarios, and a short README snippet showing how to integrate the handler into a typical web framework (e.g., Flask or FastAPI).
Requirements:
-
Core Functionality
- Implement a function
verify_stripe_signature(payload: bytes, sig_header: str, secret: str, tolerance: int = 300) -> dictthat:- Parses the
Stripe-Signatureheader to extract the timestamp (t) and one or more signatures (v1). - Validates that the timestamp is within
toleranceseconds of the current UTC time. - Computes the HMAC‑SHA256 signature of the string
"t.{payload}"using the providedsecret. - Performs a constant‑time comparison between the computed signature and each
v1signature from the header. - Returns the decoded JSON payload as a Python dictionary if verification succeeds.
- Raises a custom exception
StripeSignatureVerificationErrorwith an informative message for any failure (missing header, malformed header, timestamp out of range, signature mismatch, JSON decode error, etc.).
- Parses the
- Implement a function
-
Helper Types & Exceptions
- Define a
@dataclassnamedStripeSignatureComponentswith fieldstimestamp: intandsignatures: List[str]. - Define the custom exception class
StripeSignatureVerificationError(RuntimeError).
- Define a
-
Usage Example
- Provide a short, runnable example showing how to use the function inside a Flask route (
/webhook) and a FastAPI endpoint. Include how to retrieve the raw request body and theStripe-Signatureheader.
- Provide a short, runnable example showing how to use the function inside a Flask route (
-
Unit Tests (pytest)
- Create a file
test_stripe_signature.pycontaining at least the following tests:- Successful verification with a valid signature.
- Failure when the
Stripe-Signatureheader is missing. - Failure when the header cannot be parsed.
- Failure when the timestamp is older than
tolerance. - Failure when the computed signature does not match any
v1signature. - Failure when the payload is not valid JSON.
- Use fixtures to generate a deterministic secret and payload, and to compute a correct signature for the success case.
- Ensure tests run in isolation and do not require external network calls.
- Create a file
-
README Snippet
- Provide a concise markdown section (≤ 150 words) titled “Integrating the Stripe Signature Verifier” that explains:
- Installing required dependencies (
pip install stripe cryptography pytestetc.). - Importing the verifier.
- Adding the verification step to a webhook endpoint.
- Handling
StripeSignatureVerificationError.
- Installing required dependencies (
- Provide a concise markdown section (≤ 150 words) titled “Integrating the Stripe Signature Verifier” that explains:
-
Code Quality
- Use type hints throughout.
- Follow PEP 8 style guidelines.
- Include docstrings for all public objects.
- Use
hmac.compare_digestfor constant‑time comparison. - Do not hard‑code any secret; accept it as a parameter.
Expected Output Format:
- File 1:
stripe_signature_verifier.py– contains the implementation, helper dataclass, exception, and usage examples (as aif __name__ == "__main__":block or separate functions). - File 2:
test_stripe_signature.py– full pytest suite as described. - File 3:
README.md– the integration snippet.
Present each file as a separate fenced code block with the appropriate language tag (python for the first two, markdown for the README). Ensure the code blocks are ready to be copied verbatim into a project.
Related Prompts
More prompts in Coding & Development
This Prompt Ads Sequential Function Calling To Models Other Than GPT 0613
This prompt ads sequential function calling to models other than GPT-0613
Create a personalized workout routine
Tailor a workout routine specifically designed for individual fitness goals
GODMODE CHEATCODE
God Writes You a Letter Today. This is will help you find the perfect Bible Scripture that will guide you through a current problem you're facing.
Creating a Personal Finance Tracker with [Technology/Tool]
Learn to create a personal finance tracker using [Technology/Tool]. Get code samples and budgeting tips.
Build an entire application using bubble.io with ChatGPT4
Build an entire app with bubble.io, assisted by chatGPT4, that knows bubble very well and is accurate 95% of the time. This prompt will help you maximize the quality of chatGPT assistance. Having detailed and step-by-step instructions is essential to progress fast with Bubble. This initial prompt will help you get started on a good basis. Follow it because I will make it even better.
Become LawyerGPT
Are you in a legal bind? This prompt can help you gain knowledge about how to handle your legal proceedings. DISCLAIMER: Please meet with a real lawyer to discuss your options.