billingstripe: deterministic prepared requests sent verbatim, outcome classes, exhaustive lists and renewal invoices; discovery migrated; readiness for the locked portal and house coupon (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+1,983
−238
cmd/console/billing.go+17 −1cmd/console/billing_test.go+54 −6internal/billing/billing.go+9 −9internal/billing/billingtest/fake.go+3 −27internal/billingstripe/adapter.go+151 −22internal/billingstripe/adapter_test.go+157 −26internal/billingstripe/catalog.go+14 −4internal/billingstripe/client.go+187 −60internal/billingstripe/customer.go+17 −0internal/billingstripe/prepared.go+448 −0internal/billingstripe/prepared_test.go+839 −0internal/billingstripe/unimplemented.go+0 −60internal/console/billing.go+4 −0internal/console/billingpass.go+18 −7internal/console/billingrecovery_test.go+65 −16
diff --git a/cmd/console/billing.go b/cmd/console/billing.go| index 8f7282d92..b50186ea2 100644 |
| --- a/cmd/console/billing.go |
| +++ b/cmd/console/billing.go |
| @@ -76,11 +76,27 @@ func billingConfig(getenv func(string) string, cat *plans.Catalog) (*console.Bil |
| if err != nil { |
| return nil, billingConfigError("CARLOS_BILLING_PRICES") |
| } |
| + portal := strings.TrimSpace(getenv("CARLOS_STRIPE_PORTAL_CONFIGURATION")) |
| + if !billingstripe.ValidPortalConfiguration(portal) { |
| + return nil, billingConfigError("CARLOS_STRIPE_PORTAL_CONFIGURATION") |
| + } |
| + coupon := strings.TrimSpace(getenv("CARLOS_STRIPE_HOUSE_COUPON")) |
| + if coupon != "" && !billingstripe.ValidCouponID(coupon) { |
| + return nil, billingConfigError("CARLOS_STRIPE_HOUSE_COUPON") |
| + } |
| + // The clock probe reads one of the current book's prices. |
| + var priceIDs []string |
| + for _, ref := range prices.Refs(book.Version) { |
| + if id, ok := prices.ID(ref); ok { |
| + priceIDs = append(priceIDs, id) |
| + } |
| + } |
| provider, err := billingstripe.NewProvider(billingstripe.ProviderConfig{ |
| SecretKey: key, Account: account, WebhookSecrets: secrets, LiveMode: live, |
| + PortalConfiguration: portal, HouseCoupon: coupon, PriceIDs: priceIDs, |
| }) |
| if err != nil { |
| return nil, billingConfigError("CARLOS_STRIPE_SECRET_KEY") |
| } |
| - return &console.BillingConfig{LiveMode: live, Book: book, Prices: prices, Provider: provider}, nil |
| + return &console.BillingConfig{LiveMode: live, Book: book, Prices: prices, Provider: provider, HouseCoupon: coupon}, nil |
| } |
diff --git a/cmd/console/billing_test.go b/cmd/console/billing_test.go| index 224de0c43..a672a8205 100644 |
| --- a/cmd/console/billing_test.go |
| +++ b/cmd/console/billing_test.go |
| @@ -55,12 +55,13 @@ func billingEnv(t *testing.T) map[string]string { |
| } |
| prices, _ := json.Marshal(examplePrices(t, book)) |
| return map[string]string{ |
| - "CARLOS_BILLING": "test", |
| - "CARLOS_PRICE_BOOK": exampleBookPath, |
| - "CARLOS_BILLING_PRICES": string(prices), |
| - "CARLOS_STRIPE_SECRET_KEY": testSecretKey, |
| - "CARLOS_STRIPE_ACCOUNT": "acct_1Example", |
| - "CARLOS_STRIPE_WEBHOOK_SECRET": "whsec_primary", |
| + "CARLOS_BILLING": "test", |
| + "CARLOS_PRICE_BOOK": exampleBookPath, |
| + "CARLOS_BILLING_PRICES": string(prices), |
| + "CARLOS_STRIPE_SECRET_KEY": testSecretKey, |
| + "CARLOS_STRIPE_ACCOUNT": "acct_1Example", |
| + "CARLOS_STRIPE_WEBHOOK_SECRET": "whsec_primary", |
| + "CARLOS_STRIPE_PORTAL_CONFIGURATION": "bpc_1Example", |
| } |
| } |
| @@ -193,3 +194,50 @@ func TestBillingConfigLiveAcceptsApproved(t *testing.T) { |
| t.Fatalf("live + approved: %+v, %v", cfg, err) |
| } |
| } |
| + |
| +func TestBillingConfigPortalAndCoupon(t *testing.T) { |
| + cases := []struct { |
| + name, variable string |
| + edit func(env map[string]string) |
| + }{ |
| + {"no portal configuration", "CARLOS_STRIPE_PORTAL_CONFIGURATION", func(e map[string]string) { delete(e, "CARLOS_STRIPE_PORTAL_CONFIGURATION") }}, |
| + {"portal not bpc_", "CARLOS_STRIPE_PORTAL_CONFIGURATION", func(e map[string]string) { e["CARLOS_STRIPE_PORTAL_CONFIGURATION"] = "acct_1Example" }}, |
| + {"bare portal prefix", "CARLOS_STRIPE_PORTAL_CONFIGURATION", func(e map[string]string) { e["CARLOS_STRIPE_PORTAL_CONFIGURATION"] = "bpc_" }}, |
| + {"portal with a slash", "CARLOS_STRIPE_PORTAL_CONFIGURATION", func(e map[string]string) { e["CARLOS_STRIPE_PORTAL_CONFIGURATION"] = "bpc_1/../x" }}, |
| + {"coupon with a slash", "CARLOS_STRIPE_HOUSE_COUPON", func(e map[string]string) { e["CARLOS_STRIPE_HOUSE_COUPON"] = "house/100" }}, |
| + {"coupon with a space", "CARLOS_STRIPE_HOUSE_COUPON", func(e map[string]string) { e["CARLOS_STRIPE_HOUSE_COUPON"] = "house 100" }}, |
| + // The variables are checked in order: an earlier fault is named first. |
| + {"bad prices and portal", "CARLOS_BILLING_PRICES", func(e map[string]string) { |
| + e["CARLOS_BILLING_PRICES"] = "x" |
| + delete(e, "CARLOS_STRIPE_PORTAL_CONFIGURATION") |
| + }}, |
| + {"bad portal and coupon", "CARLOS_STRIPE_PORTAL_CONFIGURATION", func(e map[string]string) { |
| + delete(e, "CARLOS_STRIPE_PORTAL_CONFIGURATION") |
| + e["CARLOS_STRIPE_HOUSE_COUPON"] = "house/100" |
| + }}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + env := billingEnv(t) |
| + tc.edit(env) |
| + cfg, err := billingConfig(getenvFrom(env), billingCatalog(t)) |
| + if err == nil || cfg != nil { |
| + t.Fatalf("accepted: %v", cfg) |
| + } |
| + if want := "console: invalid billing configuration: " + tc.variable; err.Error() != want { |
| + t.Errorf("error %q, want %q", err, want) |
| + } |
| + }) |
| + } |
| + // No house coupon: optional, empty. |
| + cfg, err := billingConfig(getenvFrom(billingEnv(t)), billingCatalog(t)) |
| + if err != nil || cfg.HouseCoupon != "" { |
| + t.Fatalf("no coupon: %+v, %v", cfg, err) |
| + } |
| + env := billingEnv(t) |
| + env["CARLOS_STRIPE_HOUSE_COUPON"] = " house-forever_1 " |
| + cfg, err = billingConfig(getenvFrom(env), billingCatalog(t)) |
| + if err != nil || cfg.HouseCoupon != "house-forever_1" { |
| + t.Fatalf("coupon: %+v, %v", cfg, err) |
| + } |
| +} |
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index b03aa90c8..bd6ec902f 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -90,9 +90,6 @@ type Event struct { |
| LiveMode bool |
| } |
| -// MaxCustomerSubscriptions bounds CustomerSubscriptions. |
| -const MaxCustomerSubscriptions = 10 |
| - |
| // MaxListPages bounds every exhaustive list: at most this many pages of up |
| // to 100, else ErrIncomplete (Invariant 3). |
| const MaxListPages = 10 |
| @@ -225,6 +222,12 @@ var ( |
| // (fact 5). |
| ErrIndeterminate = errors.New("billing: outcome indeterminate") |
| + // ErrIdempotencyMismatch is the provider refusing a key it already |
| + // holds for other parameters (fact 1). It is a programming error, and |
| + // none of the outcome classes: the key's first request may have |
| + // executed, so the console logs it and leaves the operation unresolved. |
| + ErrIdempotencyMismatch = errors.New("billing: idempotency key reused with other parameters") |
| + |
| // ErrIncomplete is a list longer than MaxListPages pages. |
| ErrIncomplete = errors.New("billing: list incomplete") |
| // ErrNoHouseCoupon is a house Checkout with no coupon configured. |
| @@ -242,10 +245,6 @@ type Provider interface { |
| // CheckoutSubscription is the subscription a checkout made, "" when it |
| // made none. |
| CheckoutSubscription(ctx context.Context, checkoutID string) (string, error) |
| - // CustomerSubscriptions names a customer's subscriptions, newest |
| - // first, at most MaxCustomerSubscriptions: the hourly pass's discovery |
| - // of a first purchase whose events were all missed. One request. |
| - CustomerSubscriptions(ctx context.Context, customer string) ([]string, error) |
| // Check is the readiness check: the provider account and every price |
| // of the book agree with the configuration. |
| Check(ctx context.Context, book *plans.PriceBook, prices PriceMap) error |
| @@ -267,8 +266,9 @@ type Provider interface { |
| // examining subscriptions in every status. Exhaustive: ErrIncomplete |
| // past MaxListPages pages. |
| LiveSubscriptions(ctx context.Context, customer string) ([]string, error) |
| - // CustomerCheckouts is every Checkout session of a customer created |
| - // after createdAfter. Exhaustive. |
| + // CustomerCheckouts is every Checkout session of a customer created at |
| + // or after createdAfter (to the second: a session created in the same |
| + // second is listed). Exhaustive. |
| CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) |
| // Checkout reads one session. ErrNotFound when the provider has none. |
| Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error) |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 71a6a6f1d..06ed176c8 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -105,7 +105,7 @@ type PageRequest struct { |
| // Fake is an in-memory billing.Provider. |
| // |
| // 6a's fields keep their meaning: Subs, Checkouts, Err, CheckErr, Calls, |
| -// SubErr, CustomerCalls, BeforeSubscription. |
| +// SubErr, BeforeSubscription. |
| type Fake struct { |
| mu sync.Mutex |
| @@ -125,8 +125,6 @@ type Fake struct { |
| Calls int |
| // SubErr fails Subscription for one id only. |
| SubErr map[string]error |
| - // CustomerCalls counts CustomerSubscriptions calls. |
| - CustomerCalls int |
| // BeforeSubscription, when set, runs at the start of every |
| // Subscription call, outside the Fake's lock (so it may call back into |
| // the code under test); a non-nil error is returned as the read's. |
| @@ -139,8 +137,8 @@ type Fake struct { |
| Invoices map[string]*Invoice |
| // CallsBy counts requests by method name: "Subscription", |
| - // "CheckoutSubscription", "CustomerSubscriptions", "Check", "Send", |
| - // "Checkout", "PortalURL", "ClockProbe", and one per list page under |
| + // "CheckoutSubscription", "Check", "Send", "Checkout", "PortalURL", |
| + // "ClockProbe", and one per list page under |
| // "LiveSubscriptions", "CustomerCheckouts", "RenewalInvoice" (invoice |
| // pages) and "RenewalInvoiceLines" (line pages). A request that fails |
| // still counts; a CrashBeforeSend does not (nothing was sent). |
| @@ -571,28 +569,6 @@ func (f *Fake) Subscription(ctx context.Context, id string) (*billing.Subscripti |
| return c, nil |
| } |
| -// CustomerSubscriptions returns the ids of Subs on customer, in id order, |
| -// at most billing.MaxCustomerSubscriptions: 6a's single capped request. |
| -func (f *Fake) CustomerSubscriptions(ctx context.Context, customer string) ([]string, error) { |
| - f.mu.Lock() |
| - defer f.mu.Unlock() |
| - f.begin("CustomerSubscriptions") |
| - defer f.end() |
| - f.CustomerCalls++ |
| - if f.Err != nil { |
| - return nil, f.Err |
| - } |
| - if f.timedOut() { |
| - return nil, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| - } |
| - f.respond(ctx) |
| - ids := sortedKeys(f.Subs, func(s *billing.Subscription) bool { return s.Customer == customer }) |
| - if len(ids) > billing.MaxCustomerSubscriptions { |
| - ids = ids[:billing.MaxCustomerSubscriptions] |
| - } |
| - return ids, nil |
| -} |
| - |
| // CheckoutSubscription returns Checkouts[id], else the session's |
| // subscription, "" when neither names one. |
| func (f *Fake) CheckoutSubscription(ctx context.Context, id string) (string, error) { |
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go| index 683b7ad4c..5b2d661fb 100644 |
| --- a/internal/billingstripe/adapter.go |
| +++ b/internal/billingstripe/adapter.go |
| @@ -21,7 +21,23 @@ type ProviderConfig struct { |
| Account string // acct_... |
| WebhookSecrets []string // primary first, up to 3 |
| LiveMode bool |
| - BaseURL string // tests only; "" is api.stripe.com |
| + // PortalConfiguration is the locked Customer Portal configuration |
| + // (bpc_...) every portal session opens under. Required. |
| + PortalConfiguration string |
| + // HouseCoupon is the configured house coupon, "" for none. Only the |
| + // readiness check reads it: a house Checkout carries its coupon id in |
| + // its own CheckoutRequest, frozen in the prepared bytes. |
| + HouseCoupon string |
| + // PriceIDs are configured price ids; the clock probe reads the first |
| + // in sorted order. None means no probe can be made. |
| + PriceIDs []string |
| + BaseURL string // tests only; "" is api.stripe.com |
| +} |
| + |
| +// ValidPortalConfiguration reports whether id has the shape of a Customer |
| +// Portal configuration id. |
| +func ValidPortalConfiguration(id string) bool { |
| + return strings.HasPrefix(id, "bpc_") && len(id) > len("bpc_") && validID(id) |
| } |
| // maxWebhookSecrets is the primary plus two previous secrets during a |
| @@ -30,10 +46,13 @@ const maxWebhookSecrets = 3 |
| // Provider is Stripe as a billing.Provider. |
| type Provider struct { |
| - client *Client |
| - account string |
| - secrets []string |
| - liveMode bool |
| + client *Client |
| + account string |
| + secrets []string |
| + liveMode bool |
| + portal string |
| + houseCoupon string |
| + probePrice string // "" when no price is configured |
| } |
| var _ billing.Provider = (*Provider)(nil) |
| @@ -59,6 +78,21 @@ func NewProvider(cfg ProviderConfig) (*Provider, error) { |
| return nil, errors.New("billingstripe: a webhook secret is empty") |
| } |
| } |
| + if !ValidPortalConfiguration(cfg.PortalConfiguration) { |
| + return nil, errors.New("billingstripe: the portal configuration is not a bpc_ id") |
| + } |
| + if cfg.HouseCoupon != "" && !ValidCouponID(cfg.HouseCoupon) { |
| + return nil, errors.New("billingstripe: the house coupon is not a coupon id") |
| + } |
| + probe := "" |
| + for _, id := range cfg.PriceIDs { |
| + if !validID(id) { |
| + return nil, errors.New("billingstripe: a configured price is not a price id") |
| + } |
| + if probe == "" || id < probe { |
| + probe = id |
| + } |
| + } |
| var opts []Option |
| if cfg.BaseURL != "" { |
| opts = append(opts, WithBaseURL(cfg.BaseURL)) |
| @@ -67,7 +101,10 @@ func NewProvider(cfg ProviderConfig) (*Provider, error) { |
| if err != nil { |
| return nil, err |
| } |
| - return &Provider{client: c, account: cfg.Account, secrets: append([]string(nil), cfg.WebhookSecrets...), liveMode: cfg.LiveMode}, nil |
| + return &Provider{ |
| + client: c, account: cfg.Account, secrets: append([]string(nil), cfg.WebhookSecrets...), liveMode: cfg.LiveMode, |
| + portal: cfg.PortalConfiguration, houseCoupon: cfg.HouseCoupon, probePrice: probe, |
| + }, nil |
| } |
| // String and GoString keep the key and secrets out of any formatted value. |
| @@ -108,6 +145,22 @@ func liveOf(status string) bool { |
| } |
| } |
| +// collectingOf is whether Stripe is still trying to collect money on a |
| +// subscription: it is past due, unpaid or incomplete (an open invoice it |
| +// retries or awaits), its latest invoice is open, or a charged change is |
| +// waiting for its payment (pending_update). An ended subscription collects |
| +// nothing. |
| +func collectingOf(status, latestInvoiceStatus string, pendingUpdate bool) bool { |
| + switch status { |
| + case "past_due", "unpaid", "incomplete": |
| + return true |
| + case "active", "trialing": |
| + return latestInvoiceStatus == "open" || pendingUpdate |
| + default: |
| + return false |
| + } |
| +} |
| + |
| // ParseEvent verifies a delivery's signature and reduces it to what to |
| // read. Nothing else from the body is used. |
| func (p *Provider) ParseEvent(raw []byte, header http.Header, now time.Time) (billing.Event, error) { |
| @@ -155,13 +208,19 @@ func notFound(err error) bool { |
| // Subscription reads one subscription. |
| func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscription, error) { |
| - s, err := p.client.GetSubscription(ctx, id) |
| + s, date, err := p.client.getSubscription(ctx, id) |
| if notFound(err) { |
| return nil, billing.ErrNotFound |
| } |
| if err != nil { |
| return nil, err |
| } |
| + return subscriptionOf(s, date), nil |
| +} |
| + |
| +// subscriptionOf maps a Stripe subscription, read at provider time date, |
| +// onto the neutral one. |
| +func subscriptionOf(s *Subscription, date time.Time) *billing.Subscription { |
| out := &billing.Subscription{ |
| ID: s.ID, |
| Customer: s.CustomerID, |
| @@ -174,24 +233,15 @@ func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscr |
| PeriodEnd: s.CurrentPeriodEnd, |
| CancelAtPeriodEnd: s.CancelAtPeriodEnd, |
| ItemsComplete: !s.ItemsHasMore, |
| + PendingUpdate: s.PendingUpdate, |
| + PendingExpires: s.PendingExpires, |
| + Collecting: collectingOf(s.Status, s.LatestInvoiceStatus, s.PendingUpdate), |
| + ProviderTime: date, |
| } |
| for _, it := range s.Items { |
| - out.Items = append(out.Items, billing.Item{PriceID: it.PriceID, Quantity: it.Quantity, Currency: it.PriceCurrency}) |
| - } |
| - return out, nil |
| -} |
| - |
| -// CustomerSubscriptions lists a customer's subscriptions, newest first. |
| -func (p *Provider) CustomerSubscriptions(ctx context.Context, customer string) ([]string, error) { |
| - subs, err := p.client.ListCustomerSubscriptions(ctx, customer, billing.MaxCustomerSubscriptions) |
| - if err != nil { |
| - return nil, err |
| + out.Items = append(out.Items, billing.Item{ItemID: it.ID, PriceID: it.PriceID, Quantity: it.Quantity, Currency: it.PriceCurrency}) |
| } |
| - ids := make([]string, 0, len(subs)) |
| - for _, s := range subs { |
| - ids = append(ids, s.ID) |
| - } |
| - return ids, nil |
| + return out |
| } |
| // CheckoutSubscription is the subscription a checkout session made. |
| @@ -244,6 +294,85 @@ func (p *Provider) Check(ctx context.Context, book *plans.PriceBook, prices bill |
| } |
| products[price.ProductID] = true |
| } |
| + if err := p.checkPortal(ctx); err != nil { |
| + return err |
| + } |
| + if p.houseCoupon != "" { |
| + if err := p.checkHouseCoupon(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// portalCustomerUpdates is what a customer may edit about themselves in the |
| +// portal: the billing details on an invoice, nothing that identifies the |
| +// account. |
| +var portalCustomerUpdates = map[string]bool{"address": true, "name": true, "tax_id": true} |
| + |
| +// checkPortal is the locked portal (spec §10): active, in this mode, with |
| +// payment method updates and invoice history on, subscription updates and |
| +// cancellation off (every change goes through the console), and customer |
| +// updates off or limited to address, name and tax id. |
| +func (p *Provider) checkPortal(ctx context.Context) error { |
| + pc, err := p.client.GetPortalConfiguration(ctx, p.portal) |
| + if err != nil { |
| + return fmt.Errorf("billing check: reading the portal configuration: %w", err) |
| + } |
| + f := pc.Features |
| + why := "" |
| + switch { |
| + case !pc.Active: |
| + why = "not active" |
| + case pc.LiveMode != p.liveMode: |
| + why = "in the other mode" |
| + case !f.PaymentMethodUpdate.Enabled: |
| + why = "payment method updates are off" |
| + case !f.InvoiceHistory.Enabled: |
| + why = "invoice history is off" |
| + case f.SubscriptionUpdate.Enabled: |
| + why = "subscription updates are on" |
| + case f.SubscriptionCancel.Enabled: |
| + why = "cancellation is on" |
| + case f.CustomerUpdate.Enabled: |
| + for _, u := range f.CustomerUpdate.AllowedUpdates { |
| + if !portalCustomerUpdates[u] { |
| + why = "customers may edit more than address, name and tax id" |
| + break |
| + } |
| + } |
| + } |
| + if why != "" { |
| + return fmt.Errorf("billing check: the portal configuration: %s", why) |
| + } |
| + return nil |
| +} |
| + |
| +// checkHouseCoupon is the configured house coupon: valid, in this mode, |
| +// 100% off with no amount off, forever, and not limited to some products. |
| +func (p *Provider) checkHouseCoupon(ctx context.Context) error { |
| + cp, err := p.client.GetCoupon(ctx, p.houseCoupon) |
| + if err != nil { |
| + return fmt.Errorf("billing check: reading the house coupon: %w", err) |
| + } |
| + why := "" |
| + switch { |
| + case !cp.Valid: |
| + why = "not valid" |
| + case cp.LiveMode != p.liveMode: |
| + why = "in the other mode" |
| + case cp.PercentOff == nil || *cp.PercentOff != 100: |
| + why = "not 100% off" |
| + case cp.AmountOff != nil: |
| + why = "has an amount off" |
| + case cp.Duration != "forever": |
| + why = "not forever" |
| + case len(cp.AppliesToProducts) > 0: |
| + why = "limited to some products" |
| + } |
| + if why != "" { |
| + return fmt.Errorf("billing check: the house coupon: %s", why) |
| + } |
| return nil |
| } |
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go| index ddaa895e4..c371e82ef 100644 |
| --- a/internal/billingstripe/adapter_test.go |
| +++ b/internal/billingstripe/adapter_test.go |
| @@ -52,7 +52,7 @@ func testProvider(t *testing.T, base string, live bool, secrets ...string) *Prov |
| if len(secrets) == 0 { |
| secrets = []string{"whsec_primary"} |
| } |
| - p, err := NewProvider(ProviderConfig{SecretKey: key, Account: "acct_1", WebhookSecrets: secrets, LiveMode: live, BaseURL: base}) |
| + p, err := NewProvider(ProviderConfig{SecretKey: key, Account: "acct_1", WebhookSecrets: secrets, LiveMode: live, BaseURL: base, PortalConfiguration: "bpc_1"}) |
| if err != nil { |
| t.Fatalf("NewProvider: %v", err) |
| } |
| @@ -60,7 +60,7 @@ func testProvider(t *testing.T, base string, live bool, secrets ...string) *Prov |
| } |
| func TestNewProviderRefuses(t *testing.T) { |
| - good := ProviderConfig{SecretKey: "rk_test_abc", Account: "acct_1", WebhookSecrets: []string{"whsec_a"}} |
| + good := ProviderConfig{SecretKey: "rk_test_abc", Account: "acct_1", WebhookSecrets: []string{"whsec_a"}, PortalConfiguration: "bpc_1"} |
| for name, edit := range map[string]func(*ProviderConfig){ |
| "full secret key": func(c *ProviderConfig) { c.SecretKey = "sk_test_abc" }, |
| "live key in test": func(c *ProviderConfig) { c.SecretKey = "rk_live_abc" }, |
| @@ -70,6 +70,11 @@ func TestNewProviderRefuses(t *testing.T) { |
| "no secrets": func(c *ProviderConfig) { c.WebhookSecrets = nil }, |
| "empty secret": func(c *ProviderConfig) { c.WebhookSecrets = []string{""} }, |
| "four secrets": func(c *ProviderConfig) { c.WebhookSecrets = []string{"whsec_a", "whsec_b", "whsec_c", "whsec_d"} }, |
| + "no portal": func(c *ProviderConfig) { c.PortalConfiguration = "" }, |
| + "portal not bpc_": func(c *ProviderConfig) { c.PortalConfiguration = "acct_1" }, |
| + "portal bad chars": func(c *ProviderConfig) { c.PortalConfiguration = "bpc_../x" }, |
| + "bad coupon": func(c *ProviderConfig) { c.HouseCoupon = "house/100" }, |
| + "bad price id": func(c *ProviderConfig) { c.PriceIDs = []string{"price_a", "../x"} }, |
| } { |
| c := good |
| edit(&c) |
| @@ -198,8 +203,13 @@ func TestSubscriptionMapsFields(t *testing.T) { |
| want := billing.Subscription{ |
| ID: "sub_1", Customer: "cus_1", Account: "bab", ProviderStatus: "past_due", State: billing.StatePaid, Live: true, |
| Currency: "usd", LiveMode: false, PeriodEnd: end, CancelAtPeriodEnd: true, ItemsComplete: true, |
| - Items: []billing.Item{{PriceID: "price_p", Quantity: 1, Currency: "usd"}, {PriceID: "price_a", Quantity: 3, Currency: "usd"}}, |
| + Items: []billing.Item{{ItemID: "si_1", PriceID: "price_p", Quantity: 1, Currency: "usd"}, {ItemID: "si_2", PriceID: "price_a", Quantity: 3, Currency: "usd"}}, |
| + Collecting: true, // past due: still collecting |
| } |
| + if sub.ProviderTime.IsZero() { |
| + t.Error("ProviderTime not set from the response's Date") |
| + } |
| + sub.ProviderTime = time.Time{} |
| got, _ := json.Marshal(sub) |
| exp, _ := json.Marshal(want) |
| if string(got) != string(exp) { |
| @@ -248,6 +258,9 @@ type fakeStripe struct { |
| account string |
| prices map[string]map[string]any // price id -> JSON object |
| products map[string]map[string]any |
| + portal map[string]any // the configured bpc_1 |
| + coupons map[string]map[string]any |
| + queries map[string]string // path -> raw query of its last read |
| reads int |
| } |
| @@ -255,8 +268,20 @@ func (f *fakeStripe) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.reads++ |
| + if f.queries == nil { |
| + f.queries = map[string]string{} |
| + } |
| + f.queries[r.URL.Path] = r.URL.RawQuery |
| var obj any |
| switch { |
| + case r.URL.Path == "/v1/billing_portal/configurations/bpc_1": |
| + if f.portal != nil { |
| + obj = f.portal |
| + } |
| + case strings.HasPrefix(r.URL.Path, "/v1/coupons/"): |
| + if c, ok := f.coupons[strings.TrimPrefix(r.URL.Path, "/v1/coupons/")]; ok { |
| + obj = c |
| + } |
| case r.URL.Path == "/v1/account": |
| obj = map[string]any{"id": f.account} |
| case strings.HasPrefix(r.URL.Path, "/v1/prices/"): |
| @@ -289,7 +314,8 @@ func checkFixture(t *testing.T) (*plans.PriceBook, billing.PriceMap, *fakeStripe |
| t.Fatal(err) |
| } |
| raw := map[string]string{} |
| - fs := &fakeStripe{account: "acct_1", prices: map[string]map[string]any{}, products: map[string]map[string]any{}} |
| + fs := &fakeStripe{account: "acct_1", prices: map[string]map[string]any{}, products: map[string]map[string]any{}, |
| + portal: lockedPortal(), coupons: map[string]map[string]any{"house_forever": houseCoupon()}} |
| add := func(r billing.PriceRef, amount int64) { |
| id := "price_" + nonAlnum.ReplaceAllString(r.Key(), "") |
| prod := "prod_" + r.Kind + r.Name |
| @@ -380,8 +406,9 @@ func TestCheckRefusesMismatchedPrices(t *testing.T) { |
| if err := testProvider(t, srv.URL, false).Check(context.Background(), book, pm); err != nil { |
| t.Fatalf("all good: %v", err) |
| } |
| - // Request budget: the account, each price, each distinct product. |
| - if fs.reads > 1+24+8 { |
| + // Request budget: the account, each price, each distinct product, the |
| + // portal configuration. |
| + if fs.reads > 1+24+8+1 { |
| t.Errorf("check made %d reads", fs.reads) |
| } |
| } |
| @@ -439,28 +466,132 @@ func TestCreateCheckoutSendsItems(t *testing.T) { |
| } |
| } |
| -func TestCustomerSubscriptionsLists(t *testing.T) { |
| - var query string |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - if r.URL.Path != "/v1/subscriptions" { |
| - w.WriteHeader(http.StatusNotFound) |
| - return |
| - } |
| - query = r.URL.RawQuery |
| - fmt.Fprint(w, `{"has_more":false,"data":[{"id":"sub_2","livemode":false},{"id":"sub_1","livemode":false}]}`) |
| - })) |
| - defer srv.Close() |
| - p := testProvider(t, srv.URL, false) |
| - ids, err := p.CustomerSubscriptions(context.Background(), "cus_1") |
| - if err != nil || len(ids) != 2 || ids[0] != "sub_2" || ids[1] != "sub_1" { |
| - t.Fatalf("ids = %v, %v", ids, err) |
| +// lockedPortal is a portal configuration the readiness check accepts: |
| +// active, test mode, payment methods and invoices only, address edits. |
| +func lockedPortal() map[string]any { |
| + return map[string]any{ |
| + "id": "bpc_1", "object": "billing_portal.configuration", "active": true, "livemode": false, |
| + "features": map[string]any{ |
| + "customer_update": map[string]any{"enabled": true, "allowed_updates": []string{"address", "name", "tax_id"}}, |
| + "subscription_update": map[string]any{"enabled": false}, |
| + "subscription_cancel": map[string]any{"enabled": false}, |
| + "payment_method_update": map[string]any{"enabled": true}, |
| + "invoice_history": map[string]any{"enabled": true}, |
| + }, |
| + } |
| +} |
| + |
| +// houseCoupon is a house coupon the readiness check accepts. |
| +func houseCoupon() map[string]any { |
| + return map[string]any{"id": "house_forever", "object": "coupon", "valid": true, "livemode": false, |
| + "percent_off": 100, "amount_off": nil, "duration": "forever"} |
| +} |
| + |
| +func portalFeature(f *fakeStripe, name string) map[string]any { |
| + return f.portal["features"].(map[string]any)[name].(map[string]any) |
| +} |
| + |
| +func TestCheckRefusesUnlockedPortal(t *testing.T) { |
| + cases := map[string]func(f *fakeStripe){ |
| + "inactive": func(f *fakeStripe) { f.portal["active"] = false }, |
| + "other mode": func(f *fakeStripe) { f.portal["livemode"] = true }, |
| + "payment method update off": func(f *fakeStripe) { portalFeature(f, "payment_method_update")["enabled"] = false }, |
| + "invoice history off": func(f *fakeStripe) { portalFeature(f, "invoice_history")["enabled"] = false }, |
| + "subscription update on": func(f *fakeStripe) { portalFeature(f, "subscription_update")["enabled"] = true }, |
| + "subscription cancel on": func(f *fakeStripe) { portalFeature(f, "subscription_cancel")["enabled"] = true }, |
| + "email allowed": func(f *fakeStripe) { |
| + portalFeature(f, "customer_update")["allowed_updates"] = []string{"address", "email"} |
| + }, |
| + "shipping allowed": func(f *fakeStripe) { portalFeature(f, "customer_update")["allowed_updates"] = []string{"shipping"} }, |
| + "no such configuration": func(f *fakeStripe) { f.portal = nil }, |
| } |
| - for _, want := range []string{"customer=cus_1", "status=all", "limit=10"} { |
| - if !strings.Contains(query, want) { |
| - t.Errorf("query %q lacks %s", query, want) |
| + for name, edit := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + book, pm, fs := checkFixture(t) |
| + edit(fs) |
| + srv := httptest.NewServer(fs) |
| + defer srv.Close() |
| + err := testProvider(t, srv.URL, false).Check(context.Background(), book, pm) |
| + if err == nil { |
| + t.Fatal("accepted") |
| + } |
| + if !strings.Contains(err.Error(), "portal") || strings.Contains(err.Error(), "bpc_1") { |
| + t.Errorf("error %q: should say portal, without the id", err) |
| + } |
| + }) |
| + } |
| + // Customer update off altogether, or limited to address: accepted. |
| + for name, edit := range map[string]func(f *fakeStripe){ |
| + "customer update off": func(f *fakeStripe) { |
| + portalFeature(f, "customer_update")["enabled"] = false |
| + portalFeature(f, "customer_update")["allowed_updates"] = []string{"email"} |
| + }, |
| + "address only": func(f *fakeStripe) { portalFeature(f, "customer_update")["allowed_updates"] = []string{"address"} }, |
| + "as configured": func(*fakeStripe) {}, |
| + } { |
| + book, pm, fs := checkFixture(t) |
| + edit(fs) |
| + srv := httptest.NewServer(fs) |
| + if err := testProvider(t, srv.URL, false).Check(context.Background(), book, pm); err != nil { |
| + t.Errorf("%s: %v", name, err) |
| } |
| + srv.Close() |
| + } |
| +} |
| + |
| +func TestCheckRefusesBadHouseCoupon(t *testing.T) { |
| + cases := map[string]func(c map[string]any){ |
| + "invalid": func(c map[string]any) { c["valid"] = false }, |
| + "other mode": func(c map[string]any) { c["livemode"] = true }, |
| + "50%": func(c map[string]any) { c["percent_off"] = 50 }, |
| + "no percent": func(c map[string]any) { delete(c, "percent_off") }, |
| + "once": func(c map[string]any) { c["duration"] = "once" }, |
| + "repeating": func(c map[string]any) { c["duration"] = "repeating" }, |
| + "amount_off": func(c map[string]any) { c["amount_off"] = 1000 }, |
| + "restricted": func(c map[string]any) { c["applies_to"] = map[string]any{"products": []string{"prod_planpersonal"}} }, |
| + "missing": nil, |
| + } |
| + houseProvider := func(t *testing.T, base string) *Provider { |
| + return prepProvider(t, base, func(c *ProviderConfig) { c.HouseCoupon = "house_forever" }) |
| + } |
| + for name, edit := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + book, pm, fs := checkFixture(t) |
| + if edit == nil { |
| + delete(fs.coupons, "house_forever") |
| + } else { |
| + edit(fs.coupons["house_forever"]) |
| + } |
| + srv := httptest.NewServer(fs) |
| + defer srv.Close() |
| + err := houseProvider(t, srv.URL).Check(context.Background(), book, pm) |
| + if err == nil { |
| + t.Fatal("accepted") |
| + } |
| + if !strings.Contains(err.Error(), "house coupon") || strings.Contains(err.Error(), "house_forever") { |
| + t.Errorf("error %q: should say house coupon, without the id", err) |
| + } |
| + }) |
| + } |
| + book, pm, fs := checkFixture(t) |
| + srv := httptest.NewServer(fs) |
| + defer srv.Close() |
| + if err := houseProvider(t, srv.URL).Check(context.Background(), book, pm); err != nil { |
| + t.Fatalf("good coupon: %v", err) |
| + } |
| + // applies_to is only returned when expanded: unrestricted must be read, |
| + // not assumed. |
| + if q := fs.queries["/v1/coupons/house_forever"]; !strings.Contains(q, "expand%5B%5D=applies_to") { |
| + t.Errorf("coupon read query %q does not expand applies_to", q) |
| + } |
| + // No house coupon configured: none is read. |
| + _, _, fs2 := checkFixture(t) |
| + srv2 := httptest.NewServer(fs2) |
| + defer srv2.Close() |
| + if err := testProvider(t, srv2.URL, false).Check(context.Background(), book, pm); err != nil { |
| + t.Fatal(err) |
| } |
| - if _, err := p.CustomerSubscriptions(context.Background(), "../x"); err == nil { |
| - t.Error("bad customer id accepted") |
| + if _, read := fs2.queries["/v1/coupons/house_forever"]; read { |
| + t.Error("a coupon was read with none configured") |
| } |
| } |
diff --git a/internal/billingstripe/catalog.go b/internal/billingstripe/catalog.go| index 159b68334..18d957933 100644 |
| --- a/internal/billingstripe/catalog.go |
| +++ b/internal/billingstripe/catalog.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "net/http" |
| "net/url" |
| + "regexp" |
| "strconv" |
| ) |
| @@ -254,7 +255,7 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil || raw.Valid == nil { |
| return errors.New("billingstripe: coupon response missing id, valid or livemode") |
| } |
| - if !validID(*raw.ID) { |
| + if !ValidCouponID(*raw.ID) { |
| return errors.New("billingstripe: coupon id has unexpected shape") |
| } |
| *cp = Coupon{} |
| @@ -270,14 +271,23 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| return nil |
| } |
| +// couponIDRe is the charset of a coupon id: Stripe's generated ids and |
| +// custom ones of letters, digits, '_' and '-'. Nothing that could leave the |
| +// URL path segment it is placed in. |
| +var couponIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{1,200}$`) |
| + |
| +// ValidCouponID reports whether id can name a coupon in a request. |
| +func ValidCouponID(id string) bool { return couponIDRe.MatchString(id) } |
| + |
| // GetCoupon reads one coupon, with applies_to expanded so a product-limited |
| -// coupon's product list is available in the same call. |
| +// coupon's product list is available in the same call (Stripe returns |
| +// applies_to only when asked). |
| func (c *Client) GetCoupon(ctx context.Context, id string) (*Coupon, error) { |
| - if !validID(id) { |
| + if !ValidCouponID(id) { |
| return nil, &Error{Code: CodeInvalidID} |
| } |
| var cp Coupon |
| - if err := c.do(ctx, http.MethodGet, "/v1/coupons/"+id, nil, "", &cp); err != nil { |
| + if err := c.do(ctx, http.MethodGet, "/v1/coupons/"+id, url.Values{"expand[]": {"applies_to"}}, "", &cp); err != nil { |
| return nil, err |
| } |
| if cp.ID != id { |
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go| index ddb5e648e..315df1e18 100644 |
| --- a/internal/billingstripe/client.go |
| +++ b/internal/billingstripe/client.go |
| @@ -10,6 +10,7 @@ |
| package billingstripe |
| import ( |
| + "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| @@ -21,6 +22,8 @@ import ( |
| "strconv" |
| "strings" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| ) |
| const ( |
| @@ -170,24 +173,59 @@ type stripeErrorEnvelope struct { |
| } `json:"error"` |
| } |
| +// response is what every answer carries besides its body. |
| +type response struct { |
| + Status int |
| + // Date is the response's Date header, zero when it had none or it did |
| + // not parse. |
| + Date time.Time |
| + // Replayed is the Idempotent-Replayed header: the provider answered |
| + // from its memory of an earlier request under the same key (fact 7). |
| + Replayed bool |
| +} |
| + |
| // do executes one request. Every POST requires idempotencyKey; GET ignores |
| // it. No retries: a failed request is returned to the caller exactly once. |
| func (c *Client) do(ctx context.Context, method, path string, form url.Values, idempotencyKey string, out any) error { |
| + _, err := c.call(ctx, method, path, form, idempotencyKey, out) |
| + return err |
| +} |
| + |
| +// call is do, also returning the response's headers of interest. A POST |
| +// sends form as its body; any other method sends it as the query. |
| +func (c *Client) call(ctx context.Context, method, path string, form url.Values, idempotencyKey string, out any) (response, error) { |
| + var body []byte |
| + query := "" |
| + if method == http.MethodPost { |
| + body = []byte(form.Encode()) |
| + } else if len(form) > 0 { |
| + query = form.Encode() |
| + } |
| + return c.exchange(ctx, method, path, query, body, idempotencyKey, out) |
| +} |
| + |
| +// exchange makes exactly one HTTP request with body as given, byte for |
| +// byte. Every response that arrives, whatever its status, reports its Date |
| +// header to ctx's billing.ClockRecorder (Invariant 9); a transport failure |
| +// before the headers reports nothing. |
| +func (c *Client) exchange(ctx context.Context, method, path, query string, body []byte, idempotencyKey string, out any) (response, error) { |
| + var meta response |
| if method == http.MethodPost && idempotencyKey == "" { |
| - return &Error{Code: CodeMissingIdempotencyKey} |
| + return meta, &Error{Code: CodeMissingIdempotencyKey} |
| } |
| reqURL := c.baseURL + path |
| - var body io.Reader |
| + if query != "" { |
| + reqURL += "?" + query |
| + } |
| + var rd io.Reader |
| if method == http.MethodPost { |
| - body = strings.NewReader(form.Encode()) |
| - } else if len(form) > 0 { |
| - reqURL += "?" + form.Encode() |
| + rd = bytes.NewReader(body) |
| } |
| - req, err := http.NewRequestWithContext(ctx, method, reqURL, body) |
| + req, err := http.NewRequestWithContext(ctx, method, reqURL, rd) |
| if err != nil { |
| - return &Error{Code: CodeInvalidParams} |
| + return meta, &Error{Code: CodeInvalidParams} |
| } |
| req.Header.Set("Authorization", "Bearer "+c.secretKey) |
| req.Header.Set("Stripe-Version", apiVersion) |
| @@ -195,52 +233,64 @@ func (c *Client) do(ctx context.Context, method, path string, form url.Values, i |
| if method == http.MethodPost { |
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| req.Header.Set("Idempotency-Key", idempotencyKey) |
| + // net/http treats a request with an Idempotency-Key header and a |
| + // rewindable body as replayable, and resends it by itself when a |
| + // kept-alive connection drops after the request was written. |
| + // Without GetBody it cannot: one call is one request, and every |
| + // resend is the caller's decision. |
| + req.GetBody = nil |
| } |
| resp, err := c.httpClient.Do(req) |
| if err != nil { |
| if ctx.Err() != nil || isTimeout(err) { |
| - return &Error{Code: CodeTimeout} |
| + return meta, &Error{Code: CodeTimeout} |
| } |
| - return &Error{Code: CodeNetwork} |
| + return meta, &Error{Code: CodeNetwork} |
| } |
| defer resp.Body.Close() |
| + meta.Status = resp.StatusCode |
| + meta.Replayed = resp.Header.Get("Idempotent-Replayed") == "true" |
| + if d, err := http.ParseTime(resp.Header.Get("Date")); err == nil { |
| + meta.Date = d.UTC() |
| + } |
| + billing.ObserveDate(ctx, meta.Date) |
| if resp.StatusCode >= 300 && resp.StatusCode < 400 { |
| // CheckRedirect stopped us from following it, but a 3xx is still not |
| // a status this API is supposed to return. |
| - return &Error{Code: CodeUnexpectedRedirect, HTTPStatus: resp.StatusCode} |
| + return meta, &Error{Code: CodeUnexpectedRedirect, HTTPStatus: resp.StatusCode} |
| } |
| limited := io.LimitReader(resp.Body, maxResponseBytes+1) |
| respBody, err := io.ReadAll(limited) |
| if err != nil { |
| - return &Error{Code: CodeNetwork} |
| + return meta, &Error{Code: CodeNetwork, HTTPStatus: resp.StatusCode} |
| } |
| if len(respBody) > maxResponseBytes { |
| - return &Error{Code: CodeResponseTooLarge, HTTPStatus: resp.StatusCode} |
| + return meta, &Error{Code: CodeResponseTooLarge, HTTPStatus: resp.StatusCode} |
| } |
| if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| var env stripeErrorEnvelope |
| _ = json.Unmarshal(respBody, &env) // best-effort; body itself never leaves this function |
| - return &Error{ |
| + return meta, &Error{ |
| Code: CodeAPIError, |
| HTTPStatus: resp.StatusCode, |
| StripeType: safeErrorEnum(env.Error.Type), |
| StripeCode: safeErrorEnum(env.Error.Code), |
| StripeParam: safeErrorParam(env.Error.Param), |
| - Replayed: resp.Header.Get("Idempotent-Replayed") == "true", |
| + Replayed: meta.Replayed, |
| } |
| } |
| if out == nil { |
| - return nil |
| + return meta, nil |
| } |
| if err := json.Unmarshal(respBody, out); err != nil { |
| - return &Error{Code: CodeDecodeError, HTTPStatus: resp.StatusCode} |
| + return meta, &Error{Code: CodeDecodeError, HTTPStatus: resp.StatusCode} |
| } |
| - return nil |
| + return meta, nil |
| } |
| func isTimeout(err error) bool { |
| @@ -425,6 +475,13 @@ type Subscription struct { |
| // Currency is the subscription's own currency, lower case, as Stripe |
| // reports it ("" when the response carried none). |
| Currency string |
| + // PendingUpdate is a pending_update on the subscription: a charged |
| + // change waiting for its payment, dropped at PendingExpires. |
| + PendingUpdate bool |
| + PendingExpires time.Time |
| + // LatestInvoiceStatus is the latest invoice's status ("open", "paid", |
| + // ...), "" unless the read expanded latest_invoice. |
| + LatestInvoiceStatus string |
| } |
| // UnmarshalJSON decodes a Subscription strictly enough that a null response |
| @@ -448,6 +505,10 @@ func (s *Subscription) UnmarshalJSON(b []byte) error { |
| Data []SubscriptionItem `json:"data"` |
| HasMore bool `json:"has_more"` |
| } `json:"items"` |
| + PendingUpdate *struct { |
| + ExpiresAt int64 `json:"expires_at"` |
| + } `json:"pending_update"` |
| + LatestInvoice idOrExpanded `json:"latest_invoice"` |
| } |
| if err := json.Unmarshal(b, &raw); err != nil { |
| return err |
| @@ -470,6 +531,21 @@ func (s *Subscription) UnmarshalJSON(b []byte) error { |
| s.Items = raw.Items.Data |
| s.LiveMode, s.ItemsHasMore = *raw.LiveMode, raw.Items.HasMore |
| s.Currency = raw.Currency |
| + if raw.PendingUpdate != nil { |
| + s.PendingUpdate = true |
| + if raw.PendingUpdate.ExpiresAt > 0 { |
| + s.PendingExpires = time.Unix(raw.PendingUpdate.ExpiresAt, 0).UTC() |
| + } |
| + } |
| + if raw.LatestInvoice.Object != nil { |
| + var inv struct { |
| + Status string `json:"status"` |
| + } |
| + if err := json.Unmarshal(raw.LatestInvoice.Object, &inv); err != nil { |
| + return err |
| + } |
| + s.LatestInvoiceStatus = inv.Status |
| + } |
| return nil |
| } |
| @@ -570,6 +646,26 @@ func (s *Session) FixedCurrency(currency string) bool { |
| // generated by this package — a caller retrying a failed create must reuse |
| // the same key, or it is not a retry. |
| func (c *Client) CreateCheckout(ctx context.Context, p CreateCheckoutParams, idempotencyKey string) (*Session, error) { |
| + form, err := checkoutForm(p) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var sess Session |
| + if err := c.do(ctx, http.MethodPost, "/v1/checkout/sessions", form, idempotencyKey, &sess); err != nil { |
| + return nil, err |
| + } |
| + if err := validateRedirectURL(sess.URL, "checkout.stripe.com"); err != nil { |
| + return nil, err |
| + } |
| + if !sess.FixedCurrency(p.Currency) { |
| + return nil, &Error{Code: CodeCurrencyMismatch, SessionID: sess.ID, Session: &sess} |
| + } |
| + return &sess, nil |
| +} |
| + |
| +// checkoutForm validates p and encodes the parameters every Checkout |
| +// Session this package creates carries. |
| +func checkoutForm(p CreateCheckoutParams) (url.Values, error) { |
| if len(p.Items) == 0 { |
| return nil, &Error{Code: CodeInvalidParams} |
| } |
| @@ -612,24 +708,16 @@ func (c *Client) CreateCheckout(ctx context.Context, p CreateCheckoutParams, ide |
| form.Set("customer", p.CustomerID) |
| } |
| if p.HouseCoupon != "" { |
| + if !ValidCouponID(p.HouseCoupon) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| form.Set("discounts[0][coupon]", p.HouseCoupon) |
| } else { |
| form.Set("allow_promotion_codes", "true") |
| } |
| p.Metadata.set(form, "metadata") |
| p.Metadata.set(form, "subscription_data[metadata]") |
| - |
| - var sess Session |
| - if err := c.do(ctx, http.MethodPost, "/v1/checkout/sessions", form, idempotencyKey, &sess); err != nil { |
| - return nil, err |
| - } |
| - if err := validateRedirectURL(sess.URL, "checkout.stripe.com"); err != nil { |
| - return nil, err |
| - } |
| - if !sess.FixedCurrency(p.Currency) { |
| - return nil, &Error{Code: CodeCurrencyMismatch, SessionID: sess.ID, Session: &sess} |
| - } |
| - return &sess, nil |
| + return form, nil |
| } |
| // GetCheckout reads back a Checkout Session with its subscription expanded, |
| @@ -688,16 +776,24 @@ func (c *Client) CreatePortal(ctx context.Context, customerID, returnURL, config |
| return &ps, nil |
| } |
| -// GetSubscription reads one subscription. |
| +// GetSubscription reads one subscription, with its latest invoice |
| +// expanded so whether it is still being collected is in the same read. |
| func (c *Client) GetSubscription(ctx context.Context, id string) (*Subscription, error) { |
| + sub, _, err := c.getSubscription(ctx, id) |
| + return sub, err |
| +} |
| + |
| +// getSubscription is GetSubscription, also returning the response's Date. |
| +func (c *Client) getSubscription(ctx context.Context, id string) (*Subscription, time.Time, error) { |
| if !validID(id) { |
| - return nil, &Error{Code: CodeInvalidID} |
| + return nil, time.Time{}, &Error{Code: CodeInvalidID} |
| } |
| var sub Subscription |
| - if err := c.do(ctx, http.MethodGet, "/v1/subscriptions/"+id, nil, "", &sub); err != nil { |
| - return nil, err |
| + meta, err := c.call(ctx, http.MethodGet, "/v1/subscriptions/"+id, url.Values{"expand[]": {"latest_invoice"}}, "", &sub) |
| + if err != nil { |
| + return nil, meta.Date, err |
| } |
| - return &sub, nil |
| + return &sub, meta.Date, nil |
| } |
| // Proration behaviours UpdateQuantityWith accepts. They are Stripe's own |
| @@ -817,32 +913,6 @@ func (c *Client) FenceQuantityKey(ctx context.Context, itemID string, generation |
| return "", err |
| } |
| -// ListCustomerSubscriptions reads one page of a customer's subscriptions in |
| -// every status, newest first (Stripe's list order), at most limit. One |
| -// request; it never pages. |
| -func (c *Client) ListCustomerSubscriptions(ctx context.Context, customerID string, limit int) ([]Subscription, error) { |
| - if !validID(customerID) { |
| - return nil, &Error{Code: CodeInvalidID} |
| - } |
| - if limit < 1 || limit > listPageLimit { |
| - return nil, &Error{Code: CodeInvalidParams} |
| - } |
| - form := url.Values{} |
| - form.Set("customer", customerID) |
| - form.Set("status", "all") |
| - form.Set("limit", strconv.Itoa(limit)) |
| - var page subscriptionListResponse |
| - if err := c.do(ctx, http.MethodGet, "/v1/subscriptions", form, "", &page); err != nil { |
| - return nil, err |
| - } |
| - for _, s := range page.Data { |
| - if !validID(s.ID) { |
| - return nil, &Error{Code: CodeDecodeError} |
| - } |
| - } |
| - return page.Data, nil |
| -} |
| - |
| type subscriptionListResponse struct { |
| Data []Subscription `json:"data"` |
| HasMore bool `json:"has_more"` |
| @@ -899,3 +969,60 @@ func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) |
| } |
| return out, nil |
| } |
| + |
| +// listPage is one page of any Stripe list. |
| +type listPage struct { |
| + Data []json.RawMessage `json:"data"` |
| + HasMore bool `json:"has_more"` |
| +} |
| + |
| +// listAll pages through a Stripe list to completion (Invariant 3): up to |
| +// billing.MaxListPages pages of listPageLimit, each continuing with |
| +// starting_after the last id of the one before, and every status the |
| +// query does not exclude. each decodes one object and returns its id, or |
| +// errListDone to stop with success once what it looks for is found. A |
| +// list longer than billing.MaxListPages pages is billing.ErrIncomplete; a |
| +// page that says there is more but holds nothing, or repeats an id, is |
| +// broken pagination. Either way nothing is returned for the caller to act |
| +// on. |
| +func (c *Client) listAll(ctx context.Context, path string, query url.Values, each func(raw json.RawMessage) (string, error)) error { |
| + seen := map[string]bool{} |
| + after := "" |
| + for page := 1; ; page++ { |
| + q := url.Values{} |
| + for k, v := range query { |
| + q[k] = v |
| + } |
| + q.Set("limit", strconv.Itoa(listPageLimit)) |
| + if after != "" { |
| + q.Set("starting_after", after) |
| + } |
| + var lp listPage |
| + if err := c.do(ctx, http.MethodGet, path, q, "", &lp); err != nil { |
| + return err |
| + } |
| + for _, raw := range lp.Data { |
| + id, err := each(raw) |
| + if errors.Is(err, errListDone) { |
| + return nil |
| + } |
| + if err != nil { |
| + return &Error{Code: CodeDecodeError, HTTPStatus: http.StatusOK} |
| + } |
| + if !validID(id) || seen[id] { |
| + return &Error{Code: CodeBrokenPagination} |
| + } |
| + seen[id] = true |
| + after = id |
| + } |
| + if !lp.HasMore { |
| + return nil |
| + } |
| + if len(lp.Data) == 0 { |
| + return &Error{Code: CodeBrokenPagination} |
| + } |
| + if page == billing.MaxListPages { |
| + return billing.ErrIncomplete |
| + } |
| + } |
| +} |
diff --git a/internal/billingstripe/customer.go b/internal/billingstripe/customer.go| index 2f45081ba..ebfaef969 100644 |
| --- a/internal/billingstripe/customer.go |
| +++ b/internal/billingstripe/customer.go |
| @@ -132,6 +132,23 @@ func (cus *Customer) UnmarshalJSON(b []byte) error { |
| return nil |
| } |
| +// maxAccountSqidLen bounds the one value a 6b customer create carries. |
| +const maxAccountSqidLen = 64 |
| + |
| +// customerMetadataForm is a customer create as Plan 6b makes it: the |
| +// account's sqid in metadata and nothing else. No address: Checkout |
| +// collects the billing address (billing_address_collection=required) and |
| +// saves it on the customer (customer_update[address]=auto), and automatic |
| +// tax reads it from there. |
| +func customerMetadataForm(accountSqid string) (url.Values, error) { |
| + if accountSqid == "" || len(accountSqid) > maxAccountSqidLen || !noControlChars(accountSqid) { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + form.Set("metadata[account_sqid]", accountSqid) |
| + return form, nil |
| +} |
| + |
| // CreateCustomer creates a Stripe Customer carrying only a billing country |
| // (and, when given, a postal code) plus the account/intent metadata |
| // entitlement needs to attribute the customer later. tax[validate_location] |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| new file mode 100644 |
| index 000000000..54814b41f |
| --- /dev/null |
| +++ b/internal/billingstripe/prepared.go |
| @@ -0,0 +1,448 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strconv" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// A prepared request is the exact form body Send will send: url.Values |
| +// encoded, which sorts its keys, so the same request always produces the |
| +// same bytes. Every parameter is resolved before it is encoded (price and |
| +// item ids, the coupon id, URLs, metadata, the proration timestamp and |
| +// every constant), and nothing is added at send time. |
| + |
| +// prepared builds a keyed POST. |
| +func prepared(kind, path string, form url.Values, key string) (billing.Prepared, error) { |
| + if key == "" { |
| + return billing.Prepared{}, &Error{Code: CodeMissingIdempotencyKey} |
| + } |
| + return billing.Prepared{Kind: kind, Method: http.MethodPost, Path: path, Body: []byte(form.Encode()), Key: key}, nil |
| +} |
| + |
| +// PrepareCustomer encodes a customer create for the account: its metadata |
| +// only. Checkout collects the billing address (billing_address_collection) |
| +// and saves it on the customer. |
| +func (p *Provider) PrepareCustomer(accountSqid, key string) (billing.Prepared, error) { |
| + form, err := customerMetadataForm(accountSqid) |
| + if err != nil { |
| + return billing.Prepared{}, err |
| + } |
| + return prepared(billing.PreparedCustomer, "/v1/customers", form, key) |
| +} |
| + |
| +// PrepareCheckout encodes a Checkout Session create: subscription mode in |
| +// the request's currency, its line items by price id, Adaptive Pricing |
| +// off, the billing address required and saved on the customer, automatic |
| +// tax, the provider-time expiry, the success and cancel URLs, the purchase |
| +// metadata on the session and on the subscription it makes, and either the |
| +// resolved coupon (req.Coupon) or promotion codes. |
| +func (p *Provider) PrepareCheckout(req billing.CheckoutRequest) (billing.Prepared, error) { |
| + if req.ExpiresAt.IsZero() || req.ExpiresAt.Unix() <= 0 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + params := CreateCheckoutParams{ |
| + SuccessURL: req.SuccessURL, |
| + CancelURL: req.CancelURL, |
| + CustomerID: req.Customer, |
| + Metadata: CheckoutMetadata{ |
| + AccountSqid: req.AccountSqid, IntentID: req.IntentID, PriceBook: req.Book, Currency: req.Currency, |
| + }, |
| + HouseCoupon: req.Coupon, |
| + Currency: req.Currency, |
| + } |
| + for _, it := range req.Items { |
| + params.Items = append(params.Items, LineItem{PriceID: it.PriceID, Quantity: it.Quantity}) |
| + } |
| + form, err := checkoutForm(params) |
| + if err != nil { |
| + return billing.Prepared{}, err |
| + } |
| + form.Set("billing_address_collection", "required") |
| + form.Set("customer_update[address]", "auto") |
| + form.Set("expires_at", strconv.FormatInt(req.ExpiresAt.Unix(), 10)) |
| + return prepared(billing.PreparedCheckout, "/v1/checkout/sessions", form, req.IdempotencyKey) |
| +} |
| + |
| +// PrepareExpire encodes expiring an open Checkout Session. It has no body. |
| +func (p *Provider) PrepareExpire(sessionID, key string) (billing.Prepared, error) { |
| + if !validID(sessionID) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + return prepared(billing.PreparedExpire, "/v1/checkout/sessions/"+sessionID+"/expire", url.Values{}, key) |
| +} |
| + |
| +// PrepareChange encodes a subscription change: each item by id (its |
| +// quantity, a new price, or deleted), or a new item by price and quantity. |
| +// ProrateNone changes quantities with no charge (proration_behavior none). |
| +// ProrateNow invoices the prorated difference at once and, through |
| +// payment_behavior=pending_if_incomplete, applies the change only once |
| +// that is paid (provider fact 8). ProrationDate goes in exactly as given, |
| +// to the second. |
| +func (p *Provider) PrepareChange(req billing.ChangeRequest) (billing.Prepared, error) { |
| + if !validID(req.Subscription) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + if len(req.Items) == 0 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + for i, it := range req.Items { |
| + prefix := fmt.Sprintf("items[%d]", i) |
| + switch { |
| + case it.ItemID == "": |
| + if it.Delete || !validID(it.PriceID) || it.Quantity < 1 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + form.Set(prefix+"[price]", it.PriceID) |
| + form.Set(prefix+"[quantity]", strconv.FormatInt(it.Quantity, 10)) |
| + case !validID(it.ItemID): |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + case it.Delete: |
| + form.Set(prefix+"[id]", it.ItemID) |
| + form.Set(prefix+"[deleted]", "true") |
| + default: |
| + if it.Quantity < 1 || (it.PriceID != "" && !validID(it.PriceID)) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + form.Set(prefix+"[id]", it.ItemID) |
| + if it.PriceID != "" { |
| + form.Set(prefix+"[price]", it.PriceID) |
| + } |
| + form.Set(prefix+"[quantity]", strconv.FormatInt(it.Quantity, 10)) |
| + } |
| + } |
| + switch req.Proration { |
| + case billing.ProrateNone: |
| + form.Set("proration_behavior", ProrationNone) |
| + case billing.ProrateNow: |
| + form.Set("proration_behavior", ProrationAlwaysInvoice) |
| + form.Set("payment_behavior", "pending_if_incomplete") |
| + default: |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + if !req.ProrationDate.IsZero() { |
| + if req.ProrationDate.Unix() <= 0 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + form.Set("proration_date", strconv.FormatInt(req.ProrationDate.Unix(), 10)) |
| + } |
| + return prepared(billing.PreparedChange, "/v1/subscriptions/"+req.Subscription, form, req.IdempotencyKey) |
| +} |
| + |
| +// PrepareRenewal encodes stopping (renew false) or resuming renewal at the |
| +// period end. |
| +func (p *Provider) PrepareRenewal(subscription string, renew bool, key string) (billing.Prepared, error) { |
| + if !validID(subscription) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + form := url.Values{} |
| + form.Set("cancel_at_period_end", strconv.FormatBool(!renew)) |
| + return prepared(billing.PreparedRenewal, "/v1/subscriptions/"+subscription, form, key) |
| +} |
| + |
| +// preparedPathRe is the only kind of path Send will put after the base URL: |
| +// /v1/ and id-shaped segments, nothing that could leave the API's host or |
| +// climb out of /v1. |
| +var preparedPathRe = regexp.MustCompile(`^/v1(/[A-Za-z0-9_]+)+$`) |
| + |
| +// Send makes exactly one request: p.Body byte for byte, under p.Key, with |
| +// no retry by this package or by net/http. A nil error is definite |
| +// success; any other error wraps one of the outcome classes (classify), |
| +// or is billing.ErrIdempotencyMismatch. Result carries the response's |
| +// Idempotent-Replayed and Date headers whenever a response arrived. |
| +func (p *Provider) Send(ctx context.Context, prep billing.Prepared) (billing.Result, error) { |
| + switch prep.Kind { |
| + case billing.PreparedCustomer, billing.PreparedCheckout, billing.PreparedExpire, billing.PreparedChange, billing.PreparedRenewal: |
| + default: |
| + return billing.Result{}, fmt.Errorf("%w: unknown prepared kind %q, not sent", billing.ErrRefused, prep.Kind) |
| + } |
| + if prep.Method != http.MethodPost || prep.Key == "" || !preparedPathRe.MatchString(prep.Path) { |
| + return billing.Result{}, fmt.Errorf("%w: malformed prepared request, not sent", billing.ErrRefused) |
| + } |
| + var raw json.RawMessage |
| + meta, err := p.client.exchange(ctx, http.MethodPost, prep.Path, "", prep.Body, prep.Key, &raw) |
| + res := billing.Result{Replayed: meta.Replayed, ProviderTime: meta.Date} |
| + if err != nil { |
| + return res, classify(err) |
| + } |
| + if err := decodeResult(prep, raw, meta.Date, &res); err != nil { |
| + // The provider executed the request and answered 2xx, but not with |
| + // what was asked for: the outcome is not known to be the one |
| + // intended, and a resend replays the same answer. |
| + return res, fmt.Errorf("%w: %v", billing.ErrIndeterminate, err) |
| + } |
| + return res, nil |
| +} |
| + |
| +// decodeResult reads a 2xx answer to prep by its kind. |
| +func decodeResult(prep billing.Prepared, raw json.RawMessage, date time.Time, res *billing.Result) error { |
| + switch prep.Kind { |
| + case billing.PreparedCustomer: |
| + var cus Customer |
| + if err := json.Unmarshal(raw, &cus); err != nil { |
| + return errors.New("billingstripe: customer answer does not decode") |
| + } |
| + res.Customer = cus.ID |
| + case billing.PreparedCheckout, billing.PreparedExpire: |
| + var sess Session |
| + if err := json.Unmarshal(raw, &sess); err != nil { |
| + return errors.New("billingstripe: session answer does not decode") |
| + } |
| + if prep.Kind == billing.PreparedCheckout { |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + if !sess.FixedCurrency(form.Get("currency")) { |
| + return &Error{Code: CodeCurrencyMismatch} |
| + } |
| + } else if prep.Path != "/v1/checkout/sessions/"+sess.ID+"/expire" { |
| + return errors.New("billingstripe: the expired session is not the one asked for") |
| + } |
| + info, err := sessionInfo(&sess) |
| + if err != nil { |
| + return err |
| + } |
| + res.Checkout = &info |
| + case billing.PreparedChange, billing.PreparedRenewal: |
| + var sub Subscription |
| + if err := json.Unmarshal(raw, &sub); err != nil { |
| + return errors.New("billingstripe: subscription answer does not decode") |
| + } |
| + if prep.Path != "/v1/subscriptions/"+sub.ID { |
| + return errors.New("billingstripe: the subscription answered is not the one asked for") |
| + } |
| + res.Subscription = subscriptionOf(&sub, date) |
| + } |
| + return nil |
| +} |
| + |
| +// classify maps a failed request onto the outcome classes (provider facts |
| +// 1 to 5): |
| +// |
| +// - 402 or a card_error: ErrPaymentFailed, the charge declined; |
| +// - 409: ErrInFlight, a request under the same key (or on the same |
| +// object) is still executing; |
| +// - an idempotency_error: ErrIdempotencyMismatch, the key is held for |
| +// other parameters (a programming error, none of the classes); |
| +// - 429: ErrNotExecuted; |
| +// - any other 4xx: ErrRefused; |
| +// - 5xx, a redirect, or an answer that cannot be read: ErrIndeterminate; |
| +// - a transport error or timeout: ErrNoResponse; |
| +// - a request refused before it was sent: ErrRefused. |
| +// |
| +// The *Error stays wrapped for the log: its text carries no response body |
| +// and no secret. |
| +func classify(err error) error { |
| + var e *Error |
| + if !errors.As(err, &e) { |
| + return fmt.Errorf("%w: %w", billing.ErrIndeterminate, err) |
| + } |
| + class := billing.ErrIndeterminate |
| + switch e.Code { |
| + case CodeTimeout, CodeNetwork: |
| + class = billing.ErrNoResponse |
| + case CodeMissingIdempotencyKey, CodeInvalidParams, CodeInvalidID: |
| + class = billing.ErrRefused |
| + case CodeAPIError: |
| + switch { |
| + case e.HTTPStatus == http.StatusPaymentRequired || e.StripeType == "card_error": |
| + class = billing.ErrPaymentFailed |
| + case e.HTTPStatus == http.StatusConflict: |
| + class = billing.ErrInFlight |
| + case e.StripeType == "idempotency_error": |
| + class = billing.ErrIdempotencyMismatch |
| + case e.HTTPStatus == http.StatusTooManyRequests: |
| + class = billing.ErrNotExecuted |
| + case e.HTTPStatus >= 500: |
| + class = billing.ErrIndeterminate |
| + case e.HTTPStatus >= 400: |
| + class = billing.ErrRefused |
| + } |
| + } |
| + return fmt.Errorf("%w: %w", class, err) |
| +} |
| + |
| +// sessionInfo maps a Checkout Session onto the neutral read. |
| +func sessionInfo(s *Session) (billing.CheckoutInfo, error) { |
| + info := billing.CheckoutInfo{ |
| + ID: s.ID, Subscription: s.SubscriptionID, Customer: s.CustomerID, IntentID: s.Metadata["checkout_intent"], |
| + } |
| + switch s.Status { |
| + case "open": |
| + info.State = billing.CheckoutOpen |
| + case "complete": |
| + info.State = billing.CheckoutComplete |
| + case "expired": |
| + info.State = billing.CheckoutExpired |
| + default: |
| + return billing.CheckoutInfo{}, fmt.Errorf("billingstripe: session %s has an unknown status", s.ID) |
| + } |
| + if s.URL != "" { |
| + if err := validateRedirectURL(s.URL, "checkout.stripe.com"); err != nil { |
| + return billing.CheckoutInfo{}, err |
| + } |
| + info.URL = s.URL |
| + } |
| + if s.ExpiresAt > 0 { |
| + info.ExpiresAt = time.Unix(s.ExpiresAt, 0).UTC() |
| + } |
| + return info, nil |
| +} |
| + |
| +// LiveSubscriptions pages through every subscription of the customer, in |
| +// every status, and names the live ones (liveOf). Exhaustive: |
| +// billing.ErrIncomplete past billing.MaxListPages pages. |
| +func (p *Provider) LiveSubscriptions(ctx context.Context, customer string) ([]string, error) { |
| + if !validID(customer) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + out := []string{} |
| + err := p.client.listAll(ctx, "/v1/subscriptions", url.Values{"customer": {customer}, "status": {"all"}}, func(raw json.RawMessage) (string, error) { |
| + var s Subscription |
| + if err := json.Unmarshal(raw, &s); err != nil { |
| + return "", err |
| + } |
| + if liveOf(s.Status) { |
| + out = append(out, s.ID) |
| + } |
| + return s.ID, nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// CustomerCheckouts pages through the customer's Checkout Sessions created |
| +// at or after createdAfter, to the second (created[gte]), in every status. |
| +// Exhaustive. |
| +func (p *Provider) CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]billing.CheckoutInfo, error) { |
| + if !validID(customer) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + q := url.Values{"customer": {customer}, "created[gte]": {strconv.FormatInt(createdAfter.Unix(), 10)}} |
| + out := []billing.CheckoutInfo{} |
| + err := p.client.listAll(ctx, "/v1/checkout/sessions", q, func(raw json.RawMessage) (string, error) { |
| + var s Session |
| + if err := json.Unmarshal(raw, &s); err != nil { |
| + return "", err |
| + } |
| + info, err := sessionInfo(&s) |
| + if err != nil { |
| + return "", err |
| + } |
| + out = append(out, info) |
| + return s.ID, nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// Checkout reads one Checkout Session. |
| +func (p *Provider) Checkout(ctx context.Context, sessionID string) (billing.CheckoutInfo, error) { |
| + s, err := p.client.GetCheckout(ctx, sessionID) |
| + if notFound(err) { |
| + return billing.CheckoutInfo{}, billing.ErrNotFound |
| + } |
| + if err != nil { |
| + return billing.CheckoutInfo{}, err |
| + } |
| + return sessionInfo(s) |
| +} |
| + |
| +// errListDone stops listAll early: what was looked for has been found. |
| +var errListDone = errors.New("billingstripe: list done") |
| + |
| +// RenewalInvoice finds the subscription's renewal invoice for the period |
| +// starting at periodStart and sums what it billed per price. |
| +// |
| +// Stripe's invoice list cannot filter on billing_reason, so this pages the |
| +// subscription's invoices in every status (newest first, stopping at the |
| +// match) and picks the subscription_cycle invoice for that period. A |
| +// renewal invoice's own period looks back one period (Stripe: "This looks |
| +// back one period for a subscription invoice"), so the renewal for the |
| +// period starting at periodStart is the one whose period_end is |
| +// periodStart; matching period_start would find the next year's renewal. |
| +// Then it pages that invoice's lines exhaustively and sums the quantity of |
| +// each subscription line by price, leaving out proration lines and |
| +// one-off invoice items, which are not the renewal's quantities. |
| +func (p *Provider) RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (billing.InvoiceQuantities, error) { |
| + if !validID(subscription) { |
| + return billing.InvoiceQuantities{}, &Error{Code: CodeInvalidID} |
| + } |
| + want := periodStart.Unix() |
| + match := "" |
| + err := p.client.listAll(ctx, "/v1/invoices", url.Values{"subscription": {subscription}}, func(raw json.RawMessage) (string, error) { |
| + var inv struct { |
| + ID string `json:"id"` |
| + BillingReason string `json:"billing_reason"` |
| + PeriodEnd int64 `json:"period_end"` |
| + } |
| + if err := json.Unmarshal(raw, &inv); err != nil { |
| + return "", err |
| + } |
| + if inv.BillingReason == "subscription_cycle" && inv.PeriodEnd == want && validID(inv.ID) { |
| + match = inv.ID |
| + return inv.ID, errListDone |
| + } |
| + return inv.ID, nil |
| + }) |
| + if err != nil { |
| + return billing.InvoiceQuantities{}, err |
| + } |
| + if match == "" { |
| + return billing.InvoiceQuantities{}, billing.ErrNotFound |
| + } |
| + out := billing.InvoiceQuantities{Invoice: match, PeriodStart: time.Unix(want, 0).UTC(), ByPrice: map[string]int64{}} |
| + err = p.client.listAll(ctx, "/v1/invoices/"+match+"/lines", nil, func(raw json.RawMessage) (string, error) { |
| + var line struct { |
| + ID string `json:"id"` |
| + Type string `json:"type"` |
| + Proration bool `json:"proration"` |
| + Quantity int64 `json:"quantity"` |
| + Price *struct { |
| + ID string `json:"id"` |
| + } `json:"price"` |
| + } |
| + if err := json.Unmarshal(raw, &line); err != nil { |
| + return "", err |
| + } |
| + if line.Type == "subscription" && !line.Proration && line.Price != nil && line.Price.ID != "" { |
| + out.ByPrice[line.Price.ID] += line.Quantity |
| + } |
| + return line.ID, nil |
| + }) |
| + if err != nil { |
| + return billing.InvoiceQuantities{}, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// PortalURL opens a Customer Portal session under the locked configuration. |
| +// It is a write: its failures are classified like Send's. |
| +func (p *Provider) PortalURL(ctx context.Context, customer, returnURL, key string) (string, error) { |
| + ps, err := p.client.CreatePortal(ctx, customer, returnURL, p.portal, key) |
| + if err != nil { |
| + return "", classify(err) |
| + } |
| + return ps.URL, nil |
| +} |
| + |
| +// ClockProbe is one GET of the first configured price, in sorted order, |
| +// made only for its Date header, which the client reports to ctx's |
| +// recorder. It reads Prices, already granted, and needs no customer. |
| +func (p *Provider) ClockProbe(ctx context.Context) error { |
| + if p.probePrice == "" { |
| + return errors.New("billingstripe: no price is configured for the clock probe") |
| + } |
| + return p.client.do(ctx, http.MethodGet, "/v1/prices/"+p.probePrice, nil, "", nil) |
| +} |
diff --git a/internal/billingstripe/prepared_test.go b/internal/billingstripe/prepared_test.go| new file mode 100644 |
| index 000000000..b92dbebb7 |
| --- /dev/null |
| +++ b/internal/billingstripe/prepared_test.go |
| @@ -0,0 +1,839 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// prepProvider is a test-mode provider against base, with cfg edited. |
| +func prepProvider(t *testing.T, base string, edit func(*ProviderConfig)) *Provider { |
| + t.Helper() |
| + cfg := ProviderConfig{ |
| + SecretKey: "rk_test_abc", Account: "acct_1", WebhookSecrets: []string{"whsec_primary"}, |
| + PortalConfiguration: "bpc_1", BaseURL: base, |
| + } |
| + if edit != nil { |
| + edit(&cfg) |
| + } |
| + p, err := NewProvider(cfg) |
| + if err != nil { |
| + t.Fatalf("NewProvider: %v", err) |
| + } |
| + return p |
| +} |
| + |
| +var providerDate = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + |
| +func checkoutRequest() billing.CheckoutRequest { |
| + return billing.CheckoutRequest{ |
| + Customer: "cus_1", AccountSqid: "bab", IntentID: "ci_1", Book: "example-v1", Currency: "usd", |
| + Items: []billing.CheckoutItem{{PriceID: "price_p", Quantity: 1}, {PriceID: "price_a", Quantity: 2}}, |
| + SuccessURL: "https://console.example.com/billing?done=1", CancelURL: "https://console.example.com/billing", |
| + ExpiresAt: providerDate.Add(time.Hour), IdempotencyKey: "key-checkout-1", |
| + } |
| +} |
| + |
| +func changeRequest() billing.ChangeRequest { |
| + return billing.ChangeRequest{ |
| + Subscription: "sub_1", |
| + Items: []billing.ItemChange{ |
| + {ItemID: "si_1", Quantity: 12}, |
| + {ItemID: "si_2", PriceID: "price_b", Quantity: 1}, |
| + {ItemID: "si_3", Delete: true}, |
| + {PriceID: "price_new", Quantity: 3}, |
| + }, |
| + Proration: billing.ProrateNow, ProrationDate: providerDate.Add(1500 * time.Millisecond), IdempotencyKey: "key-change-1", |
| + } |
| +} |
| + |
| +// allPrepared is one Prepared of every kind, from p. |
| +func allPrepared(t *testing.T, p *Provider) map[string]billing.Prepared { |
| + t.Helper() |
| + out := map[string]billing.Prepared{} |
| + var err error |
| + if out["customer"], err = p.PrepareCustomer("bab", "key-customer-1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out["checkout"], err = p.PrepareCheckout(checkoutRequest()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out["expire"], err = p.PrepareExpire("cs_1", "key-expire-1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out["change"], err = p.PrepareChange(changeRequest()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out["renewal"], err = p.PrepareRenewal("sub_1", false, "key-renewal-1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + return out |
| +} |
| + |
| +// captured is one request an httptest server received. |
| +type captured struct { |
| + method, path, key string |
| + body []byte |
| +} |
| + |
| +type capture struct { |
| + mu sync.Mutex |
| + reqs []captured |
| +} |
| + |
| +func (c *capture) add(r *http.Request) captured { |
| + b, _ := io.ReadAll(r.Body) |
| + got := captured{method: r.Method, path: r.URL.Path, key: r.Header.Get("Idempotency-Key"), body: b} |
| + c.mu.Lock() |
| + c.reqs = append(c.reqs, got) |
| + c.mu.Unlock() |
| + return got |
| +} |
| + |
| +func (c *capture) count() int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return len(c.reqs) |
| +} |
| + |
| +func (c *capture) last() captured { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.reqs[len(c.reqs)-1] |
| +} |
| + |
| +// okBody answers a write of each kind with a minimal valid object. |
| +func okBody(path string) string { |
| + switch { |
| + case path == "/v1/customers": |
| + return `{"id":"cus_9","livemode":false}` |
| + case path == "/v1/checkout/sessions" || len(path) > len("/v1/checkout/sessions/"): |
| + if path == "/v1/checkout/sessions" { |
| + return `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9","currency":"usd","customer":"cus_1","expires_at":1793000000,"metadata":{"checkout_intent":"ci_1"}}` |
| + } |
| + if len(path) > 7 && path[len(path)-7:] == "/expire" { |
| + return `{"id":"cs_1","livemode":false,"status":"expired","currency":"usd","customer":"cus_1","metadata":{"checkout_intent":"ci_1"}}` |
| + } |
| + } |
| + return `{"id":"sub_1","customer":"cus_1","status":"active","livemode":false,"currency":"usd","items":{"has_more":false,"data":[{"id":"si_1","quantity":12,"price":{"id":"price_p","currency":"usd"}}]}}` |
| +} |
| + |
| +func TestPrepareIsDeterministic(t *testing.T) { |
| + var c capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got := c.add(r) |
| + fmt.Fprint(w, okBody(got.path)) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + first, second := allPrepared(t, p), allPrepared(t, p) |
| + wantPath := map[string]string{ |
| + "customer": "/v1/customers", "checkout": "/v1/checkout/sessions", "expire": "/v1/checkout/sessions/cs_1/expire", |
| + "change": "/v1/subscriptions/sub_1", "renewal": "/v1/subscriptions/sub_1", |
| + } |
| + wantKind := map[string]string{ |
| + "customer": billing.PreparedCustomer, "checkout": billing.PreparedCheckout, "expire": billing.PreparedExpire, |
| + "change": billing.PreparedChange, "renewal": billing.PreparedRenewal, |
| + } |
| + for name, a := range first { |
| + b := second[name] |
| + if a.Kind != b.Kind || a.Method != b.Method || a.Path != b.Path || a.Key != b.Key || string(a.Body) != string(b.Body) { |
| + t.Errorf("%s: two prepares differ:\n %+v\n %+v", name, a, b) |
| + } |
| + if a.Kind != wantKind[name] || a.Method != http.MethodPost || a.Path != wantPath[name] { |
| + t.Errorf("%s: %s %s %s", name, a.Kind, a.Method, a.Path) |
| + } |
| + // Keys sorted: the body is its own canonical form encoding. |
| + v, err := url.ParseQuery(string(a.Body)) |
| + if err != nil || v.Encode() != string(a.Body) { |
| + t.Errorf("%s: body is not canonical (sorted keys): %q", name, a.Body) |
| + } |
| + if _, err := p.Send(context.Background(), a); err != nil { |
| + t.Errorf("%s: send: %v", name, err) |
| + continue |
| + } |
| + got := c.last() |
| + if got.method != a.Method || got.path != a.Path || got.key != a.Key || string(got.body) != string(a.Body) { |
| + t.Errorf("%s: server got %s %s key %q body %q; prepared %q", name, got.method, got.path, got.key, got.body, a.Body) |
| + } |
| + } |
| + |
| + // The change's and renewal's parameters, exactly. |
| + change, _ := url.ParseQuery(string(first["change"].Body)) |
| + wantChange := url.Values{ |
| + "items[0][id]": {"si_1"}, "items[0][quantity]": {"12"}, |
| + "items[1][id]": {"si_2"}, "items[1][price]": {"price_b"}, "items[1][quantity]": {"1"}, |
| + "items[2][id]": {"si_3"}, "items[2][deleted]": {"true"}, |
| + "items[3][price]": {"price_new"}, "items[3][quantity]": {"3"}, |
| + "proration_behavior": {"always_invoice"}, "payment_behavior": {"pending_if_incomplete"}, |
| + "proration_date": {strconv.FormatInt(providerDate.Unix()+1, 10)}, |
| + } |
| + if change.Encode() != wantChange.Encode() { |
| + t.Errorf("change body\n %s\nwant\n %s", change.Encode(), wantChange.Encode()) |
| + } |
| + none := changeRequest() |
| + none.Proration = billing.ProrateNone |
| + pn, err := p.PrepareChange(none) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + nv, _ := url.ParseQuery(string(pn.Body)) |
| + if nv.Get("proration_behavior") != "none" || nv.Has("payment_behavior") { |
| + t.Errorf("ProrateNone body %q", pn.Body) |
| + } |
| + if string(first["renewal"].Body) != "cancel_at_period_end=true" { |
| + t.Errorf("stop renewal body %q", first["renewal"].Body) |
| + } |
| + if r, _ := p.PrepareRenewal("sub_1", true, "k"); string(r.Body) != "cancel_at_period_end=false" { |
| + t.Errorf("resume renewal body %q", r.Body) |
| + } |
| + if string(first["customer"].Body) != "metadata%5Baccount_sqid%5D=bab" { |
| + t.Errorf("customer body %q: metadata only, no address", first["customer"].Body) |
| + } |
| + if len(first["expire"].Body) != 0 { |
| + t.Errorf("expire body %q", first["expire"].Body) |
| + } |
| + |
| + // Refused before any request: no key, a missing id, no items, an |
| + // unknown proration. |
| + n := c.count() |
| + bad := map[string]func() error{ |
| + "customer no key": func() error { _, err := p.PrepareCustomer("bab", ""); return err }, |
| + "customer no sqid": func() error { _, err := p.PrepareCustomer("", "k"); return err }, |
| + "expire bad id": func() error { _, err := p.PrepareExpire("../cs", "k"); return err }, |
| + "renewal no key": func() error { _, err := p.PrepareRenewal("sub_1", true, ""); return err }, |
| + "change no items": func() error { r := changeRequest(); r.Items = nil; _, err := p.PrepareChange(r); return err }, |
| + "change proration": func() error { r := changeRequest(); r.Proration = "later"; _, err := p.PrepareChange(r); return err }, |
| + "change bad sub": func() error { r := changeRequest(); r.Subscription = "sub 1"; _, err := p.PrepareChange(r); return err }, |
| + "checkout no key": func() error { |
| + r := checkoutRequest() |
| + r.IdempotencyKey = "" |
| + _, err := p.PrepareCheckout(r) |
| + return err |
| + }, |
| + "checkout no exp": func() error { |
| + r := checkoutRequest() |
| + r.ExpiresAt = time.Time{} |
| + _, err := p.PrepareCheckout(r) |
| + return err |
| + }, |
| + "checkout no items": func() error { r := checkoutRequest(); r.Items = nil; _, err := p.PrepareCheckout(r); return err }, |
| + } |
| + for name, f := range bad { |
| + if f() == nil { |
| + t.Errorf("%s: prepared", name) |
| + } |
| + } |
| + if c.count() != n { |
| + t.Errorf("a Prepare made a request") |
| + } |
| +} |
| + |
| +func TestPrepareCheckoutCarriesResolvedCoupon(t *testing.T) { |
| + p := prepProvider(t, "http://127.0.0.1:1", nil) |
| + req := checkoutRequest() |
| + plain, err := p.PrepareCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v, _ := url.ParseQuery(string(plain.Body)) |
| + want := url.Values{ |
| + "mode": {"subscription"}, "currency": {"usd"}, "customer": {"cus_1"}, |
| + "line_items[0][price]": {"price_p"}, "line_items[0][quantity]": {"1"}, |
| + "line_items[1][price]": {"price_a"}, "line_items[1][quantity]": {"2"}, |
| + "adaptive_pricing[enabled]": {"false"}, "billing_address_collection": {"required"}, |
| + "customer_update[address]": {"auto"}, "automatic_tax[enabled]": {"true"}, |
| + "expires_at": {strconv.FormatInt(providerDate.Add(time.Hour).Unix(), 10)}, |
| + "success_url": {req.SuccessURL}, "cancel_url": {req.CancelURL}, |
| + "allow_promotion_codes": {"true"}, |
| + "metadata[account_sqid]": {"bab"}, "metadata[checkout_intent]": {"ci_1"}, |
| + "metadata[price_book]": {"example-v1"}, "metadata[currency]": {"usd"}, |
| + "subscription_data[metadata][account_sqid]": {"bab"}, |
| + "subscription_data[metadata][checkout_intent]": {"ci_1"}, |
| + "subscription_data[metadata][price_book]": {"example-v1"}, |
| + "subscription_data[metadata][currency]": {"usd"}, |
| + } |
| + if v.Encode() != want.Encode() { |
| + t.Errorf("checkout body\n %s\nwant\n %s", v.Encode(), want.Encode()) |
| + } |
| + |
| + req.Coupon = "house_forever" |
| + house, err := p.PrepareCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hv, _ := url.ParseQuery(string(house.Body)) |
| + if hv.Get("discounts[0][coupon]") != "house_forever" || hv.Has("allow_promotion_codes") { |
| + t.Errorf("house body %q", house.Body) |
| + } |
| + // The coupon id is frozen in the bytes: the provider's own house |
| + // coupon setting plays no part. |
| + other := prepProvider(t, "http://127.0.0.1:1", func(c *ProviderConfig) { c.HouseCoupon = "another_coupon" }) |
| + again, _ := other.PrepareCheckout(req) |
| + if string(again.Body) != string(house.Body) { |
| + t.Errorf("the provider's configured coupon changed the prepared bytes") |
| + } |
| +} |
| + |
| +func TestSendVerbatimOneRequest(t *testing.T) { |
| + var c capture |
| + var mode atomic.Value |
| + mode.Store("500") |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + c.add(r) |
| + switch mode.Load() { |
| + case "500": |
| + w.WriteHeader(http.StatusInternalServerError) |
| + fmt.Fprint(w, `{"error":{"type":"api_error"}}`) |
| + case "hang": |
| + <-r.Context().Done() |
| + case "ok": |
| + fmt.Fprint(w, okBody(r.URL.Path)) |
| + case "drop": |
| + // Read the request, then close the connection with no answer. |
| + hj, _ := w.(http.Hijacker) |
| + conn, _, _ := hj.Hijack() |
| + conn.Close() |
| + } |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, err := p.PrepareChange(changeRequest()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + if _, err := p.Send(context.Background(), prep); !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("500: %v", err) |
| + } |
| + if c.count() != 1 || string(c.last().body) != string(prep.Body) || c.last().key != prep.Key { |
| + t.Fatalf("500: %d requests, body %q", c.count(), c.last().body) |
| + } |
| + |
| + mode.Store("hang") |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + _, err = p.Send(ctx, prep) |
| + cancel() |
| + if !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("timeout: %v", err) |
| + } |
| + if c.count() != 2 || string(c.last().body) != string(prep.Body) { |
| + t.Fatalf("timeout: %d requests in all", c.count()) |
| + } |
| + |
| + // A kept-alive connection dropped after the request was written: the |
| + // transport must not resend it on its own (an Idempotency-Key header |
| + // makes net/http treat a POST as replayable). |
| + mode.Store("ok") |
| + if _, err := p.Send(context.Background(), prep); err != nil { |
| + t.Fatalf("warm the connection: %v", err) |
| + } |
| + mode.Store("drop") |
| + if _, err := p.Send(context.Background(), prep); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("dropped: %v", err) |
| + } |
| + if c.count() != 4 { |
| + t.Fatalf("dropped connection: %d requests in all, want 4 (no transport retry)", c.count()) |
| + } |
| + |
| + // A malformed Prepared is never sent. |
| + for name, bad := range map[string]billing.Prepared{ |
| + "no key": {Kind: prep.Kind, Method: http.MethodPost, Path: prep.Path, Body: prep.Body}, |
| + "GET": {Kind: prep.Kind, Method: http.MethodGet, Path: prep.Path, Body: prep.Body, Key: "k"}, |
| + "bad path": {Kind: prep.Kind, Method: http.MethodPost, Path: "/v1/../x", Body: prep.Body, Key: "k"}, |
| + "other host": {Kind: prep.Kind, Method: http.MethodPost, Path: "//evil.example/v1/x", Body: prep.Body, Key: "k"}, |
| + "no kind": {Method: http.MethodPost, Path: prep.Path, Body: prep.Body, Key: "k"}, |
| + } { |
| + if _, err := p.Send(context.Background(), bad); !errors.Is(err, billing.ErrRefused) { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| + if c.count() != 4 { |
| + t.Errorf("a malformed Prepared was sent") |
| + } |
| +} |
| + |
| +func TestOutcomeClasses(t *testing.T) { |
| + type answer struct { |
| + status int |
| + body string |
| + } |
| + cases := []struct { |
| + name string |
| + ans *answer // nil: no answer at all |
| + want error // nil: success |
| + }{ |
| + {"2xx", &answer{200, ""}, nil}, |
| + {"402", &answer{402, `{"error":{"type":"card_error","code":"card_declined"}}`}, billing.ErrPaymentFailed}, |
| + {"card_error on a 400", &answer{400, `{"error":{"type":"card_error"}}`}, billing.ErrPaymentFailed}, |
| + {"409 same key executing", &answer{409, `{"error":{"type":"idempotency_error","code":"idempotency_key_in_use"}}`}, billing.ErrInFlight}, |
| + {"409 lock", &answer{409, `{"error":{"type":"invalid_request_error","code":"lock_timeout"}}`}, billing.ErrInFlight}, |
| + {"idempotency parameter mismatch", &answer{400, `{"error":{"type":"idempotency_error"}}`}, billing.ErrIdempotencyMismatch}, |
| + {"429", &answer{429, `{"error":{"type":"rate_limit_error"}}`}, billing.ErrNotExecuted}, |
| + {"400", &answer{400, `{"error":{"type":"invalid_request_error","code":"parameter_missing"}}`}, billing.ErrRefused}, |
| + {"404", &answer{404, `{"error":{"type":"invalid_request_error","code":"resource_missing"}}`}, billing.ErrRefused}, |
| + {"500", &answer{500, `{"error":{"type":"api_error"}}`}, billing.ErrIndeterminate}, |
| + {"503", &answer{503, ``}, billing.ErrIndeterminate}, |
| + {"2xx that does not decode", &answer{200, `{"nope":`}, billing.ErrIndeterminate}, |
| + {"transport error", nil, billing.ErrNoResponse}, |
| + } |
| + classes := []error{billing.ErrPaymentFailed, billing.ErrRefused, billing.ErrNotExecuted, billing.ErrInFlight, |
| + billing.ErrNoResponse, billing.ErrIndeterminate, billing.ErrIdempotencyMismatch} |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if tc.ans == nil { |
| + hj, _ := w.(http.Hijacker) |
| + conn, _, _ := hj.Hijack() |
| + conn.Close() |
| + return |
| + } |
| + body := tc.ans.body |
| + if tc.ans.status == 200 && body == "" { |
| + body = okBody(r.URL.Path) |
| + } |
| + w.WriteHeader(tc.ans.status) |
| + fmt.Fprint(w, body) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, _ := p.PrepareRenewal("sub_1", true, "key-1") |
| + res, err := p.Send(context.Background(), prep) |
| + if tc.want == nil { |
| + if err != nil || res.Subscription == nil || res.Subscription.ID != "sub_1" { |
| + t.Fatalf("success: %+v, %v", res, err) |
| + } |
| + return |
| + } |
| + if !errors.Is(err, tc.want) { |
| + t.Fatalf("err = %v, want %v", err, tc.want) |
| + } |
| + for _, other := range classes { |
| + if other != tc.want && errors.Is(err, other) { |
| + t.Errorf("err %v is also %v", err, other) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestReplayedAndProviderTime(t *testing.T) { |
| + status := http.StatusOK |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Date", providerDate.Format(http.TimeFormat)) |
| + w.Header().Set("Idempotent-Replayed", "true") |
| + w.WriteHeader(status) |
| + if status == http.StatusOK { |
| + fmt.Fprint(w, okBody(r.URL.Path)) |
| + } else { |
| + fmt.Fprint(w, `{"error":{"type":"card_error"}}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + for name, prep := range allPrepared(t, p) { |
| + res, err := p.Send(context.Background(), prep) |
| + if err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if !res.Replayed || !res.ProviderTime.Equal(providerDate) { |
| + t.Errorf("%s: Replayed %v ProviderTime %v", name, res.Replayed, res.ProviderTime) |
| + } |
| + switch name { |
| + case "customer": |
| + if res.Customer != "cus_9" { |
| + t.Errorf("customer = %q", res.Customer) |
| + } |
| + case "checkout", "expire": |
| + if res.Checkout == nil || res.Checkout.IntentID != "ci_1" { |
| + t.Errorf("%s: checkout = %+v", name, res.Checkout) |
| + } |
| + case "change", "renewal": |
| + if res.Subscription == nil || !res.Subscription.ProviderTime.Equal(providerDate) || res.Subscription.Items[0].ItemID != "si_1" { |
| + t.Errorf("%s: subscription = %+v", name, res.Subscription) |
| + } |
| + } |
| + } |
| + status = http.StatusPaymentRequired |
| + prep, _ := p.PrepareChange(changeRequest()) |
| + res, err := p.Send(context.Background(), prep) |
| + if !errors.Is(err, billing.ErrPaymentFailed) || !res.Replayed || !res.ProviderTime.Equal(providerDate) { |
| + t.Errorf("replayed decline: %+v, %v", res, err) |
| + } |
| + // A read carries its Date too. |
| + status = http.StatusOK |
| + sub, err := p.Subscription(context.Background(), "sub_1") |
| + if err != nil || !sub.ProviderTime.Equal(providerDate) { |
| + t.Errorf("read ProviderTime: %+v, %v", sub, err) |
| + } |
| +} |
| + |
| +// recorder is a ClockRecorder on a frozen monotonic clock: Now is exactly |
| +// the last observed Date. |
| +func recorder() *billing.ClockRecorder { |
| + return &billing.ClockRecorder{Monotonic: func() time.Duration { return 0 }} |
| +} |
| + |
| +func TestObserveDateOnEveryResponse(t *testing.T) { |
| + var answer atomic.Value |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + a := answer.Load().(string) |
| + if a == "hang" { |
| + <-r.Context().Done() |
| + return |
| + } |
| + w.Header().Set("Date", providerDate.Format(http.TimeFormat)) |
| + switch a { |
| + case "ok": |
| + fmt.Fprint(w, okBody("/v1/subscriptions/sub_1")) |
| + case "404": |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"type":"invalid_request_error"}}`) |
| + case "500": |
| + w.WriteHeader(http.StatusInternalServerError) |
| + case "empty": |
| + fmt.Fprint(w, `{"data":[],"has_more":false}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, _ := p.PrepareRenewal("sub_1", true, "k") |
| + calls := map[string]func(ctx context.Context){ |
| + "ok": func(ctx context.Context) { _, _ = p.Subscription(ctx, "sub_1") }, |
| + "404": func(ctx context.Context) { _, _ = p.Subscription(ctx, "sub_1") }, |
| + "500": func(ctx context.Context) { _, _ = p.Send(ctx, prep) }, |
| + "empty": func(ctx context.Context) { _, _ = p.LiveSubscriptions(ctx, "cus_1") }, |
| + } |
| + for name, call := range calls { |
| + answer.Store(name) |
| + rec := recorder() |
| + call(billing.WithClock(context.Background(), rec)) |
| + if now, err := rec.Now(); err != nil || !now.Equal(providerDate) { |
| + t.Errorf("%s: recorder = %v, %v; want %v", name, now, err, providerDate) |
| + } |
| + } |
| + answer.Store("hang") |
| + rec := recorder() |
| + ctx, cancel := context.WithTimeout(billing.WithClock(context.Background(), rec), 100*time.Millisecond) |
| + _, err := p.Subscription(ctx, "sub_1") |
| + cancel() |
| + if err == nil { |
| + t.Fatal("hung read succeeded") |
| + } |
| + if _, err := rec.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Errorf("a timeout before headers fed the recorder: %v", err) |
| + } |
| +} |
| + |
| +func TestClockProbeIsOnePriceGet(t *testing.T) { |
| + var c capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + c.add(r) |
| + w.Header().Set("Date", providerDate.Format(http.TimeFormat)) |
| + fmt.Fprintf(w, `{"id":%q,"livemode":false}`, r.URL.Path[len("/v1/prices/"):]) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, func(cfg *ProviderConfig) { cfg.PriceIDs = []string{"price_c", "price_a", "price_b"} }) |
| + rec := recorder() |
| + if err := p.ClockProbe(billing.WithClock(context.Background(), rec)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.count() != 1 || c.last().method != http.MethodGet || c.last().path != "/v1/prices/price_a" { |
| + t.Fatalf("probe: %d requests, last %+v", c.count(), c.last()) |
| + } |
| + if now, err := rec.Now(); err != nil || !now.Equal(providerDate) { |
| + t.Errorf("recorder = %v, %v", now, err) |
| + } |
| + // No price configured: an error, and no request. |
| + none := prepProvider(t, srv.URL, nil) |
| + if err := none.ClockProbe(context.Background()); err == nil { |
| + t.Error("probe with no price succeeded") |
| + } |
| + if c.count() != 1 { |
| + t.Errorf("probe with no price made a request") |
| + } |
| +} |
| + |
| +// listServer serves a customer's subscriptions, ascending by id, the way |
| +// Stripe pages: limit, starting_after, has_more. |
| +type listServer struct { |
| + t *testing.T |
| + mu sync.Mutex |
| + objects []string // JSON objects with "id" |
| + ids []string |
| + queries []url.Values |
| +} |
| + |
| +func (s *listServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + q := r.URL.Query() |
| + s.queries = append(s.queries, q) |
| + limit, _ := strconv.Atoi(q.Get("limit")) |
| + if limit <= 0 { |
| + limit = 10 |
| + } |
| + start := 0 |
| + if after := q.Get("starting_after"); after != "" { |
| + for i, id := range s.ids { |
| + if id == after { |
| + start = i + 1 |
| + } |
| + } |
| + } |
| + stop := min(start+limit, len(s.ids)) |
| + w.Header().Set("Date", providerDate.Format(http.TimeFormat)) |
| + fmt.Fprint(w, `{"data":[`) |
| + for i := start; i < stop; i++ { |
| + if i > start { |
| + fmt.Fprint(w, ",") |
| + } |
| + fmt.Fprint(w, s.objects[i]) |
| + } |
| + fmt.Fprintf(w, `],"has_more":%v}`, stop < len(s.ids)) |
| +} |
| + |
| +func (s *listServer) addSub(id, status string) { |
| + s.ids = append(s.ids, id) |
| + s.objects = append(s.objects, fmt.Sprintf(`{"id":%q,"customer":"cus_1","status":%q,"livemode":false}`, id, status)) |
| +} |
| + |
| +func (s *listServer) requests() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return len(s.queries) |
| +} |
| + |
| +func TestLiveSubscriptionsPagesToCompletion(t *testing.T) { |
| + ls := &listServer{t: t} |
| + for i := 0; i < 200; i++ { |
| + ls.addSub(fmt.Sprintf("sub_%04d", i), "canceled") |
| + } |
| + ls.addSub("sub_9999", "active") |
| + srv := httptest.NewServer(ls) |
| + defer srv.Close() |
| + ids, err := prepProvider(t, srv.URL, nil).LiveSubscriptions(context.Background(), "cus_1") |
| + if err != nil || len(ids) != 1 || ids[0] != "sub_9999" { |
| + t.Fatalf("ids = %v, %v", ids, err) |
| + } |
| + if ls.requests() != 3 { |
| + t.Fatalf("%d requests, want 3", ls.requests()) |
| + } |
| + for i, q := range ls.queries { |
| + if q.Get("customer") != "cus_1" || q.Get("status") != "all" || q.Get("limit") != "100" { |
| + t.Errorf("page %d query %v", i, q) |
| + } |
| + } |
| + if ls.queries[0].Has("starting_after") || ls.queries[1].Get("starting_after") != "sub_0099" || ls.queries[2].Get("starting_after") != "sub_0199" { |
| + t.Errorf("cursors: %v %v %v", ls.queries[0], ls.queries[1], ls.queries[2]) |
| + } |
| + // Every live status counts; ended ones do not. |
| + ls2 := &listServer{t: t} |
| + for _, st := range []string{"active", "trialing", "past_due", "incomplete", "unpaid", "canceled", "incomplete_expired", "paused"} { |
| + ls2.addSub("sub_"+st, st) |
| + } |
| + srv2 := httptest.NewServer(ls2) |
| + defer srv2.Close() |
| + ids, err = prepProvider(t, srv2.URL, nil).LiveSubscriptions(context.Background(), "cus_1") |
| + if err != nil || len(ids) != 5 { |
| + t.Errorf("live ids = %v, %v", ids, err) |
| + } |
| + if _, err := prepProvider(t, srv2.URL, nil).LiveSubscriptions(context.Background(), "../cus"); err == nil { |
| + t.Error("bad customer id accepted") |
| + } |
| +} |
| + |
| +func TestLiveSubscriptionsEmptyListIsOneRequest(t *testing.T) { |
| + ls := &listServer{t: t} |
| + srv := httptest.NewServer(ls) |
| + defer srv.Close() |
| + ids, err := prepProvider(t, srv.URL, nil).LiveSubscriptions(context.Background(), "cus_1") |
| + if err != nil || len(ids) != 0 || ls.requests() != 1 { |
| + t.Fatalf("ids = %v, %v after %d requests", ids, err, ls.requests()) |
| + } |
| +} |
| + |
| +func TestLiveSubscriptionsIncomplete(t *testing.T) { |
| + ls := &listServer{t: t} |
| + for i := 0; i < billing.MaxListPages*100+1; i++ { |
| + ls.addSub(fmt.Sprintf("sub_%05d", i), "canceled") |
| + } |
| + srv := httptest.NewServer(ls) |
| + defer srv.Close() |
| + ids, err := prepProvider(t, srv.URL, nil).LiveSubscriptions(context.Background(), "cus_1") |
| + if !errors.Is(err, billing.ErrIncomplete) || ids != nil { |
| + t.Fatalf("ids = %v, err = %v; want ErrIncomplete", ids, err) |
| + } |
| + if ls.requests() != billing.MaxListPages { |
| + t.Errorf("%d requests, want %d", ls.requests(), billing.MaxListPages) |
| + } |
| + // Exactly ten full pages is complete. |
| + ls.ids, ls.objects = ls.ids[:billing.MaxListPages*100], ls.objects[:billing.MaxListPages*100] |
| + ls.queries = nil |
| + if _, err := prepProvider(t, srv.URL, nil).LiveSubscriptions(context.Background(), "cus_1"); err != nil { |
| + t.Errorf("ten pages: %v", err) |
| + } |
| + // A page that says there is more but holds nothing is broken, not |
| + // incomplete and not empty. |
| + broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + fmt.Fprint(w, `{"data":[],"has_more":true}`) |
| + })) |
| + defer broken.Close() |
| + if ids, err := prepProvider(t, broken.URL, nil).LiveSubscriptions(context.Background(), "cus_1"); err == nil || ids != nil { |
| + t.Errorf("broken pagination: %v, %v", ids, err) |
| + } |
| +} |
| + |
| +func TestCustomerCheckoutsPages(t *testing.T) { |
| + ls := &listServer{t: t} |
| + for i := 0; i < 150; i++ { |
| + id := fmt.Sprintf("cs_%04d", i) |
| + ls.ids = append(ls.ids, id) |
| + ls.objects = append(ls.objects, fmt.Sprintf(`{"id":%q,"livemode":false,"status":"expired","customer":"cus_1","expires_at":1793000000,"metadata":{"checkout_intent":"ci_%d"}}`, id, i)) |
| + } |
| + ls.ids = append(ls.ids, "cs_9999") |
| + ls.objects = append(ls.objects, `{"id":"cs_9999","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9999","customer":"cus_1","subscription":null,"expires_at":1793000000,"metadata":{"checkout_intent":"ci_new"}}`) |
| + srv := httptest.NewServer(ls) |
| + defer srv.Close() |
| + after := providerDate.Add(1500 * time.Millisecond) |
| + got, err := prepProvider(t, srv.URL, nil).CustomerCheckouts(context.Background(), "cus_1", after) |
| + if err != nil || len(got) != 151 || ls.requests() != 2 { |
| + t.Fatalf("%d sessions, %v, after %d requests", len(got), err, ls.requests()) |
| + } |
| + last := got[150] |
| + want := billing.CheckoutInfo{ID: "cs_9999", URL: "https://checkout.stripe.com/c/pay/cs_9999", Customer: "cus_1", IntentID: "ci_new", |
| + State: billing.CheckoutOpen, ExpiresAt: time.Unix(1793000000, 0).UTC()} |
| + if last != want { |
| + t.Errorf("last = %+v\nwant %+v", last, want) |
| + } |
| + if got[0].State != billing.CheckoutExpired { |
| + t.Errorf("first state %q", got[0].State) |
| + } |
| + // Inclusive, to the second: a session created in the same second as |
| + // createdAfter is listed. |
| + for i, q := range ls.queries { |
| + if q.Get("customer") != "cus_1" || q.Get("created[gte]") != strconv.FormatInt(providerDate.Unix()+1, 10) || q.Has("created[gt]") || q.Get("limit") != "100" { |
| + t.Errorf("page %d query %v", i, q) |
| + } |
| + } |
| + if ls.queries[1].Get("starting_after") != "cs_0099" { |
| + t.Errorf("cursor %v", ls.queries[1]) |
| + } |
| +} |
| + |
| +func TestRenewalInvoiceQuantities(t *testing.T) { |
| + periodStart := time.Date(2027, 1, 2, 3, 4, 5, 0, time.UTC) |
| + ps := periodStart.Unix() |
| + year := int64(365 * 24 * 3600) |
| + inv := &listServer{t: t} |
| + addInv := func(id, reason string, start, end int64) { |
| + inv.ids = append(inv.ids, id) |
| + inv.objects = append(inv.objects, fmt.Sprintf(`{"id":%q,"subscription":"sub_1","billing_reason":%q,"status":"paid","period_start":%d,"period_end":%d}`, id, reason, start, end)) |
| + } |
| + // Stripe's invoice period looks back one period on a renewal: the |
| + // renewal for the period starting at ps has period_end == ps. |
| + for i := 0; i < 120; i++ { |
| + addInv(fmt.Sprintf("in_%04d", i), "subscription_update", ps-100, ps-100) |
| + } |
| + addInv("in_create", "subscription_create", ps-year, ps-year) |
| + addInv("in_next", "subscription_cycle", ps, ps+year) // next year's renewal: period_start == ps, not it |
| + addInv("in_cycle", "subscription_cycle", ps-year, ps) |
| + lines := &listServer{t: t} |
| + addLine := func(id, price string, qty int64, typ string, proration bool) { |
| + lines.ids = append(lines.ids, id) |
| + lines.objects = append(lines.objects, fmt.Sprintf(`{"id":%q,"type":%q,"proration":%v,"quantity":%d,"price":{"id":%q}}`, id, typ, proration, qty, price)) |
| + } |
| + for i := 0; i < 100; i++ { |
| + price := "price_a" |
| + if i == 0 { |
| + price = "price_p" |
| + } |
| + addLine(fmt.Sprintf("il_%04d", i), price, 1, "subscription", false) |
| + } |
| + addLine("il_0100", "price_a", 2, "subscription", false) |
| + addLine("il_0101", "price_a", 5, "subscription", true) // a proration line is not the renewal's quantity |
| + addLine("il_0102", "price_x", 1, "invoiceitem", false) |
| + var invoicePaths []string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/v1/invoices": |
| + invoicePaths = append(invoicePaths, r.URL.RawQuery) |
| + if r.URL.Query().Get("subscription") != "sub_1" || r.URL.Query().Has("status") { |
| + t.Errorf("invoice query %q", r.URL.RawQuery) |
| + } |
| + inv.ServeHTTP(w, r) |
| + case "/v1/invoices/in_cycle/lines": |
| + lines.ServeHTTP(w, r) |
| + default: |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"type":"invalid_request_error"}}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + got, err := p.RenewalInvoice(context.Background(), "sub_1", periodStart) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got.Invoice != "in_cycle" || !got.PeriodStart.Equal(periodStart) || len(got.ByPrice) != 2 || got.ByPrice["price_p"] != 1 || got.ByPrice["price_a"] != 101 { |
| + t.Errorf("got %+v", got) |
| + } |
| + if inv.requests() != 2 || lines.requests() != 2 { |
| + t.Errorf("%d invoice pages, %d line pages; want 2 and 2", inv.requests(), lines.requests()) |
| + } |
| + if _, err := p.RenewalInvoice(context.Background(), "sub_1", periodStart.Add(time.Hour)); !errors.Is(err, billing.ErrNotFound) { |
| + t.Errorf("no such renewal: %v", err) |
| + } |
| + if _, err := p.RenewalInvoice(context.Background(), "../sub", periodStart); err == nil { |
| + t.Error("bad subscription id accepted") |
| + } |
| +} |
| + |
| +func TestCollectingOf(t *testing.T) { |
| + cases := []struct { |
| + status, invoice string |
| + pending, want bool |
| + }{ |
| + {"active", "paid", false, false}, |
| + {"active", "", false, false}, |
| + {"active", "open", false, true}, |
| + {"active", "draft", false, false}, |
| + {"active", "paid", true, true}, |
| + {"past_due", "paid", false, true}, |
| + {"unpaid", "", false, true}, |
| + {"incomplete", "open", false, true}, |
| + {"trialing", "paid", false, false}, |
| + {"canceled", "open", false, false}, |
| + {"incomplete_expired", "open", false, false}, |
| + } |
| + for _, tc := range cases { |
| + if got := collectingOf(tc.status, tc.invoice, tc.pending); got != tc.want { |
| + t.Errorf("collectingOf(%q, %q, %v) = %v, want %v", tc.status, tc.invoice, tc.pending, got, tc.want) |
| + } |
| + } |
| + // End to end: the read expands latest_invoice and maps pending_update. |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Query().Get("expand[]") != "latest_invoice" { |
| + t.Errorf("read query %q", r.URL.RawQuery) |
| + } |
| + fmt.Fprint(w, `{"id":"sub_1","customer":"cus_1","status":"active","livemode":false,"currency":"usd", |
| + "pending_update":{"expires_at":1793000000},"latest_invoice":{"id":"in_1","status":"open"}, |
| + "items":{"has_more":false,"data":[{"id":"si_1","quantity":1,"price":{"id":"price_p","currency":"usd"}}]}}`) |
| + })) |
| + defer srv.Close() |
| + sub, err := prepProvider(t, srv.URL, nil).Subscription(context.Background(), "sub_1") |
| + if err != nil || !sub.Collecting || !sub.PendingUpdate || !sub.PendingExpires.Equal(time.Unix(1793000000, 0).UTC()) { |
| + t.Errorf("sub = %+v, %v", sub, err) |
| + } |
| +} |
diff --git a/internal/billingstripe/unimplemented.go b/internal/billingstripe/unimplemented.go| deleted file mode 100644 |
| index b89812c3d..000000000 |
| --- a/internal/billingstripe/unimplemented.go |
| +++ /dev/null |
| @@ -1,60 +0,0 @@ |
| -package billingstripe |
| - |
| -import ( |
| - "context" |
| - "errors" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/billing" |
| -) |
| - |
| -// errNotImplemented is every Plan 6b provider method until Task 5 builds |
| -// the Stripe encoding and outcome classification. Nothing here makes a |
| -// request. |
| -var errNotImplemented = errors.New("billingstripe: not implemented yet (plan 6b task 5)") |
| - |
| -func (p *Provider) PrepareCustomer(string, string) (billing.Prepared, error) { |
| - return billing.Prepared{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) PrepareCheckout(billing.CheckoutRequest) (billing.Prepared, error) { |
| - return billing.Prepared{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) PrepareExpire(string, string) (billing.Prepared, error) { |
| - return billing.Prepared{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) PrepareChange(billing.ChangeRequest) (billing.Prepared, error) { |
| - return billing.Prepared{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) PrepareRenewal(string, bool, string) (billing.Prepared, error) { |
| - return billing.Prepared{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) Send(context.Context, billing.Prepared) (billing.Result, error) { |
| - return billing.Result{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) LiveSubscriptions(context.Context, string) ([]string, error) { |
| - return nil, errNotImplemented |
| -} |
| - |
| -func (p *Provider) CustomerCheckouts(context.Context, string, time.Time) ([]billing.CheckoutInfo, error) { |
| - return nil, errNotImplemented |
| -} |
| - |
| -func (p *Provider) Checkout(context.Context, string) (billing.CheckoutInfo, error) { |
| - return billing.CheckoutInfo{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) RenewalInvoice(context.Context, string, time.Time) (billing.InvoiceQuantities, error) { |
| - return billing.InvoiceQuantities{}, errNotImplemented |
| -} |
| - |
| -func (p *Provider) PortalURL(context.Context, string, string, string) (string, error) { |
| - return "", errNotImplemented |
| -} |
| - |
| -func (p *Provider) ClockProbe(context.Context) error { return errNotImplemented } |
diff --git a/internal/console/billing.go b/internal/console/billing.go| index 7255dcf8c..1319b6aa0 100644 |
| --- a/internal/console/billing.go |
| +++ b/internal/console/billing.go |
| @@ -16,6 +16,10 @@ type BillingConfig struct { |
| Book *plans.PriceBook |
| Prices billing.PriceMap |
| Provider billing.Provider |
| + // HouseCoupon is the coupon id a house account's Checkout carries |
| + // (CARLOS_STRIPE_HOUSE_COUPON), "" for none. The console copies it into |
| + // CheckoutRequest.Coupon, so it is frozen in the prepared bytes. |
| + HouseCoupon string |
| } |
| // billingRuntime is a server's billing state. ready is set once the |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 9408fdccd..ba6c0347e 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -2,9 +2,12 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "log" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| ) |
| const ( |
| @@ -105,12 +108,13 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| s.billingDiscoveryPass(ctx, now) |
| } |
| -// billingDiscoveryPass asks the provider for the subscriptions of each |
| -// customer bound within billingDiscoveryWindow that has none recorded, or |
| -// whose last discovery left a candidate unsynced, and syncs each one |
| -// (Astra finding 3): a first purchase whose every event was |
| +// billingDiscoveryPass asks the provider for the live subscriptions of |
| +// each customer bound within billingDiscoveryWindow that has none |
| +// recorded, or whose last discovery left a candidate unsynced, and syncs |
| +// each one (Astra finding 3): a first purchase whose every event was |
| // missed, because billing was not ready while the provider retried, is |
| -// still found. One list request per such customer per pass. |
| +// still found. The list is exhaustive (Provider.LiveSubscriptions, up to |
| +// billing.MaxListPages pages per such customer per pass). |
| func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| var after int64 |
| for ctx.Err() == nil { |
| @@ -145,8 +149,15 @@ func (s *Server) discoverCustomer(ctx context.Context, b billingAccount, now tim |
| return |
| } |
| failed := false |
| - ids, err := s.billing.cfg.Provider.CustomerSubscriptions(ctx, b.Customer) |
| - if err != nil { |
| + ids, err := s.billing.cfg.Provider.LiveSubscriptions(ctx, b.Customer) |
| + switch { |
| + case errors.Is(err, billing.ErrIncomplete): |
| + // Discovery observes; it never acts on part of a list (Invariant |
| + // 3). Nothing is synced, and the discovery stays outstanding. |
| + failed = true |
| + ids = nil |
| + log.Printf("console: billing discovery: account %d: customer %s has more subscriptions than one list may read; nothing changed", b.AccountID, b.Customer) |
| + case err != nil: |
| failed = true |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| } |
diff --git a/internal/console/billingrecovery_test.go b/internal/console/billingrecovery_test.go| index 55297e89d..bd593a8ae 100644 |
| --- a/internal/console/billingrecovery_test.go |
| +++ b/internal/console/billingrecovery_test.go |
| @@ -120,10 +120,10 @@ func TestSyncPassDiscoversAMissedFirstPurchase(t *testing.T) { |
| if err := bf.st.SetBillingCustomer(old.ID, "cus_old", billingNow); err != nil { |
| t.Fatal(err) |
| } |
| - bf.fake.CustomerCalls = 0 |
| + before := bf.liveListCalls() |
| bf.srv.billingSyncPass(context.Background(), billingNow.Add(billingDiscoveryWindow+time.Hour)) |
| - if bf.fake.CustomerCalls != 0 { |
| - t.Fatalf("discovery asked about %d customers past the window", bf.fake.CustomerCalls) |
| + if bf.liveListCalls() != before { |
| + t.Fatalf("discovery read %d pages for a customer past the window", bf.liveListCalls()-before) |
| } |
| } |
| @@ -239,10 +239,10 @@ func TestDiscoveryKeepsAFailedCandidate(t *testing.T) { |
| t.Fatalf("billing row = %+v", b) |
| } |
| // Every candidate resolved: the customer is no longer asked about. |
| - bf.fake.CustomerCalls = 0 |
| + before := bf.liveListCalls() |
| bf.srv.billingSyncPass(context.Background(), billingNow.Add(3*time.Hour)) |
| - if bf.fake.CustomerCalls != 0 { |
| - t.Fatalf("resolved customer still in discovery: %d calls", bf.fake.CustomerCalls) |
| + if bf.liveListCalls() != before { |
| + t.Fatalf("resolved customer still in discovery: %d calls", bf.liveListCalls()-before) |
| } |
| } |
| @@ -306,13 +306,13 @@ func TestCloseMissingRacingASyncKeepsTheSync(t *testing.T) { |
| } |
| // Astra round 3: the discovery marker is durable before any candidate |
| -// commits. At the moment the second candidate is read (the first, an ended |
| -// subscription, already committed), a console that stopped there would |
| -// still find the customer on the discovery list. |
| +// commits. At the moment the second candidate is read (the first, a live |
| +// past-due subscription, already committed), a console that stopped there |
| +// would still find the customer on the discovery list. |
| func TestDiscoveryMarkerIsDurableBeforeACandidateCommits(t *testing.T) { |
| bf := newBillingFixture(t) |
| bf.ready(t) |
| - bf.put(bf.personalSub("sub_a", "incomplete_expired", nil)) |
| + bf.put(bf.personalSub("sub_a", "past_due", nil)) |
| bf.put(bf.personalSub("sub_b", "active", nil)) |
| pass := billingNow.Add(time.Hour) |
| var checked bool |
| @@ -364,10 +364,10 @@ func TestDiscoverySkipsACustomerWhoseMarkerCannotBeWritten(t *testing.T) { |
| WHEN NEW.discover_retry = 1 BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| t.Fatal(err) |
| } |
| - bf.fake.CustomerCalls = 0 |
| + before := bf.liveListCalls() |
| bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| - if bf.fake.CustomerCalls != 0 { |
| - t.Fatalf("discovery listed the customer's subscriptions without its marker: %d calls", bf.fake.CustomerCalls) |
| + if bf.liveListCalls() != before { |
| + t.Fatalf("discovery listed the customer's subscriptions without its marker: %d calls", bf.liveListCalls()-before) |
| } |
| if b, _ := bf.st.BillingAccount(bf.acct.ID); b.Subscription != "" { |
| t.Fatalf("a candidate committed without the marker: %+v", b) |
| @@ -448,9 +448,58 @@ func TestDiscoverySuccessResolvesItsProblemWithTheMarker(t *testing.T) { |
| if open, _ := bf.st.BillingProblems(false); len(open) != 0 { |
| t.Fatalf("discovery_failing left open after a failed resolve: %+v", open) |
| } |
| - bf.fake.CustomerCalls = 0 |
| + before := bf.liveListCalls() |
| bf.srv.billingSyncPass(context.Background(), pass.Add(2*time.Hour)) |
| - if bf.fake.CustomerCalls != 0 { |
| - t.Fatalf("customer still in discovery after both succeeded: %d calls", bf.fake.CustomerCalls) |
| + if bf.liveListCalls() != before { |
| + t.Fatalf("customer still in discovery after both succeeded: %d calls", bf.liveListCalls()-before) |
| + } |
| +} |
| + |
| +// liveListCalls is the number of LiveSubscriptions pages discovery has |
| +// asked the provider for. |
| +func (bf *billingFixture) liveListCalls() int { |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + return bf.fake.CallsBy["LiveSubscriptions"] |
| +} |
| + |
| +// Invariant 3: discovery examines every one of the customer's |
| +// subscriptions, so a live one behind more than a page of ended ones is |
| +// still found. A list longer than billing.MaxListPages pages is logged and |
| +// changes nothing: no candidate is synced and the discovery stays |
| +// outstanding. |
| +func TestDiscoveryUsesExhaustiveList(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + for i := 0; i < 150; i++ { |
| + bf.put(bf.personalSub(fmt.Sprintf("sub_a%04d", i), "canceled", nil)) |
| + } |
| + bf.put(bf.personalSub("sub_z", "active", nil)) |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("a live subscription behind 150 ended ones was not found: plan %q", p) |
| + } |
| + if n := bf.liveListCalls(); n != 2 { |
| + t.Errorf("discovery read %d pages, want 2", n) |
| + } |
| + |
| + // Past the page limit: incomplete, so nothing is adopted. |
| + bf2 := newBillingFixture(t) |
| + bf2.ready(t) |
| + for i := 0; i < billing.MaxListPages*100; i++ { |
| + bf2.put(bf2.personalSub(fmt.Sprintf("sub_a%05d", i), "canceled", nil)) |
| + } |
| + bf2.put(bf2.personalSub("sub_z", "active", nil)) |
| + bf2.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| + if p := bf2.plan(t); p == "personal" { |
| + t.Fatal("an incomplete list adopted a subscription") |
| + } |
| + if b, _ := bf2.st.BillingAccount(bf2.acct.ID); b.Subscription != "" { |
| + t.Fatalf("an incomplete list recorded a subscription: %+v", b) |
| + } |
| + before := bf2.liveListCalls() |
| + bf2.srv.billingSyncPass(context.Background(), billingNow.Add(billingDiscoveryWindow+2*time.Hour)) |
| + if bf2.liveListCalls() == before { |
| + t.Error("an incomplete discovery was not kept outstanding for the next pass") |
| } |
| } |