Maintaining real-time visibility over revenue operations requires instant alerting when payments succeed or fail. By building a custom Stripe-to-Telegram webhook notification daemon in Python, engineering and finance teams get immediate, cryptographically verified mobile alerts for failed recurring subscriptions, high-value invoice settlements, and dispute notices—completely bypassing expensive notification SaaS tools.
In this technical implementation guide, we construct a production-ready Python service using FastAPI, verify incoming Stripe cryptographic signatures, format Markdown alerts with direct action links, and deploy the daemon to a hardened cloud container.
1. Event Flow Architecture: Stripe to Telegram
| Phase | Component | Security / Operational Requirement |
|---|---|---|
| 1. Webhook Emission | Stripe Cloud Infrastructure | Emits signed POST payload with Stripe-Signature timestamp header. |
| 2. Signature Verification | Python FastAPI Webhook Receiver | Validates HMAC SHA-256 signature against whsec_... secret to prevent spoofing. |
| 3. Message Formatting | Alert Template Engine | Extracts customer email, amount due, currency, and hosted invoice URL. |
| 4. Telegram Dispatch | Telegram Bot API (HTTPS) | Dispatches formatted Markdown notification to private team leadership channel. |
2. Complete Python Implementation Code
Below is the production-tested Python service implementation with full error handling and asynchronous Telegram message dispatching:
# server.py
import os
import httpx
import stripe
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
app = FastAPI()
STRIPE_API_KEY = os.environ["STRIPE_API_KEY"]
STRIPE_WEBHOOK_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"]
TELEGRAM_BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
stripe.api_key = STRIPE_API_KEY
async def send_telegram_alert(text: str):
# Asynchronously dispatches Markdown alerts to Telegram channel.
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
"chat_id": TELEGRAM_CHAT_ID,
"text": text,
"parse_mode": "Markdown",
"disable_web_page_preview": False
}
async with httpx.AsyncClient() as client:
try:
r = await client.post(url, json=payload, timeout=8.0)
r.raise_for_status()
except Exception as e:
print(f"Telegram dispatch failed: {e}")
@app.post("/api/stripe-webhook")
async def stripe_webhook(request: Request, background_tasks: BackgroundTasks):
payload = await request.body()
sig_header = request.headers.get("stripe-signature")
if not sig_header:
raise HTTPException(status_code=400, detail="Missing Stripe-Signature header")
try:
event = stripe.Webhook.construct_event(
payload, sig_header, STRIPE_WEBHOOK_SECRET
)
except (ValueError, stripe.error.SignatureVerificationError) as e:
raise HTTPException(status_code=400, detail="Invalid signature verification")
event_type = event["type"]
obj = event["data"]["object"]
# 1. Invoice Payment Failed (High Priority Churn Alert)
if event_type == "invoice.payment_failed":
email = obj.get("customer_email", "N/A")
amount = obj.get("amount_due", 0) / 100
currency = obj.get("currency", "usd").upper()
invoice_url = obj.get("hosted_invoice_url", "https://dashboard.stripe.com")
msg = (
"🚨 *STRIPE PAYMENT FAILED*\n\n"
f"👤 *Customer:* `{email}`\n"
f"💳 *Amount Due:* `${amount:,.2f} {currency}`\n"
f"⚠️ *Failure Reason:* {obj.get('last_finalization_error', {}).get('message', 'Card declined')}\n\n"
f"🔗 [Open Hosted Invoice]({invoice_url})"
)
background_tasks.add_task(send_telegram_alert, msg)
# 2. Invoice Payment Succeeded (Revenue Alert)
elif event_type == "invoice.payment_succeeded":
email = obj.get("customer_email", "N/A")
amount = obj.get("amount_paid", 0) / 100
currency = obj.get("currency", "usd").upper()
msg = (
"💰 *STRIPE PAYMENT COLLECTED*\n\n"
f"👤 *Customer:* `{email}`\n"
f"💵 *Amount Collected:* `${amount:,.2f} {currency}`\n"
f"✅ *Status:* Paid in Full"
)
background_tasks.add_task(send_telegram_alert, msg)
return JSONResponse(content={"received": True}, status_code=200)
3. Production Failure Modes & Telegram API Limits
- Telegram Bot API Rate Limiting: Telegram enforces a hard limit of 30 messages per second across all chats and 1 message per second inside a single group chat. If an e-commerce flash sale processes 200 orders in 3 seconds, unthrottled alerts will trigger HTTP
429 Too Many Requests. Remedy: Always buffer messages through an asynchronous background queue (such as Redis Celery or BullMQ) with rate smoothing. - Signature Verification Failures: In frameworks like Express or FastAPI, reading the request body as parsed JSON before passing it to Stripe SDK invalidates the cryptographic signature. Remedy: Always pass the raw, unparsed byte string directly into
stripe.Webhook.construct_event().
Frequently Asked Questions (FAQs)
How do I test Stripe webhooks locally?
Install the official Stripe CLI and run stripe listen --forward-to localhost:8000/api/stripe-webhook. The CLI outputs a temporary whsec_... signing secret and allows you to trigger test events via stripe trigger invoice.payment_failed.
Can I route alerts to different Telegram topics in a supergroup?
Yes. Telegram Supergroups support forum topics. By passing the message_thread_id parameter in your Telegram sendMessage payload, you can route successful payments to a #revenue topic and failed charges to an #urgent-collections topic.
Editorial Disclosure: Zelobiz publishes independent engineering benchmarks and architectural evaluations. We may receive affiliate compensation when you subscribe to partner hosting services through our links at no additional cost to you.