From Form to Paid Invoice: A Lead-to-Payment Pipeline

A lead fills in your form, you send an invoice, and then you wait. You open your bank app on Friday, see two payments from people whose names you half-remember, and start guessing which invoice each one closes. One of them paid twice because the first invoice expired and they got a second one. Another got access to nothing because nobody noticed the money arrived. This is the pipeline you are about to replace.

Here is the result you are building: a single chain where a paid status can only be set by a bank webhook whose signature checks out. Form submission creates a record with status new. An invoice gets a unique number. The bank calls your endpoint when money lands, you verify the signature, store the event, and only then flip the status to paid and send the confirmation with access. A daily report shows you every record and its status, so reconciliation becomes reading a table instead of hunting through a banking app.

You will see it works when you can fire the same webhook three times and end up with one paid record, one email, and one access grant.

What each piece owns

The whole design rests on one rule: the database is the source of truth, not the bank's dashboard. The bank tells you something happened; your system decides what that means for your records.

Component What it owns Who can change status
Form handler Creates the lead record as new, never as paid Nobody
Invoice generator Assigns a unique, idempotent invoice number Nobody
Webhook endpoint Verifies signature, stores the raw event The only path to paid
Event processor Applies the event once, ignores repeats Transitions new → paid
Notifier Sends confirmation and access after paid Nobody
Daily report Compares your records against the bank statement Flags mismatches for a human

Statuses worth having: new, invoiced, paid, failed, refunded. Resist the urge to add more — every extra status is a branch someone has to handle in code and a state a support person has to explain. More on the topic: “Chargeback: Why "I Paid by Card, So the Money Will Come Back" Doesn't Work — and How to Dispute a Payment Properly”.

Step 1: the form writes a record, not an email

The most common shortcut is a form that emails you. It feels instant and it destroys the chain: there is no record to attach a status to, no ID to put on the invoice, and no way to answer "did this person pay?" six weeks later without searching your inbox.

The AI writes: a form handler that validates input, inserts a row with status = 'new', a server-generated UUID, a timestamp, and the email, and returns a plain confirmation page. It also writes the migration for the table.

You check: that the handler rejects empty and malformed emails, that it never trusts a client-supplied status or price field, and that the UUID is generated on the server. If the form posts a price, someone will eventually post price=1 — recompute the amount from your own price list.

One decision belongs to you alone: what happens when the same email submits twice in ten minutes. Either you deduplicate on email plus a short window, or you allow duplicates and accept that one person may hold two invoices. Pick one and write it down, because the AI will pick something silently otherwise.

Step 2: an invoice number that survives being generated twice

Invoice numbers are where idempotency starts. If your handler crashes after creating the invoice but before saving the number, a retry creates a second invoice for the same lead. Now the client has two payment links and the bank will happily accept both. More on the topic: “Automatic Payment-Deadline Reminders: Build It in an Evening”.

The fix is to derive the invoice number from the record, not from a counter you increment in application code. A pattern like INV-2026-<short record id> is unique by construction: the same lead always produces the same number, so a retry overwrites nothing and creates nothing new.

The AI writes: the invoice template (HTML or PDF), the number derivation, and a uniqueness constraint in the database on that number column. The constraint is the real protection — application logic fails, constraints do not.

You check: the template renders the amount, the currency, the invoice number, and your legal entity details correctly; the number is stable across two runs for the same lead; and the constraint actually rejects a duplicate insert when you try one by hand.

If your bank's API lets you create a payment link or a requisition per invoice, store the bank's reference on the record too. Check the bank's documentation for the exact field name and whether the link expires — do not guess it, the field names differ between providers.

Step 3: the webhook endpoint, and why the signature is the whole security model

Your endpoint is a public URL. Anyone who learns it can POST a fake "payment succeeded" body. The only thing standing between you and free access for strangers is the signature: the bank signs the raw request body with a secret only you and the bank know, and you recompute the signature over the raw bytes before parsing anything.

This is where most implementations break, and it breaks quietly. If you parse the JSON first and re-serialize it to check the signature, key order and whitespace change and the signature never matches — or worse, you disable the check to make it work. If your framework parses the body automatically, you need the raw body available; in Express, for instance, that means capturing it in the body-parser verify callback rather than using express.json() alone.

A working shape in Node with Express (body-parser is bundled with Express 4, so npm install express@4 is enough):

const express = require('express');
const crypto = require('crypto');

const app = express();

app.post('/webhooks/bank',
  express.json({
    verify: (req, res, buf) => { req.rawBody = buf; }
  }),
  (req, res) => {
    const received = req.header('x-bank-signature') || '';
    const expected = crypto
      .createHmac('sha256', process.env.BANK_WEBHOOK_SECRET)
      .update(req.rawBody)
      .digest('hex');

    const a = Buffer.from(received);
    const b = Buffer.from(expected);
    if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
      return res.status(401).send('bad signature');
    }

    // store the raw event, respond fast, process asynchronously
    res.status(200).send('ok');
  }
);

The AI writes: this handler, the event table, and the processing job. You check: the header name and the signing algorithm against your bank's documentation — some providers use a different header and some sign a timestamp plus body, not the body alone. Do not let the AI invent the header name; open the docs and compare character by character.

Respond 200 before you do the work Store the raw event and return 200 immediately, then process it in a background job. If your handler sends the email and calls an API before responding, a slow mail provider turns into a timeout, the bank retries, and you get the duplicate you were trying to avoid.

Step 4: the same webhook will arrive more than once

Banks retry. Networks drop responses. A webhook that arrives twice is not an edge case, it is Tuesday. Your processor must be safe to run on the same event any number of times.

Two layers do the job:

  1. Event-level deduplication. Store the bank's event ID with a unique constraint. On a repeat, the insert fails, you log it and stop.
  2. State-level guard. Even with a new event ID, only transition invoiced → paid. If the record is already paid, do nothing — no second email, no second access grant.

The AI writes both, plus a test that posts the identical payload three times and asserts one paid record, one email, one grant. You check that the test actually fails when you remove the guard — a test that passes on broken code is worse than no test.

Step 5: the confirmation and the access grant

The email is the part the client sees, so it is the part that generates support tickets. Send it from the processor after the status flips, not from the webhook handler, and make it idempotent: if it fails, the job retries; if it succeeds, a later retry must not send it again. The usual pattern is a confirmation_sent_at column checked before sending.

The AI writes the email template and the send step. You check the email arrives with working access credentials, that the amount and invoice number match the record, and that a deliberately failed send (wrong mail key) retries without duplicating on the next successful attempt.

Where this breaks, and what to do about it

The signature check passes but the amount is wrong. Someone paid a different sum, or paid in a different currency, and your handler marks the invoice paid anyway. Always compare the webhook amount and currency against the stored invoice before transitioning. On a mismatch, move the record to failed, store the received amount, and let a human decide — refund, top-up request, or manual close.

The webhook never arrives. The bank's callback fails silently, or the client paid by a method that does not trigger it. This is why the daily report exists: every morning, pull the bank statement and compare it to records in invoiced status. Any invoice older than a few days with no payment gets a nudge; any payment in the statement with no matching record gets investigated. Without this step, a broken webhook means money with no access and nobody noticing.

The secret leaks. A webhook secret in a public repository or a log line means anyone can forge payments. Keep it in environment variables, rotate it if it ever appears in a log, and make sure your logging does not print raw headers.

The reconciliation is not optional A webhook is a notification, not a ledger. The daily statement comparison is what catches the cases the webhook cannot: missing callbacks, wrong amounts, payments for expired invoices.

How to verify it before a real client touches it

Run these by hand in your bank's sandbox. Each has a clear success sign.

  • Happy path. Submit the form, generate the invoice, pay in sandbox. Success: one paid record, one email, access works.
  • Replay. POST the same webhook payload three times. Success: one paid record, one email, one grant, two logged duplicates.
  • Bad signature. Send a payload with a wrong signature. Success: HTTP 401, no status change, an entry in your log.
  • Amount mismatch. Send a validly signed event with a different amount. Success: record goes to failed, no email, nothing granted.
  • Forged status. POST a body claiming paid with no signature at all. Success: rejected.

If all five pass in sandbox, you have a pipeline. If the replay test fails, nothing else matters yet — fix it before going live. More on the topic: “CI/CD Pipeline: From Git Push to Canary Release”.

Access you need, and where it can be impossible

You need three things: API credentials for the bank (a merchant account with webhook access enabled), the webhook signing secret, and a publicly reachable HTTPS endpoint. The first two come from your bank's merchant dashboard or their onboarding — check the docs for whether your plan includes webhooks at all, because some entry-level merchant accounts do not.

The endpoint is the honest blocker: a laptop is not reachable from the internet. You need a deployed server or a tunnel for testing. If your bank has no webhook support in your region or plan, this pipeline cannot be built as described — you fall back to polling the statement on a schedule, which is slower and less reliable but still beats manual reconciliation.

If the build is longer than you want to own — signature handling, retries, the daily report, the tests — this is the kind of project asibiont.com takes on turnkey: you describe the chain, the developer names the price, you top up the balance and get the working pipeline. Details are at https://asibiont.com/en/subscription-tiers.

What it costs you

In time, the honest range is a few days for someone comfortable with backend work and a bank sandbox, and noticeably longer if you are learning webhook verification and idempotency as you go. The AI accelerates the boilerplate — handler, template, tests — but the debugging of signatures and retries is human work, because it depends on your bank's exact behavior.

In money, expect the cost of a small server and whatever your bank charges for merchant services; those depend on your provider and region, so check their pricing rather than trusting a number in an article. There is no per-lead cost here — the pipeline runs on infrastructure you already pay for.

The measure of success is simple: a month from now, you open one table, see every lead and where it stands, and never once open your banking app to figure out who paid. That is the pipeline working. If you still find yourself reconciling by hand, the webhook is not the source of truth yet — and that is the thing to fix first, before adding a single feature on top. The same build, done for you, is at https://asibiont.com/en/subscription-tiers.

AssetMaterials for this article

A document from this article — download and apply it.

  • DOCXWebhook Idempotency & Reconciliation Test Checklist.docxDOCX · 39.1 KBDownload
← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text and the attached files.