A customer pays, the money lands, and someone on your side emails them a PDF invoice or certificate by hand. That works for ten orders a week. At a hundred it breaks, and the first thing that breaks is not the PDF — it is the assumption that a confirmed payment means you can issue the document right away.
The result of this build: a payment webhook fires, your service verifies the signature, matches the payment to a record in your own database, generates a PDF from a template, emails it, and can re-issue the same document on request — every step written to an event log. You know it works when a test payment produces exactly one PDF, a replayed webhook produces zero new PDFs, and a forged body produces a rejection in the log.
Here is one concrete case to hang the whole build on. A small training company sells a course completion certificate. A student pays, the webhook arrives, a PDF goes out. One Tuesday the webhook arrives twice — the payment provider retries because your server was slow to answer — and the student gets two certificates with different numbers. Same evening, a webhook with a copied body but no valid signature shows up and, because the first version of the handler trusted anything that reached the URL, a certificate is issued for a payment that never happened. Both failures come from the same mistaken model: payment as permission instead of payment as an event.
What you are actually building, and what it refuses to do
The build has five moving parts, and each one exists because the event model needs it: More on the topic: “No API? Build a Webhook Bridge to Your Messenger”.
- A receiving endpoint that accepts a webhook and does nothing else yet.
- A signature check that rejects anything not signed by the provider's secret.
- A write to your own database: the payment record and its status, keyed by the provider's payment ID.
- A PDF generator that fills a template with the payer's data from that database record.
- A delivery step (email) plus a re-issue path that produces the same document again on demand.
What it refuses to do: issue a document on the strength of a webhook body alone, and issue two documents for one payment ID. Those two refusals are the design. More on the topic: “Bank Webhook Captures Invoice Payment in CRM Without Losses”.
Step 1: the receiving endpoint — AI writes it, you check what it does on a bad request
Ask the agent for a single HTTP handler that accepts a POST, reads the raw body before any JSON parsing, and returns 200 quickly while pushing the real work to a queue or a background task. The raw body matters: signature verification runs over the exact bytes the provider sent, and a framework that parses and re-serializes JSON will change the bytes and break the check.
Your check as the human: send a completely malformed body to the endpoint and confirm it does not 500 and does not crash the worker. Send a valid request and confirm the endpoint answers in well under the provider's timeout — most providers retry if you are slow, and retries are exactly the duplicates you are trying to avoid.
Two things to confirm in the provider's documentation rather than trusting the agent: which header carries the signature and what exactly is signed (the raw body, a timestamp plus body, a hash of both). These differ between providers and the agent will guess if you let it.
The catch in the async handoff. If the endpoint returns 200 before the unique-key insert has run, two rapid retries can both be accepted and both enqueue work before either insert lands. The unique key still saves you, but only if the insert happens in the worker, not in the request handler — and only if the worker treats "row already existed" as "do nothing." So the rule is: the endpoint's only job is verify-and-enqueue; the insert and the new-row check live together in the worker, in one transaction. If you would rather keep the insert in the handler, do that and skip the queue for the insert step — but then the handler is doing database work before it answers, and you must keep that work fast enough to beat the provider's timeout. Pick one; do not split the insert and the new-row check across the two.
Step 2: signature check — the one place you do not let the AI improvise
This is a short step with a hard rule: compute the expected signature with the provider's secret over the raw body, compare it in constant time, and reject with a 4xx on mismatch. Never compare with == on strings in a way that leaks timing, and never skip the check because "it's behind HTTPS anyway" — HTTPS protects the transport, not the authenticity of a body someone POSTs to your URL.
# requests==2.31.0, Flask==3.0.0
import hmac, hashlib
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = b"whsec_from_provider_dashboard"
@app.post("/webhook/payment")
def payment_webhook():
raw = request.get_data() # raw bytes, before JSON parsing
sent = request.headers.get("X-Signature", "")
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sent):
abort(401)
# ... hand off to step 3
return "", 200
The header name and the exact construction of expected are placeholders — replace them with what the provider documents. What you keep is the shape: raw bytes in, constant-time compare, 401 out.
Step 3: your database is the source of truth, not the webhook
Write the payment to your own table with the provider's payment ID as a unique key. The webhook is a notification; your row is the fact. This is what lets you answer "did this person pay?" later without calling the provider. More on the topic: “Automatic Payment-Deadline Reminders: Build It in an Evening”.
Ask the agent for an insert that is safe under a race — an INSERT... ON CONFLICT (payment_id) DO NOTHING in PostgreSQL, or a unique index plus a handled duplicate error. Then the duplicate webhook from Tuesday hits the unique key, the insert does nothing, and the handler can return 200 and stop. That is idempotent processing by payment ID, and it is the whole fix for the double-certificate problem.
The part the plain DO NOTHING hides: it tells you nothing about whether it inserted. You need the row count back to know whether this is a new paid row (figure step 4) or a replay. In PostgreSQL, RETURNING gives you the inserted row and nothing on a conflict, so an empty result means "duplicate":
-- PostgreSQL 15+
CREATE TABLE payments (
payment_id TEXT PRIMARY KEY,
status TEXT NOT NULL,
payer_email TEXT NOT NULL,
payer_name TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
issued_at TIMESTAMPTZ
);
-- returns one row if newly inserted, zero rows if it already existed
INSERT INTO payments (payment_id, status, payer_email, payer_name, amount_cents)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (payment_id) DO NOTHING
RETURNING payment_id;
In your handler, rowcount == 1 (or a non-empty result) means newly created — only then does issuance start. rowcount == 0 means duplicate — return 200 and stop. If your driver does not surface the count, use RETURNING and check whether a row came back; do not fall back to a separate SELECT before the insert, which reintroduces the race the unique key was meant to close.
Your check: fire the same webhook twice with the same payment ID and confirm the second one changes nothing and issues nothing — the second insert returns zero rows, so the new-row branch never runs. Then fire a webhook with a new payment ID but a body that claims a status you did not expect — the row should record the status as-is and your issuance logic should only trigger on the status that means "paid."
Step 4: the PDF from a template — AI does the layout, you check the data path
The agent is good at this part: take an HTML template, fill it with the payer's name, email, amount and a document number, render to PDF. Use a real renderer — WeasyPrint or a headless browser — not a hand-rolled PDF writer.
The human check is not the layout, it is the data source. The template must read from your database row, not from the webhook payload. If the PDF is generated straight from the request body, a forged-but-signed-elsewhere or malformed body can put wrong data on a real-looking document. The row you wrote in step 3 is the only trustworthy input.
Generate the document number from the payment ID or your own sequence, not from a random value — that way re-issuing the same payment produces the same document number, which is what a re-issue should mean.
Step 5: email delivery and re-issue on demand
Send the PDF as an attachment through your mail provider's API. Two rules here: send only after the PDF exists on disk or in storage (not in the same transaction as the row write), and log the send result so a failed email is visible rather than silent.
The re-issue path is a small endpoint: given a payment ID, regenerate the PDF from the stored row and send it again. This is where the event log earns its keep — you can see that the original was sent at 14:02, the re-issue at 16:40, and both carry the same document number.
Where this breaks, and what holds it together
Three real failure modes for this specific build:
Slow response, provider retries. If your endpoint does the PDF and the email inline and takes longer than the provider's timeout, the provider retries and you get duplicates. What holds the data: the unique key on payment ID, checked in the same place the insert happens. It fails only if you skipped it — then the retry becomes a second certificate. Answer fast, work in the background, and keep the insert and the new-row check together so the async handoff cannot open a window between them.
Webhook arrives before your record exists. Some providers send the event before your checkout flow has written its own order row. If step 3 assumes the row is already there, the insert fails or attaches to nothing. The fix is to make the webhook write create-or-update the payment row itself, keyed by payment ID, rather than depending on an earlier write.
The mail provider has no API or rate-limits you. If delivery fails, the PDF exists but the customer has nothing. What holds it: the event log and the re-issue endpoint. It fails if you never logged the send — then you cannot tell who is waiting. Log every send attempt with its result.
What it costs in time and money
Units of the calculation, so you can redo it for your case:
- Build hours: roughly 8–12 hours of an experienced developer for the five steps above, broken down as endpoint and signature (2–3 h), database and idempotency (2–3 h), PDF template (2–3 h), email and re-issue plus logging (2–3 h). Add 2–4 hours if you have never wired a webhook before.
- Hosting: a small always-on server or a serverless function, priced by your provider — check current pricing, do not trust a number from an article.
- PDF rendering: free if you run a local renderer; a hosted PDF API bills per document, so at 500 documents a month check its per-document rate against your margin.
- Email: most transactional mail providers have a free tier in the low thousands per month, then bill per thousand — check the current rate.
No line here is a quote from a provider; they change. The point is the shape: the build is a day or two of work, and the recurring cost is small until volume grows. More on the topic: “Build a Messenger Bot That Answers and Logs Leads in CRM”.
If you would rather not spend that day, asibiont.com takes builds like this turnkey — the developer names the price, you top up your balance and get the working project. Details are on the subscription tiers page: https://asibiont.com/en/subscription-tiers
The thing to carry away is not the code. It is that "payment confirmed" is a message that can arrive twice, late, or fake, and the document is only safe once you have checked the signature, matched it to your own row, and made the write idempotent by payment ID — with the insert and the new-row check in one place so the answer "was this new?" is trustworthy. Everything else — the template, the email, the re-issue button — sits downstream of that one decision.
For the wider picture of how these small builds fit together, see the projects on asibiont.com: https://asibiont.com/en/subscription-tiers