python
40 lines · 7 steps
Verifying signed payment webhooks in Flask
A Flask blueprint authenticates incoming payment webhooks with an HMAC signature before queuing the event for async processing.
Explained by
highlit
1import hashlib
2import hmac
3import os
4
5from flask import Blueprint, abort, current_app, jsonify, request
6
7from .tasks import process_payment_event
8
9webhooks = Blueprint("webhooks", __name__)
10
11
12def verify_signature(payload: bytes, header: str) -> bool:
13 if not header:
14 return False
15 try:
16 timestamp, received = (part.split("=", 1)[1] for part in header.split(","))
17 except (ValueError, IndexError):
18 return False
19
20 secret = current_app.config["WEBHOOK_SIGNING_SECRET"].encode()
21 signed = f"{timestamp}.{payload.decode()}".encode()
22 expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
23 return hmac.compare_digest(expected, received)
24
25
26@webhooks.route("/webhooks/payments", methods=["POST"])
27def handle_payment_webhook():
28 payload = request.get_data()
29 signature = request.headers.get("X-Signature", "")
30
31 if not verify_signature(payload, signature):
32 current_app.logger.warning("Rejected webhook with invalid signature")
33 abort(400, description="Invalid signature")
34
35 event = request.get_json(silent=True)
36 if event is None or "type" not in event:
37 abort(400, description="Malformed payload")
38
39 process_payment_event.delay(event["id"], event["type"])
40 return jsonify(received=True), 202
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Always verify a webhook's signature against a shared secret before trusting its payload.
- 2Use constant-time comparison like hmac.compare_digest to avoid leaking secrets through timing.
- 3Acknowledge webhooks fast by offloading real work to a background task queue.
Related explainers
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 steps
python
def is_valid_card_number(number: str) -> bool: digits = [int(c) for c in number if c.isdigit()] if len(digits) < 13 or len(digits) > 19:
Validating card numbers with the Luhn check
checksum
validation
luhn-algorithm
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/verifying-signed-payment-webhooks-in-flask-explained-python-1706/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.