Make payment webhook handlers more robust against retries and ordering
Split out of #688. These are the lower-priority robustness points that apply to all three payment providers (Stripe, Polar, Lemon Squeezy). None of them cause wrong data today, so they are grouped here as follow-ups.
1. Permanent errors trigger pointless retries
Every handler returns a non-2xx status for any thrown Error, and the providers retry on non-2xx. That is right for transient failures such as a database outage, but it also applies to failures that can never succeed on retry, for example "There should be exactly one line item" or "Unable to extract price id". The provider keeps retrying those, Stripe for up to three days.
The Lemon Squeezy handler also returns 422 for UnhandledWebhookEventError, while Stripe and Polar return 2xx for the same case. Lemon Squeezy retries anything that isn't 200, so unhandled events get retried there.
Suggested fix: distinguish permanent business errors from transient ones. Log the permanent ones and return 2xx so the provider stops retrying, the same way UnhandledWebhookEventError is handled already. Return non-2xx only for errors where a retry can help.
2. Handlers do network calls before responding
Stripe recommends returning 2xx quickly and doing work asynchronously, since a slow handler can time out and cause a retry. The Stripe handler sends an email inside the request, and the Lemon Squeezy handler calls the Lemon Squeezy API to fetch the customer portal URL. Both are network calls on the webhook's critical path.
Suggested fix: move the slow parts to a Wasp job and respond right after the database update. This is fine at the template's expected volume, so treat it as a scaling concern.
3. Handlers trust the order of events
Stripe and Polar don't guarantee event order. The subscription handlers write the status from the event payload, so a delayed customer.subscription.updated can overwrite a newer state. The current status mapping makes this mostly harmless, but a stale active arriving after a deleted would reopen access.
Suggested fix: when order matters, fetch the current object from the provider's API instead of trusting the payload snapshot.
Source: wasp-lang/open-saas