Phase 14, part 3: Stripe's events

/billing/stripe takes Stripe's webhooks, signatures checked, each event
handled once, and keeps each team's subscription up to date: checkout, its
status, seats and period, failed and paid invoices, cancellation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 13:21:25 -07:00
co-authored by Claude Opus 5.5
parent 8fb79220e3
commit 4833f53e0d
9 changed files with 421 additions and 2 deletions
+2
View File
@@ -30,6 +30,8 @@ var routeAreas = map[string]string{
"/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic,
"/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic,
"/setup": areaPublic, "/invite": areaPublic, "/signup": areaPublic,
// Stripe's events: signed with the webhook's secret instead.
"=/billing/stripe": areaPublic,
"/teams": areaSignedIn,
// The JSON API: its own keys, like /mcp.
"/api": areaPublic,
+1 -1
View File
@@ -180,7 +180,7 @@ var actionLabels = map[string]string{
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
"signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
"signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "billing": "billing changed:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
"domain-released": "released the domain", "exported": "exported", "downloaded-export": "downloaded the export", "team-deleting": "asked to delete the team", "team-undeleted": "undid the team's deletion", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
+1 -1
View File
@@ -298,7 +298,7 @@ func (s *Server) csrf(next http.Handler) http.Handler {
if c, err := r.Cookie(name); err == nil && len(c.Value) >= 32 {
token = c.Value
}
if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") {
if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") && r.URL.Path != "/billing/stripe" {
if token == "" || !sameToken(token, sentToken(r)) {
http.Error(w, "This form has expired: reload the page and try again.", http.StatusForbidden)
return
+73
View File
@@ -2,10 +2,13 @@ package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"supermarket/internal/audit"
"supermarket/internal/billing"
"supermarket/internal/users"
)
@@ -172,3 +175,73 @@ func (s *Server) billingPortal(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, addr, http.StatusSeeOther)
}
// stripeWebhook takes Stripe's events (POST /billing/stripe), with their
// signatures checked; each is handled once.
func (s *Server) stripeWebhook(w http.ResponseWriter, r *http.Request) {
if !s.billingOn() || s.Config == nil {
http.NotFound(w, r)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "too large", http.StatusRequestEntityTooLarge)
return
}
now := time.Now()
if err := billing.VerifySignature(r.Header.Get("Stripe-Signature"), body, s.Config.StripeWebhookSecret, now); err != nil {
s.Log.Warn("billing: a webhook refused", "err", err, "ip", clientIP(r))
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
var e billing.Event
if err := json.Unmarshal(body, &e); err != nil || e.ID == "" {
http.Error(w, "unreadable event", http.StatusBadRequest)
return
}
var seen int
_ = s.platform().QueryRow(`SELECT count(*) FROM stripe_events WHERE id = ?`, e.ID).Scan(&seen)
if seen > 0 {
w.WriteHeader(http.StatusOK) // already handled
return
}
load := func(team int64, customer string) (*billing.Account, error) {
if customer != "" {
if a, err := billing.ByCustomer(s.platform(), customer); err == nil {
return a, nil
}
}
if team == 0 {
return nil, nil
}
if _, err := users.GetTeam(s.platform(), team); err != nil {
return nil, nil // not one of ours
}
return billing.Get(s.platform(), team)
}
a, change, err := billing.Apply(load, s.Plans, &e, now)
if err != nil {
s.Log.Error("billing: handling an event", "event", e.ID, "type", e.Type, "err", err)
http.Error(w, "couldn't handle it", http.StatusInternalServerError) // Stripe tries again
return
}
if a != nil {
if err := billing.Save(s.platform(), a, now); err != nil {
s.Log.Error("billing: saving", "event", e.ID, "err", err)
http.Error(w, "couldn't save it", http.StatusInternalServerError)
return
}
if ts, err := s.forTeam(a.Team); err == nil {
detail := e.Type
if change.Note != "" {
detail = change.Note
}
ts.record(audit.Entry{Kind: audit.System, Action: "billing", Target: change.Before + " → " + change.After, Detail: detail})
}
s.Log.Info("billing: event", "type", e.Type, "team", a.Team, "status", a.Status)
}
if _, err := billing.SeenEvent(s.platform(), e.ID, e.Type, now); err != nil {
s.Log.Warn("billing: noting an event", "err", err)
}
w.WriteHeader(http.StatusOK)
}
+53
View File
@@ -1,6 +1,7 @@
package web
import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
@@ -10,6 +11,7 @@ import (
"testing"
"time"
"supermarket/internal/audit"
"supermarket/internal/billing"
"supermarket/internal/users"
)
@@ -253,3 +255,54 @@ func TestBillingPage(t *testing.T) {
}
_ = ts
}
// postEvent sends a signed Stripe event.
func postEvent(t *testing.T, s *Server, h http.Handler, id, typ, obj string, sign bool) int {
t.Helper()
body := []byte(`{"id":"` + id + `","type":"` + typ + `","data":{"object":` + obj + `}}`)
sig := "t=1,v1=00"
if sign {
sig = billing.Sign(body, s.Config.StripeWebhookSecret, time.Now())
}
rec := do(h, http.MethodPost, "/billing/stripe", bytes.NewReader(body), map[string]string{"Stripe-Signature": sig, "Content-Type": "application/json", csrfHeader: ""})
return rec.Code
}
func TestStripeWebhooks(t *testing.T) {
s, h := newBilled(t)
s.Config.StripeWebhookSecret = "whsec_test"
signUp(t, h, "olu@acme.example", "Acme", "acme.example")
u, _ := users.ByEmail(s.platform(), "olu@acme.example")
list, _ := users.TeamsOf(s.platform(), u.ID)
team := strconv.FormatInt(list[0].ID, 10)
if code := postEvent(t, s, h, "evt_0", "checkout.session.completed", `{"client_reference_id":"`+team+`","customer":"cus_9","subscription":"sub_9"}`, false); code != http.StatusBadRequest {
t.Errorf("unsigned: %d", code)
}
if code := postEvent(t, s, h, "evt_1", "checkout.session.completed", `{"client_reference_id":"`+team+`","customer":"cus_9","subscription":"sub_9"}`, true); code != http.StatusOK {
t.Fatalf("checkout: %d", code)
}
active := `{"id":"sub_9","customer":"cus_9","status":"active","metadata":{"team":"` + team + `"},"items":{"data":[{"quantity":3,"current_period_end":1900000000}]}}`
postEvent(t, s, h, "evt_2", "customer.subscription.updated", active, true)
a, _ := billing.Get(s.platform(), list[0].ID)
if a.Status != billing.Active || a.Customer != "cus_9" || a.Seats != 3 {
t.Fatalf("active: %+v", a)
}
postEvent(t, s, h, "evt_3", "invoice.payment_failed", `{"customer":"cus_9","subscription":"sub_9"}`, true)
// evt_2 again (Stripe retries): handled once, so it doesn't undo evt_3.
if code := postEvent(t, s, h, "evt_2", "customer.subscription.updated", active, true); code != http.StatusOK {
t.Errorf("replay: %d", code)
}
if a, _ = billing.Get(s.platform(), list[0].ID); a.Status != billing.PastDue || a.PastDueSince.IsZero() {
t.Errorf("past due: %+v", a)
}
// Someone else's customer on the same Stripe account: ignored.
if code := postEvent(t, s, h, "evt_4", "invoice.paid", `{"customer":"cus_other"}`, true); code != http.StatusOK {
t.Errorf("another customer: %d", code)
}
ts, _ := s.forTeam(list[0].ID)
entries, _ := audit.List(ts.DB, audit.Filter{Action: "billing"}, 10)
if len(entries) != 3 || !strings.Contains(entries[0].Target, "active → past_due") {
t.Errorf("log: %+v", entries)
}
}
+1
View File
@@ -345,6 +345,7 @@ func (s *Server) Handler() (http.Handler, error) {
// Signing in (the server edition).
mux.HandleFunc("GET /setup/{token}", (*Server).setupPage)
mux.HandleFunc("POST /setup/{token}", (*Server).setupSave)
mux.HandleFunc("POST /billing/stripe", (*Server).stripeWebhook)
mux.HandleFunc("GET /settings/billing", (*Server).billingPage)
mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout)
mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal)