Files
supermarket/internal/api/stripe/client.go
T
davidandClaude Opus 5.5 2c242d8c94 Phase 4 part 1: the full Stripe sync, and margins per product
Customers, invoices with all their lines (both of Stripe's line shapes),
credit notes, refunds (with their customer) and products: a backfill,
then the Events API every hour, and a new backfill when events have
expired. Metrics page with sync status. Gross margin per product: a
default (60%) and overrides, with names from Stripe's products or the
invoice lines. Schemas 18 and 19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 09:24:32 -07:00

382 lines
12 KiB
Go

// Package stripe reads checkouts and paid invoices from Stripe's API
// (https://docs.stripe.com/api) with a restricted, read-only key. It never
// creates or changes anything in Stripe.
package stripe
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const apiBase = "https://api.stripe.com"
// ErrUnauthorized means the key was refused.
var ErrUnauthorized = errors.New("Stripe refused the API key")
// Client calls the API with one key.
type Client struct {
key, base string
http *http.Client
}
func New(key string) *Client {
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: time.Minute}}
}
// WithBase points the client at another server (for tests).
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
return c
}
// Live reports whether the key is for live data, not test mode.
func (c *Client) Live() bool { return strings.Contains(c.key, "_live_") }
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
u := c.base + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.key)
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
if err != nil {
return err
}
if res.StatusCode == http.StatusUnauthorized {
return ErrUnauthorized
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" {
return fmt.Errorf("Stripe %s: %s", path, e.Error.Message)
}
return fmt.Errorf("Stripe %s: HTTP %d", path, res.StatusCode)
}
return json.Unmarshal(raw, out)
}
// list reads every page of a list endpoint, oldest first.
func list[T interface{ id() string }](ctx context.Context, c *Client, path string, q url.Values, max int) ([]T, error) {
var all []T
q.Set("limit", "100")
for {
var page struct {
Data []T `json:"data"`
HasMore bool `json:"has_more"`
}
if err := c.get(ctx, path, q, &page); err != nil {
return nil, err
}
all = append(all, page.Data...)
if !page.HasMore || len(page.Data) == 0 || len(all) >= max {
break
}
q.Set("starting_after", page.Data[len(page.Data)-1].id())
}
// Stripe lists newest first.
for i, j := 0, len(all)-1; i < j; i, j = i+1, j-1 {
all[i], all[j] = all[j], all[i]
}
return all, nil
}
// Session is a completed Checkout Session: someone bought, subscribed or
// started a trial.
type Session struct {
ID string `json:"id"`
Created int64 `json:"created"`
Status string `json:"status"` // complete, open, expired
Mode string `json:"mode"` // payment, subscription, setup
PaymentStatus string `json:"payment_status"` // paid, unpaid, no_payment_required
AmountTotal int64 `json:"amount_total"`
Currency string `json:"currency"`
Customer string `json:"customer"`
Invoice string `json:"invoice"`
CustomerDetails struct {
Email string `json:"email"`
Name string `json:"name"`
} `json:"customer_details"`
Metadata map[string]string `json:"metadata"`
}
func (s Session) id() string { return s.ID }
// Sessions lists the completed Checkout Sessions created since a time.
func (c *Client) Sessions(ctx context.Context, since time.Time) ([]Session, error) {
q := url.Values{"status": {"complete"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
return list[Session](ctx, c, "/v1/checkout/sessions", q, 5000)
}
// Invoice is a paid invoice: a subscription's first or later payment.
type Invoice struct {
ID string `json:"id"`
Created int64 `json:"created"`
Customer string `json:"customer"`
CustomerEmail string `json:"customer_email"`
CustomerName string `json:"customer_name"`
AmountPaid int64 `json:"amount_paid"`
Currency string `json:"currency"`
BillingReason string `json:"billing_reason"` // subscription_create, subscription_cycle, manual…
Transitions struct {
PaidAt int64 `json:"paid_at"`
} `json:"status_transitions"`
}
func (i Invoice) id() string { return i.ID }
// PaidInvoices lists the paid invoices created since a time.
func (c *Client) PaidInvoices(ctx context.Context, since time.Time) ([]Invoice, error) {
q := url.Values{"status": {"paid"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
return list[Invoice](ctx, c, "/v1/invoices", q, 5000)
}
// Check reads one session and one invoice, so a key missing either
// permission says which.
func (c *Client) Check(ctx context.Context) error {
var page struct {
Data []json.RawMessage `json:"data"`
}
if err := c.get(ctx, "/v1/checkout/sessions", url.Values{"limit": {"1"}}, &page); err != nil {
return fmt.Errorf("reading checkouts: %w", err)
}
if err := c.get(ctx, "/v1/invoices", url.Values{"limit": {"1"}}, &page); err != nil {
return fmt.Errorf("reading invoices: %w", err)
}
return nil
}
// Raw is an object as Stripe sent it, with its ID and creation time read.
type Raw struct {
ID string
Object string
Created int64
JSON json.RawMessage
}
// ListRaw reads every page of a list endpoint, newest first as Stripe sends
// them, keeping each object whole.
func (c *Client) ListRaw(ctx context.Context, path string, q url.Values, max int) ([]Raw, error) {
if q == nil {
q = url.Values{}
}
q.Set("limit", "100")
var all []Raw
for {
var page struct {
Data []json.RawMessage `json:"data"`
HasMore bool `json:"has_more"`
}
if err := c.get(ctx, path, q, &page); err != nil {
return nil, err
}
for _, d := range page.Data {
var head struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
}
if err := json.Unmarshal(d, &head); err != nil {
return nil, err
}
all = append(all, Raw{ID: head.ID, Object: head.Object, Created: head.Created, JSON: d})
}
if !page.HasMore || len(page.Data) == 0 || (max > 0 && len(all) >= max) {
return all, nil
}
q.Set("starting_after", all[len(all)-1].ID)
}
}
// InvoiceLines reads all of an invoice's lines (for invoices whose embedded
// list was cut short).
func (c *Client) InvoiceLines(ctx context.Context, invoiceID string) ([]json.RawMessage, error) {
raws, err := c.ListRaw(ctx, "/v1/invoices/"+url.PathEscape(invoiceID)+"/lines", nil, 0)
if err != nil {
return nil, err
}
out := make([]json.RawMessage, len(raws))
for i, r := range raws {
out[i] = r.JSON
}
return out, nil
}
// EventTypes are the events the sync follows.
var EventTypes = []string{
"customer.created", "customer.updated", "customer.deleted",
"invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible",
"credit_note.created", "credit_note.updated", "credit_note.voided",
"refund.created", "refund.updated", "charge.refunded",
}
// Event is one change, with the object as it was after it.
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Created int64 `json:"created"`
Data struct {
Object json.RawMessage `json:"object"`
} `json:"data"`
}
// Events lists the events of the followed types after a time, oldest first.
func (c *Client) Events(ctx context.Context, after time.Time) ([]Event, error) {
q := url.Values{"created[gt]": {strconv.FormatInt(after.Unix(), 10)}}
for _, t := range EventTypes {
q.Add("types[]", t)
}
raws, err := c.ListRaw(ctx, "/v1/events", q, 0)
if err != nil {
return nil, err
}
out := make([]Event, 0, len(raws))
for i := len(raws) - 1; i >= 0; i-- {
var e Event
if err := json.Unmarshal(raws[i].JSON, &e); err != nil {
return nil, err
}
out = append(out, e)
}
return out, nil
}
// Line is an invoice line, read from either shape Stripe has used: the
// older one (price, type, proration on the line) and the 2025 one (pricing,
// parent).
type Line struct {
ID string
Amount int64 // after discounts, before tax
Currency string
PeriodStart int64
PeriodEnd int64
Subscription string
Price string
Product string
Interval string // day, week, month, year; "" for one-off
IntervalCount int
Quantity int64
Proration bool
Recurring bool
Description string
}
// ParseLine reads an invoice line.
func ParseLine(raw json.RawMessage) (Line, error) {
var l struct {
Description string `json:"description"`
ID string `json:"id"`
Amount int64 `json:"amount"`
Currency string `json:"currency"`
Period struct {
Start int64 `json:"start"`
End int64 `json:"end"`
} `json:"period"`
Quantity int64 `json:"quantity"`
Proration bool `json:"proration"`
Type string `json:"type"`
Subscription json.RawMessage `json:"subscription"`
Price *struct {
ID string `json:"id"`
Product json.RawMessage `json:"product"`
Recurring *struct {
Interval string `json:"interval"`
IntervalCount int `json:"interval_count"`
} `json:"recurring"`
} `json:"price"`
Pricing *struct {
PriceDetails *struct {
Price json.RawMessage `json:"price"`
Product string `json:"product"`
} `json:"price_details"`
} `json:"pricing"`
Parent *struct {
Type string `json:"type"`
SubscriptionItemDetails *struct {
Subscription string `json:"subscription"`
Proration bool `json:"proration"`
} `json:"subscription_item_details"`
} `json:"parent"`
DiscountAmounts []struct {
Amount int64 `json:"amount"`
} `json:"discount_amounts"`
}
if err := json.Unmarshal(raw, &l); err != nil {
return Line{}, err
}
out := Line{ID: l.ID, Amount: l.Amount, Currency: l.Currency, PeriodStart: l.Period.Start, PeriodEnd: l.Period.End,
Quantity: l.Quantity, Proration: l.Proration, Subscription: idOf(l.Subscription), Description: l.Description}
for _, d := range l.DiscountAmounts {
out.Amount -= d.Amount
}
if l.Price != nil {
out.Price, out.Product = l.Price.ID, idOf(l.Price.Product)
if l.Price.Recurring != nil {
out.Interval, out.IntervalCount = l.Price.Recurring.Interval, l.Price.Recurring.IntervalCount
}
}
if l.Pricing != nil && l.Pricing.PriceDetails != nil {
out.Price = or(out.Price, idOf(l.Pricing.PriceDetails.Price))
out.Product = or(out.Product, l.Pricing.PriceDetails.Product)
}
if l.Parent != nil && l.Parent.SubscriptionItemDetails != nil {
out.Subscription = or(out.Subscription, l.Parent.SubscriptionItemDetails.Subscription)
out.Proration = out.Proration || l.Parent.SubscriptionItemDetails.Proration
}
out.Recurring = l.Type == "subscription" || (l.Parent != nil && l.Parent.Type == "subscription_item_details") || out.Interval != ""
return out, nil
}
func or(a, b string) string {
if a != "" {
return a
}
return b
}
// idOf reads a field that is an ID string or an expanded object with an id.
func idOf(raw json.RawMessage) string {
if len(raw) == 0 || string(raw) == "null" {
return ""
}
var s string
if json.Unmarshal(raw, &s) == nil {
return s
}
var o struct {
ID string `json:"id"`
}
_ = json.Unmarshal(raw, &o)
return o.ID
}
// GetRaw reads one object.
func (c *Client) GetRaw(ctx context.Context, path string, q url.Values) (json.RawMessage, error) {
var out json.RawMessage
err := c.get(ctx, path, q, &out)
return out, err
}
// IDOf reads a field that is an ID string or an expanded object with an id.
func IDOf(raw json.RawMessage) string { return idOf(raw) }