Paywise payment webhook updates the order
C# · ASP.NET Core · intermediate · modification
Adds the Paywise webhook, so an order moves to paid (or payment failed) as soon as Paywise reports the payment. `PaywiseWebhookEndpoint.cs` maps an anonymous `POST /webhooks/paywise` that reads the raw body, checks the signature, parses the event, then records the event id and applies the order change in one transaction; a redelivered event hits the primary key and is acknowledged without being applied again. `PaywiseSignature.cs` parses the `Paywise-Signature` header and checks the HMAC and the five-minute window. `PaywiseOptions.cs` holds the secret, and `Program.cs` binds it (startup fails without one) and maps the endpoint. `ProcessedWebhookEvent.cs`, its mapping in `ShopDbContext.cs` and the migration `0042_processed_webhook_events.sql` add the processed-events table. `PaywiseSignatureTests.cs` covers the signature check, the window edges and malformed headers; `PaywiseWebhookTests.cs` covers the endpoint against the test database, concurrent redeliveries and out-of-order events included.
Shop API: ASP.NET Core 10 minimal API on .NET 10 (C# 14, nullable reference types enabled, implicit usings), EF Core 10 with Npgsql on PostgreSQL 16 (default READ COMMITTED isolation, no retrying execution strategy), one `ShopDbContext` per request. It runs as two instances behind nginx, which terminates TLS and caps request bodies at 1 MB on every route; server clocks are NTP-synced. Existing and unchanged in `Program.cs`: the DbContext, `TimeProvider.System`, JWT bearer sign-in for the shop's own users, a fallback authorization policy that requires a signed-in user on every endpoint, and `UseExceptionHandler` with problem details, so an unhandled exception answers 500 without exception details. `Order` (existing, `Data/Order.cs`): `Id` (long identity), `CustomerId`, `TotalCents`, `Status` (a string, one of the `OrderStatus` constants `awaiting_payment`, `payment_failed`, `paid`, `shipped`, `cancelled`), `CreatedAt` and `PaidAt` (`DateTimeOffset?`, `timestamptz`). Schema changes are plain SQL files in `db/migrations/`, applied in order by the existing migration runner at deploy, before the new version starts. Paywise's webhook format: `t` is the Unix time in seconds, in decimal digits, at which this delivery attempt was signed; `v1` is the HMAC-SHA256 as 64 hex characters, keyed with the UTF-8 bytes of the whole webhook secret (`whsec_` prefix included), over the ASCII `t`, a `.` and the raw body bytes. Paywise may add other comma-separated schemes to the header later (such as `v0=...`), which receivers are told to ignore. A delivery that does not get a 2xx answer is retried with backoff for up to three days, each attempt re-signed with a fresh `t` and the same event id. Bodies are UTF-8 JSON, `{ "id": "evt_...", "type": "...", "created": <unix seconds>, "data": { ... } }`, where `data` is always an object; on `payment.succeeded` and `payment.failed` it carries `orderId` (the shop's order id, which the checkout attaches to the payment) and `paymentId`, and other event types carry other fields, never `orderId`. Event ids are unique per event. The checkout creates each payment server-side with the order's total, so an event never changes an amount, and a customer whose payment failed may pay again on the same order. In production the secret comes from the environment (`Paywise__WebhookSecret`). A few thousand payments a day; a cleanup job for old `processed_webhook_events` rows is out of scope. Tests: xUnit; `ShopApiFactory` (existing) is a `WebApplicationFactory<Program>` that builds a fresh database from `db/migrations` on the CI Postgres for each test class and offers `CreateDbContext()`, `SeedOrderAsync(status)` and `GetOrderAsync(id)`; it runs the host in the `Testing` environment, and `appsettings.Testing.json` (existing, unchanged) sets a dummy `Paywise:WebhookSecret` for the test host, which the webhook tests override with a secret they know.
Requirements
- New endpoint `POST /webhooks/paywise` receives Paywise's payment events and updates the order each one belongs to. Paywise calls it, not a signed-in user, so it is open to anonymous callers: the request's signature is what authenticates it.
- A request is accepted only when it carries exactly one `Paywise-Signature` header in Paywise's format (`t=<timestamp>,v1=<signature>`, see context) whose `v1` matches the HMAC-SHA256 of `<t>.<raw request body>` under the webhook secret `Paywise:WebhookSecret`, compared in constant time, and whose `t` is at most five minutes (300 seconds, inclusive, in whole seconds) away from the server's clock in either direction. Anything else (no header, a malformed one, a wrong signature, a stale or future timestamp) answers 400 and changes nothing. The API refuses to start without a webhook secret.
- Paywise delivers every event at least once and may deliver the same event (same `id`) again, also at the same time as the first delivery. Each event is applied at most once: every later delivery answers 200 and changes nothing.
- `payment.succeeded` moves the order from `awaiting_payment` or `payment_failed` to `paid` and sets `PaidAt` to the time the webhook is processed; `payment.failed` moves it from `awaiting_payment` to `payment_failed`. An event for an unknown order, or for an order in any other status (a late `payment.failed` after the payment went through, a payment for a cancelled order), changes nothing, is logged as a warning for the support team and answers 200. Other event types answer 200 and change nothing.
- An event counts as processed only together with its order change: if applying it fails, the endpoint answers 500 (no detail in the body), nothing is recorded, and Paywise's retry applies it. A correctly signed body that is not a readable event (no `id` or `type`, or a payment event without a positive `orderId`) answers 400.
Files touched
- src/Shop.Api/Program.cs
- src/Shop.Api/Payments/PaywiseOptions.cs
- src/Shop.Api/Payments/PaywiseSignature.cs
- src/Shop.Api/Payments/PaywiseWebhookEndpoint.cs
- src/Shop.Api/Data/ProcessedWebhookEvent.cs
- src/Shop.Api/Data/ShopDbContext.cs
- db/migrations/0042_processed_webhook_events.sql
- tests/Shop.Api.Tests/PaywiseSignatureTests.cs
- tests/Shop.Api.Tests/PaywiseWebhookTests.cs