/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>
205 lines
5.8 KiB
Go
205 lines
5.8 KiB
Go
package billing
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Stripe's webhooks.
|
|
|
|
// Tolerance is how old a signed event may be.
|
|
const Tolerance = 5 * time.Minute
|
|
|
|
// ErrSignature is an event whose signature doesn't check.
|
|
var ErrSignature = errors.New("the event's signature doesn't match")
|
|
|
|
// VerifySignature checks Stripe's Stripe-Signature header (t=…,v1=…) on a
|
|
// body: an HMAC-SHA256, with the webhook's secret, of "<t>.<body>".
|
|
func VerifySignature(header string, body []byte, secret string, now time.Time) error {
|
|
var t int64
|
|
var sigs []string
|
|
for _, part := range strings.Split(header, ",") {
|
|
k, v, ok := strings.Cut(strings.TrimSpace(part), "=")
|
|
if !ok {
|
|
continue
|
|
}
|
|
switch k {
|
|
case "t":
|
|
t, _ = strconv.ParseInt(v, 10, 64)
|
|
case "v1":
|
|
sigs = append(sigs, v)
|
|
}
|
|
}
|
|
if t == 0 || len(sigs) == 0 || secret == "" {
|
|
return ErrSignature
|
|
}
|
|
if d := now.Sub(time.Unix(t, 0)); d > Tolerance || d < -Tolerance {
|
|
return errors.New("the event is too old, or from the future")
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write([]byte(strconv.FormatInt(t, 10) + "." + string(body)))
|
|
want := mac.Sum(nil)
|
|
for _, s := range sigs {
|
|
got, err := hex.DecodeString(s)
|
|
if err == nil && hmac.Equal(got, want) {
|
|
return nil
|
|
}
|
|
}
|
|
return ErrSignature
|
|
}
|
|
|
|
// Sign makes a Stripe-Signature header: for tests.
|
|
func Sign(body []byte, secret string, at time.Time) string {
|
|
t := strconv.FormatInt(at.Unix(), 10)
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write([]byte(t + "." + string(body)))
|
|
return "t=" + t + ",v1=" + hex.EncodeToString(mac.Sum(nil))
|
|
}
|
|
|
|
// Event is a Stripe event, as far as billing reads it.
|
|
type Event struct {
|
|
ID string `json:"id"`
|
|
Type string `json:"type"`
|
|
Data struct {
|
|
Object json.RawMessage `json:"object"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// The objects billing reads.
|
|
type checkoutSession struct {
|
|
ClientReference string `json:"client_reference_id"`
|
|
Customer string `json:"customer"`
|
|
Subscription string `json:"subscription"`
|
|
}
|
|
|
|
type subscription struct {
|
|
ID string `json:"id"`
|
|
Customer string `json:"customer"`
|
|
Status string `json:"status"`
|
|
CurrentPeriodEnd int64 `json:"current_period_end"`
|
|
TrialEnd int64 `json:"trial_end"`
|
|
Metadata map[string]string `json:"metadata"`
|
|
Items struct {
|
|
Data []struct {
|
|
Quantity int `json:"quantity"`
|
|
CurrentPeriodEnd int64 `json:"current_period_end"`
|
|
Price struct {
|
|
ID string `json:"id"`
|
|
} `json:"price"`
|
|
} `json:"data"`
|
|
} `json:"items"`
|
|
}
|
|
|
|
type invoice struct {
|
|
Customer string `json:"customer"`
|
|
Subscription string `json:"subscription"`
|
|
}
|
|
|
|
// Change is what an event did to a team's account, for the log.
|
|
type Change struct {
|
|
Team int64
|
|
Before string // the status before
|
|
After string
|
|
Note string
|
|
}
|
|
|
|
// Apply updates the accounts for an event. Events about customers
|
|
// Supermarket doesn't know (another product on the same Stripe account)
|
|
// are ignored: a nil Change.
|
|
func Apply(load func(team int64, customer string) (*Account, error), p *Plans, e *Event, now time.Time) (*Account, *Change, error) {
|
|
switch e.Type {
|
|
case "checkout.session.completed":
|
|
var cs checkoutSession
|
|
if err := json.Unmarshal(e.Data.Object, &cs); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
team, _ := strconv.ParseInt(cs.ClientReference, 10, 64)
|
|
a, err := load(team, cs.Customer)
|
|
if err != nil || a == nil {
|
|
return nil, nil, err
|
|
}
|
|
before := a.Status
|
|
a.Customer = cs.Customer
|
|
if cs.Subscription != "" {
|
|
a.Subscription = cs.Subscription
|
|
}
|
|
return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: "subscribed through Checkout"}, nil
|
|
|
|
case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted":
|
|
var sub subscription
|
|
if err := json.Unmarshal(e.Data.Object, &sub); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
team, _ := strconv.ParseInt(sub.Metadata["team"], 10, 64)
|
|
a, err := load(team, sub.Customer)
|
|
if err != nil || a == nil {
|
|
return nil, nil, err
|
|
}
|
|
before := a.Status
|
|
a.Customer, a.Subscription, a.Plan = sub.Customer, sub.ID, p.Paid
|
|
status := sub.Status
|
|
switch status {
|
|
case "unpaid", "incomplete":
|
|
status = PastDue
|
|
case "incomplete_expired", "paused":
|
|
status = Canceled
|
|
}
|
|
if e.Type == "customer.subscription.deleted" {
|
|
status, a.Subscription = Canceled, ""
|
|
}
|
|
a.Status = status
|
|
if len(sub.Items.Data) > 0 {
|
|
a.Seats = sub.Items.Data[0].Quantity
|
|
}
|
|
end := sub.CurrentPeriodEnd
|
|
if end == 0 && len(sub.Items.Data) > 0 {
|
|
end = sub.Items.Data[0].CurrentPeriodEnd // newer API versions keep it on the item
|
|
}
|
|
if end > 0 {
|
|
a.PeriodEnd = time.Unix(end, 0)
|
|
}
|
|
if sub.TrialEnd > 0 {
|
|
a.TrialEnds = time.Unix(sub.TrialEnd, 0)
|
|
}
|
|
markPastDue(a, now)
|
|
return a, &Change{Team: a.Team, Before: before, After: a.Status}, nil
|
|
|
|
case "invoice.payment_failed", "invoice.paid":
|
|
var inv invoice
|
|
if err := json.Unmarshal(e.Data.Object, &inv); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
a, err := load(0, inv.Customer)
|
|
if err != nil || a == nil {
|
|
return nil, nil, err
|
|
}
|
|
before := a.Status
|
|
if e.Type == "invoice.payment_failed" && a.Subscription != "" {
|
|
a.Status = PastDue
|
|
} else if e.Type == "invoice.paid" && a.Status == PastDue {
|
|
a.Status = Active
|
|
}
|
|
markPastDue(a, now)
|
|
return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: strings.ReplaceAll(e.Type, "_", " ")}, nil
|
|
}
|
|
return nil, nil, nil // not an event billing follows
|
|
}
|
|
|
|
// markPastDue notes when a team fell behind, and forgets it when it's
|
|
// caught up.
|
|
func markPastDue(a *Account, now time.Time) {
|
|
if a.Status == PastDue {
|
|
if a.PastDueSince.IsZero() {
|
|
a.PastDueSince = now
|
|
}
|
|
return
|
|
}
|
|
a.PastDueSince, a.Warned = time.Time{}, ""
|
|
}
|