// 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 }