Prompt

How do I build invoice generation and payment retries into my app?

Technology / Payments Infrastructure1 observationLast seen Oct 15, 2026

Latest observation

Oct 15, 2026OpenAI APIWeb search: off

A good way to build invoice generation and payment retries is to treat them as two separate but connected workflows:

  1. Billing/invoicing workflow: create an invoice, store it, send it, and track its state.
  2. Payment recovery workflow: attempt payment, retry on failure, notify the customer, and eventually mark as failed/uncollectible if needed.

Here’s a practical design.


1) Model the billing objects

At minimum, you’ll want these entities:

Customer

  • id
  • name
  • email
  • billing address
  • payment method(s)
  • subscription status

Invoice

  • id
  • customer_id
  • invoice_number
  • status: draft | open | paid | past_due | void | uncollectible
  • issue_date
  • due_date
  • currency
  • subtotal
  • tax
  • total
  • amount_paid
  • amount_due
  • line_items_json or related table
  • pdf_url (optional)
  • created_at / updated_at

Payment attempt

  • id
  • invoice_id
  • payment_method_id
  • status: pending | succeeded | failed
  • failure_reason
  • processor_reference
  • attempt_number
  • created_at

Retry schedule

  • invoice_id
  • next_retry_at
  • retry_count
  • max_retries
  • status: active | stopped | exhausted

2) Invoice generation flow

A common flow:

  1. Trigger invoice creation

    • end of billing period
    • manual invoicing
    • subscription renewal
    • usage threshold reached
  2. Create invoice as draft

    • collect line items
    • calculate subtotal/tax/discounts/total
    • assign invoice number
  3. Finalize invoice

    • lock amounts
    • set status to open
    • optionally generate PDF
    • send to customer via email or in-app
  4. Record payment

    • when payment succeeds, mark invoice paid
    • otherwise leave open or set past_due

Important tips

  • Make invoice creation idempotent so you don’t generate duplicates if a job retries.
  • Use a unique key like customer_id + billing_period_start + billing_period_end.
  • Store immutable invoice totals once finalized.

3) Payment retry strategy

Retries should be controlled and predictable.

Retry triggers

Retry when payment fails due to:

  • insufficient funds
  • temporary processor/network issues
  • expired authentication / SCA challenges
  • gateway timeouts

Do not blindly retry for:

  • invalid card number
  • canceled card
  • fraud block
  • permanently declined payment methods

Retry policy

A common pattern:

  • Retry 1: after 1 hour
  • Retry 2: after 24 hours
  • Retry 3: after 3 days
  • Retry 4: after 7 days

After max retries:

  • mark invoice past_due or uncollectible
  • notify customer
  • optionally suspend service depending on your policy

Smart retrying

If available from your payment provider:

  • use their dunning tools
  • leverage decline codes
  • retry at optimal times based on card/bank behavior
  • automatically update expired cards via network updater

4) Event-driven architecture

This is easiest to maintain if you use asynchronous jobs/events.

Example events

  • invoice.created
  • invoice.finalized
  • payment.attempted
  • payment.failed
  • payment.succeeded
  • invoice.past_due

Example job queue

Use a background worker system to:

  • generate invoices
  • send emails
  • schedule retries
  • reconcile webhook events
  • update invoice statuses

This avoids doing billing work in the request/response path.


5) Suggested retry logic

Pseudo-flow:

If payment fails:
  record failure reason
  if failure is retryable and retry_count < max_retries:
      schedule next attempt using retry policy
      notify customer if needed
  else:
      mark invoice as past_due/uncollectible
      stop retries
      notify customer and internal team

Retryable vs non-retryable

Retryable

  • timeout
  • temporary network error
  • processor unavailable
  • insufficient funds (sometimes)

Non-retryable

  • invalid card
  • expired card
  • stolen card
  • authentication failed permanently
  • account closed

6) Webhooks matter

If you use Stripe, Braintree, Adyen, etc., don’t rely only on synchronous API responses.

Listen for:

  • payment_intent.succeeded
  • payment_intent.payment_failed
  • invoice.payment_succeeded
  • invoice.payment_failed
  • charge.refunded
  • payment_method.updated

Use webhook events to:

  • confirm payment results
  • update invoice state
  • trigger retry scheduling
  • keep your DB in sync with the gateway

Also:

  • verify webhook signatures
  • make handlers idempotent
  • persist processed event IDs to avoid duplicates

7) Customer notifications

Communicate clearly:

  • invoice generated
  • payment failed
  • retry scheduled
  • payment succeeded after retry
  • final failure / service impact

Best practice:

  • include amount due
  • due date
  • “update payment method” link
  • invoice PDF/download link
  • support contact info

8) Security and compliance

If you’re handling payments:

  • Do not store raw card data unless you’re fully PCI-compliant
  • Use tokenized payment methods from a PSP
  • Encrypt sensitive data at rest
  • Restrict access to billing operations
  • Log carefully; avoid leaking card details or full PII

9) Practical data/state machine

A simple invoice state machine:

draft -> open -> paid
open -> past_due
past_due -> paid
past_due -> uncollectible
open -> void
draft -> void

Payment attempt state machine:

pending -> succeeded
pending -> failed

Retry schedule state:

active -> exhausted
active -> stopped

10) Minimal implementation plan

Phase 1: Basic billing

  • Create invoice table
  • Generate invoice numbers
  • Add line items and totals
  • Mark invoices open/paid
  • Email invoices

Phase 2: Payment collection

  • Integrate payment provider
  • Store payment method tokens
  • Attempt automatic collection
  • Handle webhook events

Phase 3: Retries

  • Add retry policy table/config
  • Queue background retry jobs
  • Track attempt count and failure reasons
  • Stop retries after max attempts

Phase 4: Dunning

  • Customer reminders
  • payment method update flows
  • service suspension rules
  • analytics and reporting

11) Example retry policy configuration

{
  "max_retries": 4,
  "retry_intervals_hours": [1, 24, 72, 168],
  "retryable_decline_codes": ["insufficient_funds", "issuer_unavailable", "processing_error"],
  "non_retryable_decline_codes": ["invalid_card", "expired_card", "lost_card", "stolen_card"]
}

12) If you use Stripe

A common Stripe approach:

  • Create subscription/invoice
  • Use automatic collection
  • Listen to invoice/payment webhooks
  • Let Stripe manage retries with Smart Retries or custom dunning settings if appropriate
  • Update your internal invoice record from webhook confirmations

If you want, I can also provide:

  1. a database schema for this,
  2. a sample retry worker in your backend language,
  3. or a Stripe-based implementation example.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.