package billing import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "time" ) // Stripe is the platform's Stripe account: the few calls billing needs. type Stripe struct { Key string Base string // https://api.stripe.com/v1; tests point it elsewhere HTTP *http.Client } // NewStripe is a client for a secret key. func NewStripe(key string) *Stripe { return &Stripe{Key: key, Base: "https://api.stripe.com/v1", HTTP: &http.Client{Timeout: 30 * time.Second}} } func (s *Stripe) call(ctx context.Context, method, path string, form url.Values, out any) error { var body io.Reader u := s.Base + path if method == http.MethodGet && form != nil { u += "?" + form.Encode() } else if form != nil { body = strings.NewReader(form.Encode()) } req, err := http.NewRequestWithContext(ctx, method, u, body) if err != nil { return err } req.SetBasicAuth(s.Key, "") if body != nil { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } resp, err := s.HTTP.Do(req) if err != nil { return fmt.Errorf("reaching Stripe: %w", err) } defer resp.Body.Close() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode >= 300 { var e struct { Error struct{ Message string } `json:"error"` } _ = json.Unmarshal(raw, &e) if e.Error.Message == "" { e.Error.Message = resp.Status } return errors.New("Stripe said: " + e.Error.Message) } if out == nil { return nil } return json.Unmarshal(raw, out) } // CreateCustomer makes the team's customer. func (s *Stripe) CreateCustomer(ctx context.Context, email, name string, team int64) (string, error) { var c struct{ ID string } err := s.call(ctx, http.MethodPost, "/customers", url.Values{"email": {email}, "name": {name}, "metadata[team]": {strconv.FormatInt(team, 10)}}, &c) return c.ID, err } // Checkout is a Stripe Checkout session for subscribing. type Checkout struct { Customer, Price string Quantity int Team int64 Success, Cancel string Tax bool } // CheckoutURL starts Checkout: the address to send the owner to. func (s *Stripe) CheckoutURL(ctx context.Context, c Checkout) (string, error) { team := strconv.FormatInt(c.Team, 10) form := url.Values{ "mode": {"subscription"}, "customer": {c.Customer}, "line_items[0][price]": {c.Price}, "line_items[0][quantity]": {strconv.Itoa(max(c.Quantity, 1))}, "success_url": {c.Success}, "cancel_url": {c.Cancel}, "client_reference_id": {team}, "subscription_data[metadata][team]": {team}, } if c.Tax { form.Set("automatic_tax[enabled]", "true") form.Set("customer_update[address]", "auto") } var out struct{ URL string } err := s.call(ctx, http.MethodPost, "/checkout/sessions", form, &out) return out.URL, err } // PortalURL is the Customer Portal, for paying and the invoices. func (s *Stripe) PortalURL(ctx context.Context, customer, back string) (string, error) { var out struct{ URL string } err := s.call(ctx, http.MethodPost, "/billing_portal/sessions", url.Values{"customer": {customer}, "return_url": {back}}, &out) return out.URL, err } // Invoice is the next one. type Invoice struct { AmountDue int64 // in the currency's smallest unit Currency string Date time.Time // when it's charged } // Upcoming is the customer's next invoice, or nil if there's none. func (s *Stripe) Upcoming(ctx context.Context, customer string) (*Invoice, error) { var out struct { AmountDue int64 `json:"amount_due"` Currency string `json:"currency"` NextPaymentAttempt int64 `json:"next_payment_attempt"` PeriodEnd int64 `json:"period_end"` } if err := s.call(ctx, http.MethodGet, "/invoices/upcoming", url.Values{"customer": {customer}}, &out); err != nil { return nil, err } when := out.NextPaymentAttempt if when == 0 { when = out.PeriodEnd } return &Invoice{AmountDue: out.AmountDue, Currency: out.Currency, Date: time.Unix(when, 0)}, nil } // SetQuantity changes how many people the subscription pays for, with // Stripe prorating the difference. func (s *Stripe) SetQuantity(ctx context.Context, subscription string, quantity int) error { var sub struct { Items struct { Data []struct{ ID string } `json:"data"` } `json:"items"` } if err := s.call(ctx, http.MethodGet, "/subscriptions/"+url.PathEscape(subscription), nil, &sub); err != nil { return err } if len(sub.Items.Data) == 0 { return errors.New("the subscription has nothing in it") } return s.call(ctx, http.MethodPost, "/subscription_items/"+url.PathEscape(sub.Items.Data[0].ID), url.Values{"quantity": {strconv.Itoa(max(quantity, 1))}, "proration_behavior": {"create_prorations"}}, nil) }