Prompt
How do I build invoice generation and payment retries into my app?
Latest observation
A good way to build invoice generation and payment retries is to treat them as two separate but connected workflows:
- Billing/invoicing workflow: create an invoice, store it, send it, and track its state.
- 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
- 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:
-
Trigger invoice creation
- end of billing period
- manual invoicing
- subscription renewal
- usage threshold reached
-
Create invoice as draft
- collect line items
- calculate subtotal/tax/discounts/total
- assign invoice number
-
Finalize invoice
- lock amounts
- set status to
open - optionally generate PDF
- send to customer via email or in-app
-
Record payment
- when payment succeeds, mark invoice
paid - otherwise leave
openor setpast_due
- when payment succeeds, mark invoice
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_dueoruncollectible - 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.createdinvoice.finalizedpayment.attemptedpayment.failedpayment.succeededinvoice.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.succeededpayment_intent.payment_failedinvoice.payment_succeededinvoice.payment_failedcharge.refundedpayment_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:
- a database schema for this,
- a sample retry worker in your backend language,
- or a Stripe-based implementation example.