billing: create shared customers and save cards without subscriptions
Reuse the persisted customer-create path with optional owner email and tax location. Add owner-only card setup and save domain payment methods for future use.
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
17 files changed,
+469
−45
internal/billing/billing.go+14 −1internal/billing/billingtest/fake.go+30 −6internal/billingstripe/card_test.go+94 −0internal/billingstripe/payment.go+33 −20internal/billingstripe/payment_test.go+3 −1internal/billingstripe/prepared.go+34 −4internal/console/billingcard.go+68 −0internal/console/billingcard_test.go+82 −0internal/console/billingcheckout.go+4 −4internal/console/billingcustomer.go+65 −0internal/console/billingpage.go+9 −2internal/console/billingpage_copy.go+4 −0internal/console/billingpage_test.go+7 −7internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_nonapp_test.go+16 −0internal/console/server.go+1 −0internal/console/templates/billing.html+4 −0
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index a0bb61f0c..a154e6a60 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -143,6 +143,17 @@ type CheckoutRequest struct { |
| IdempotencyKey string |
| } |
| +// CustomerDetails supplies an owner's email and optional tax location at creation. |
| +type CustomerDetails struct{ Email, Country, PostalCode string } |
| + |
| +func (CustomerDetails) String() string { return "billing.CustomerDetails{redacted}" } |
| +func (d CustomerDetails) GoString() string { return d.String() } |
| + |
| +// SetupCheckoutRequest saves a card on an existing customer without a charge. |
| +type SetupCheckoutRequest struct { |
| + AccountSqid, Customer, SuccessURL, CancelURL, Key string |
| +} |
| + |
| // PaymentCheckoutRequest creates a one-off Checkout payment for later capture. |
| type PaymentCheckoutRequest struct { |
| AccountSqid, Customer, Currency string |
| @@ -196,6 +207,7 @@ type CheckoutInfo struct { |
| // The kinds of Prepared. |
| const ( |
| + PreparedSetupCheckout = "setup_checkout" |
| PreparedCustomer = "customer" |
| PreparedCheckout = "checkout" |
| PreparedExpire = "expire" |
| @@ -297,7 +309,8 @@ type Provider interface { |
| // The Prepare methods encode a write exactly as Send will send it, with |
| // the given idempotency key. They make no request. |
| - PrepareCustomer(accountSqid, key string) (Prepared, error) |
| + PrepareCustomer(accountSqid, key string, details ...CustomerDetails) (Prepared, error) |
| + PrepareSetupCheckout(req SetupCheckoutRequest) (Prepared, error) |
| PrepareCheckout(req CheckoutRequest) (Prepared, error) |
| PrepareExpire(sessionID, key string) (Prepared, error) |
| PrepareChange(req ChangeRequest) (Prepared, error) |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 445fbebe5..ab4766e20 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -76,7 +76,10 @@ const ( |
| const maxPage = 100 |
| // Customer is a customer at the provider. |
| -type Customer struct{ ID, Account string } |
| +type Customer struct { |
| + ID, Account string |
| + Details billing.CustomerDetails |
| +} |
| // Invoice is an invoice at the provider. Lines use PriceID and Quantity. |
| type Invoice struct { |
| @@ -784,7 +787,8 @@ func (f *Fake) Writes() int { |
| // ---- prepared requests ---- |
| type customerBody struct { |
| - Account string `json:"account"` |
| + Account string `json:"account"` |
| + Details billing.CustomerDetails `json:"details,omitempty"` |
| } |
| type checkoutBody struct { |
| @@ -832,7 +836,7 @@ func fromUnix(s int64) time.Time { |
| func pathFor(kind string, body any) string { |
| switch b := body.(type) { |
| - case *paymentCheckoutBody: |
| + case *billing.SetupCheckoutRequest, *paymentCheckoutBody: |
| return "/v1/checkout/sessions" |
| case *paymentActionBody: |
| action := "capture" |
| @@ -866,11 +870,18 @@ func prepare(kind, key string, body any) (billing.Prepared, error) { |
| } |
| // PrepareCustomer encodes a customer create for the account. |
| -func (f *Fake) PrepareCustomer(accountSqid, key string) (billing.Prepared, error) { |
| +func (f *Fake) PrepareCustomer(accountSqid, key string, details ...billing.CustomerDetails) (billing.Prepared, error) { |
| if accountSqid == "" { |
| return billing.Prepared{}, errors.New("billingtest: customer: no account") |
| } |
| - return prepare(billing.PreparedCustomer, key, &customerBody{Account: accountSqid}) |
| + body := &customerBody{Account: accountSqid} |
| + if len(details) > 1 { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + if len(details) == 1 { |
| + body.Details = details[0] |
| + } |
| + return prepare(billing.PreparedCustomer, key, body) |
| } |
| // PrepareCheckout encodes a Checkout create. |
| @@ -920,6 +931,8 @@ func (f *Fake) PrepareRenewal(subscription string, renew bool, key string) (bill |
| func decode(p billing.Prepared) (any, error) { |
| var body any |
| switch p.Kind { |
| + case billing.PreparedSetupCheckout: |
| + body = &billing.SetupCheckoutRequest{} |
| case billing.PreparedPaymentCheckout: |
| body = &paymentCheckoutBody{} |
| case billing.PreparedCapture, billing.PreparedCancelPayment: |
| @@ -1121,9 +1134,13 @@ func (f *Fake) execute(body any) (billing.Result, error) { |
| return billing.Result{Payment: &info}, nil |
| } |
| return billing.Result{}, billing.ErrRefused |
| + case *billing.SetupCheckoutRequest: |
| + id := f.nextID("cs") |
| + info := billing.CheckoutInfo{ID: id, URL: "https://checkout.example.test/c/" + id, Customer: b.Customer, State: billing.CheckoutOpen} |
| + return billing.Result{Checkout: &info}, nil |
| case *customerBody: |
| id := f.nextID("cus") |
| - f.Customers[id] = &Customer{ID: id, Account: b.Account} |
| + f.Customers[id] = &Customer{ID: id, Account: b.Account, Details: b.Details} |
| return billing.Result{Customer: id}, nil |
| case *checkoutBody: |
| id := f.nextID("cs") |
| @@ -1532,3 +1549,10 @@ func (f *Fake) CompletePaymentCheckout(sessionID string) (string, error) { |
| s.Authorised = true |
| return s.PaymentIntent, nil |
| } |
| + |
| +func (f *Fake) PrepareSetupCheckout(req billing.SetupCheckoutRequest) (billing.Prepared, error) { |
| + if req.Customer == "" || req.AccountSqid == "" || req.SuccessURL == "" || req.CancelURL == "" { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + return prepare(billing.PreparedSetupCheckout, req.Key, &req) |
| +} |
diff --git a/internal/billingstripe/card_test.go b/internal/billingstripe/card_test.go| new file mode 100644 |
| index 000000000..b64571506 |
| --- /dev/null |
| +++ b/internal/billingstripe/card_test.go |
| @@ -0,0 +1,94 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func TestCustomerDetailsForm(t *testing.T) { |
| + var cap capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cap.add(r) |
| + fmt.Fprint(w, `{"id":"cus_1","livemode":false}`) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, err := p.PrepareCustomer("bab", "customer:bab:1", billing.CustomerDetails{Email: "owner@example.com", Country: "IE", PostalCode: "D01 A123"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + for key, want := range map[string]string{"metadata[account_sqid]": "bab", "email": "owner@example.com", "address[country]": "IE", "address[postal_code]": "D01 A123"} { |
| + if form.Get(key) != want { |
| + t.Errorf("%s=%q, want %q", key, form.Get(key), want) |
| + } |
| + } |
| + if _, err := p.Send(context.Background(), prep); err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(cap.last().body) != string(prep.Body) || cap.last().key != prep.Key { |
| + t.Fatal("prepared customer changed") |
| + } |
| +} |
| + |
| +func TestSetupCheckoutFormAndRefusals(t *testing.T) { |
| + for _, which := range []string{"ok", "wrong customer", "wrong mode", "untrusted url", "missing mode", "missing livemode"} { |
| + t.Run(which, func(t *testing.T) { |
| + var cap capture |
| + response := `{"id":"cs_setup","mode":"setup","status":"open","livemode":false,"customer":"cus_1","url":"https://checkout.stripe.com/c/pay/cs_setup"}` |
| + switch which { |
| + case "wrong customer": |
| + response = strings.ReplaceAll(response, "cus_1", "cus_other") |
| + case "wrong mode": |
| + response = strings.ReplaceAll(response, `"mode":"setup"`, `"mode":"payment"`) |
| + case "untrusted url": |
| + response = strings.ReplaceAll(response, "checkout.stripe.com", "attacker.example") |
| + case "missing mode": |
| + response = strings.ReplaceAll(response, `"mode":"setup",`, "") |
| + case "missing livemode": |
| + response = strings.ReplaceAll(response, `"livemode":false,`, "") |
| + } |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cap.add(r); fmt.Fprint(w, response) })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + req := billing.SetupCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", SuccessURL: "https://console.example.com/billing", CancelURL: "https://console.example.com/billing", Key: "setup-key"} |
| + prep, err := p.PrepareSetupCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cap.count() != 0 { |
| + t.Fatal("prepare sent request") |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + for key, want := range map[string]string{"mode": "setup", "customer": "cus_1", "payment_method_types[0]": "card", "success_url": req.SuccessURL, "cancel_url": req.CancelURL, "metadata[account]": "bab"} { |
| + if form.Get(key) != want { |
| + t.Errorf("%s=%q", key, form.Get(key)) |
| + } |
| + } |
| + if form.Has("line_items[0][quantity]") || form.Has("payment_intent_data[capture_method]") { |
| + t.Fatal("setup must not charge") |
| + } |
| + result, err := p.Send(context.Background(), prep) |
| + if which != "ok" { |
| + if !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("untrusted response: %+v %v", result, err) |
| + } |
| + return |
| + } |
| + if err != nil || result.Checkout == nil || result.Checkout.Customer != req.Customer { |
| + t.Fatalf("setup result: %+v %v", result, err) |
| + } |
| + if cap.last().path != "/v1/checkout/sessions" || cap.last().key != req.Key || string(cap.last().body) != string(prep.Body) { |
| + t.Fatal("send changed setup") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/billingstripe/payment.go b/internal/billingstripe/payment.go| index 990381dac..cd3e34ce2 100644 |
| --- a/internal/billingstripe/payment.go |
| +++ b/internal/billingstripe/payment.go |
| @@ -21,26 +21,28 @@ func (p *Provider) PreparePaymentCheckout(req billing.PaymentCheckoutRequest) (b |
| return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| } |
| form := url.Values{ |
| - "mode": {"payment"}, |
| - "payment_intent_data[capture_method]": {"manual"}, |
| - "line_items[0][price_data][currency]": {req.Currency}, |
| - "line_items[0][price_data][unit_amount]": {strconv.FormatInt(req.Amount, 10)}, |
| - "line_items[0][price_data][product_data][name]": {req.Description}, |
| - "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| - "line_items[0][quantity]": {"1"}, |
| - "automatic_tax[enabled]": {"true"}, |
| - "adaptive_pricing[enabled]": {"false"}, |
| - "billing_address_collection": {"required"}, |
| - "customer_update[address]": {"auto"}, |
| - "customer_update[name]": {"auto"}, |
| - "tax_id_collection[enabled]": {"true"}, |
| - "customer": {req.Customer}, |
| - "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, |
| - "metadata[account]": {req.AccountSqid}, |
| - "metadata[purchase]": {req.Reference}, |
| - "success_url": {req.SuccessURL}, |
| - "cancel_url": {req.CancelURL}, |
| - "expand[]": {"payment_intent"}, |
| + "mode": {"payment"}, |
| + "payment_intent_data[setup_future_usage]": {"off_session"}, |
| + "saved_payment_method_options[payment_method_save]": {"enabled"}, |
| + "payment_intent_data[capture_method]": {"manual"}, |
| + "line_items[0][price_data][currency]": {req.Currency}, |
| + "line_items[0][price_data][unit_amount]": {strconv.FormatInt(req.Amount, 10)}, |
| + "line_items[0][price_data][product_data][name]": {req.Description}, |
| + "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| + "line_items[0][quantity]": {"1"}, |
| + "automatic_tax[enabled]": {"true"}, |
| + "adaptive_pricing[enabled]": {"false"}, |
| + "billing_address_collection": {"required"}, |
| + "customer_update[address]": {"auto"}, |
| + "customer_update[name]": {"auto"}, |
| + "tax_id_collection[enabled]": {"true"}, |
| + "customer": {req.Customer}, |
| + "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, |
| + "metadata[account]": {req.AccountSqid}, |
| + "metadata[purchase]": {req.Reference}, |
| + "success_url": {req.SuccessURL}, |
| + "cancel_url": {req.CancelURL}, |
| + "expand[]": {"payment_intent"}, |
| } |
| return prepared(billing.PreparedPaymentCheckout, "/v1/checkout/sessions", form, req.Key) |
| } |
| @@ -186,3 +188,14 @@ func paymentResult(prep billing.Prepared, raw json.RawMessage) (billing.PaymentI |
| } |
| return billing.PaymentInfo{PaymentIntent: pi.ID, IntentStatus: pi.Status, AmountTotal: *pi.Amount, Currency: pi.Currency}, nil |
| } |
| + |
| +func (p *Provider) PrepareSetupCheckout(req billing.SetupCheckoutRequest) (billing.Prepared, error) { |
| + if !validID(req.Customer) || req.AccountSqid == "" || req.SuccessURL == "" || req.CancelURL == "" { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + return prepared(billing.PreparedSetupCheckout, "/v1/checkout/sessions", url.Values{ |
| + "mode": {"setup"}, "customer": {req.Customer}, "payment_method_types[0]": {"card"}, |
| + "metadata[account]": {req.AccountSqid}, "setup_intent_data[metadata][account]": {req.AccountSqid}, |
| + "success_url": {req.SuccessURL}, "cancel_url": {req.CancelURL}, |
| + }, req.Key) |
| +} |
diff --git a/internal/billingstripe/payment_test.go b/internal/billingstripe/payment_test.go| index 7ad5629d4..8e00314f1 100644 |
| --- a/internal/billingstripe/payment_test.go |
| +++ b/internal/billingstripe/payment_test.go |
| @@ -51,7 +51,9 @@ func TestPaymentCheckoutForm(t *testing.T) { |
| } |
| want := url.Values{ |
| "mode": {"payment"}, "payment_intent_data[capture_method]": {"manual"}, |
| - "line_items[0][price_data][currency]": {"eur"}, "line_items[0][price_data][unit_amount]": {"1500"}, |
| + "payment_intent_data[setup_future_usage]": {"off_session"}, |
| + "saved_payment_method_options[payment_method_save]": {"enabled"}, |
| + "line_items[0][price_data][currency]": {"eur"}, "line_items[0][price_data][unit_amount]": {"1500"}, |
| "line_items[0][price_data][product_data][name]": {"example.com"}, "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| "line_items[0][quantity]": {"1"}, "automatic_tax[enabled]": {"true"}, "customer": {"cus_1"}, |
| "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, "metadata[account]": {"bab"}, "metadata[purchase]": {"purchase_1"}, |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index c48942e5d..cf560c4d5 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -29,13 +29,30 @@ func prepared(kind, path string, form url.Values, key string) (billing.Prepared, |
| } |
| // 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) { |
| +// plus optional owner email and tax location. Checkout collects the full address. |
| +func (p *Provider) PrepareCustomer(accountSqid, key string, details ...billing.CustomerDetails) (billing.Prepared, error) { |
| form, err := customerMetadataForm(accountSqid) |
| if err != nil { |
| return billing.Prepared{}, err |
| } |
| + if len(details) > 1 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + if len(details) == 1 { |
| + d := details[0] |
| + if !noControlChars(d.Email) || !validPostalCode(d.PostalCode) || (d.Country != "" && !validCountry(d.Country)) || (d.Country == "" && d.PostalCode != "") { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + if d.Email != "" { |
| + form.Set("email", d.Email) |
| + } |
| + if d.Country != "" { |
| + form.Set("address[country]", d.Country) |
| + } |
| + if d.PostalCode != "" { |
| + form.Set("address[postal_code]", d.PostalCode) |
| + } |
| + } |
| return prepared(billing.PreparedCustomer, "/v1/customers", form, key) |
| } |
| @@ -171,7 +188,7 @@ var preparedPathRe = regexp.MustCompile(`^/v1(/[A-Za-z0-9_]+)+$`) |
| // 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, |
| + case billing.PreparedSetupCheckout, billing.PreparedCustomer, billing.PreparedCheckout, billing.PreparedExpire, billing.PreparedChange, billing.PreparedRenewal, |
| billing.PreparedPaymentCheckout, billing.PreparedCapture, billing.PreparedCancelPayment: |
| default: |
| return billing.Result{}, fmt.Errorf("%w: unknown prepared kind %q, not sent", billing.ErrRefused, prep.Kind) |
| @@ -197,6 +214,19 @@ func (p *Provider) Send(ctx context.Context, prep billing.Prepared) (billing.Res |
| // 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.PreparedSetupCheckout: |
| + var sess struct { |
| + ID, URL, Mode, Status, Customer string |
| + LiveMode *bool `json:"livemode"` |
| + } |
| + if err := json.Unmarshal(raw, &sess); err != nil { |
| + return errors.New("billingstripe: setup answer does not decode") |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + if !validID(sess.ID) || sess.Mode != "setup" || sess.LiveMode == nil || sess.Customer != form.Get("customer") || sess.Status != "open" || validateRedirectURL(sess.URL, "checkout.stripe.com") != nil { |
| + return errors.New("billingstripe: invalid setup session") |
| + } |
| + res.Checkout = &billing.CheckoutInfo{ID: sess.ID, URL: sess.URL, Customer: sess.Customer, State: billing.CheckoutOpen} |
| case billing.PreparedPaymentCheckout, billing.PreparedCapture, billing.PreparedCancelPayment: |
| info, err := paymentResult(prep, raw) |
| if err != nil { |
diff --git a/internal/console/billingcard.go b/internal/console/billingcard.go| new file mode 100644 |
| index 000000000..ea2208031 |
| --- /dev/null |
| +++ b/internal/console/billingcard.go |
| @@ -0,0 +1,68 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "log" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func (s *Server) handleBillingCard(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, ok := s.billingOwner(w, r) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + s.billingCSRFRefused(w, r) |
| + return |
| + } |
| + back := billingPagePath(acct.Sqid) |
| + if !s.billing.ready.Load() { |
| + s.setFlash(w, "err", billingCopy["card.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + if !s.requireFreshAuth(w, r, addr, raw) { |
| + return |
| + } |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(s.billingClock(r.Context()), 30*time.Second) |
| + defer cancel() |
| + to, err := s.cardSetupLocked(h, ctx, acct) |
| + release() |
| + if err != nil { |
| + log.Printf("console: billing card %s: %v", acct.Sqid, err) |
| + s.setFlash(w, "err", billingCopy["card.failed"]) |
| + to = back |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| + |
| +func (s *Server) cardSetupLocked(h billingHold, ctx context.Context, acct *Account) (string, error) { |
| + b, err := s.paymentCustomerLocked(h, ctx, acct, "", "", false) |
| + if err != nil { |
| + return "", err |
| + } |
| + back := s.cfg.Origin + billingPagePath(acct.Sqid) |
| + // Like a portal open, each attempt gets a fresh session. It cannot charge |
| + // money or change a subscription, and an unknown response is never replayed. |
| + req, err := s.billing.cfg.Provider.PrepareSetupCheckout(billing.SetupCheckoutRequest{AccountSqid: acct.Sqid, Customer: b.Customer, SuccessURL: back, CancelURL: back, Key: "card:" + b.Customer + ":" + newPortalNonce()}) |
| + if err != nil { |
| + return "", err |
| + } |
| + result, err := s.sendPreparedLocked(h, ctx, req) |
| + if err != nil { |
| + return "", err |
| + } |
| + if result.Checkout == nil || result.Checkout.ID == "" || result.Checkout.URL == "" || result.Checkout.Customer != b.Customer { |
| + return "", billing.ErrIndeterminate |
| + } |
| + return result.Checkout.URL, nil |
| +} |
diff --git a/internal/console/billingcard_test.go b/internal/console/billingcard_test.go| new file mode 100644 |
| index 000000000..579afdfa3 |
| --- /dev/null |
| +++ b/internal/console/billingcard_test.go |
| @@ -0,0 +1,82 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func TestBillingAddCardWithoutCustomer(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + if _, err := o.st.SetAccountPlan(o.acct.ID, "free", nil, 0, PlanSourceSponsored, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + page := o.request(t, http.MethodGet, o.billingBase(), nil) |
| + if page.Status != 200 || !strings.Contains(page.Body, "Add a card") || strings.Contains(page.Body, "/billing/portal") { |
| + t.Fatal("missing add card action or unexpected portal") |
| + } |
| + o.stepUp(t) |
| + for i := 0; i < 2; i++ { |
| + r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil) |
| + if r.Status != 303 || !strings.HasPrefix(r.Loc, "https://checkout.example.test/") { |
| + t.Fatalf("setup: %+v", r) |
| + } |
| + } |
| + b, err := o.st.BillingAccount(o.acct.ID) |
| + if err != nil || b == nil || b.Customer == "" || b.Subscription != "" { |
| + t.Fatalf("billing: %+v %v", b, err) |
| + } |
| + customers, setups := 0, 0 |
| + for _, p := range o.fake.Sent { |
| + if p.Kind == billing.PreparedCustomer { |
| + customers++ |
| + } |
| + if p.Kind == "setup_checkout" { |
| + setups++ |
| + var req struct{ Customer, SuccessURL, CancelURL string } |
| + if err := json.Unmarshal(p.Body, &req); err != nil { |
| + t.Fatal(err) |
| + } |
| + if req.Customer != b.Customer || req.SuccessURL != o.srv.cfg.Origin+o.billingBase() || req.CancelURL != req.SuccessURL { |
| + t.Fatalf("setup request: %+v", req) |
| + } |
| + } |
| + } |
| + if customers != 1 || setups != 2 { |
| + t.Fatalf("customers=%d setups=%d", customers, setups) |
| + } |
| + page = o.request(t, http.MethodGet, o.billingBase(), nil) |
| + if strings.Contains(page.Body, "/billing/card") || !strings.Contains(page.Body, "/billing/portal") { |
| + t.Fatal("bound customer needs portal only") |
| + } |
| +} |
| + |
| +func TestBillingAddCardGates(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + if err := o.st.AddMember(o.acct.ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + kim := newBrowser(t) |
| + o.setUser("kim@keymail.dev") |
| + signUp(t, o.consoleFixture, kim, "card-member") |
| + if status, _, _ := postForm(t, kim, o.ts.URL+o.billingBase()+"/card", url.Values{"csrf": {sessionToken(t, o.consoleFixture, kim)}}); status != 404 { |
| + t.Fatalf("member status=%d", status) |
| + } |
| + if status := httpPostNoCSRF(t, o, o.billingBase()+"/card", url.Values{}); status != 403 { |
| + t.Fatalf("csrf status=%d", status) |
| + } |
| + if r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil); r.Status != 303 || !strings.Contains(r.Loc, "/oauth/authorize") { |
| + t.Fatalf("stepup: %+v", r) |
| + } |
| + if b, err := o.st.BillingAccount(o.acct.ID); err != nil || b != nil { |
| + t.Fatalf("gate wrote billing: %+v %v", b, err) |
| + } |
| + if len(o.fake.Sent) != 0 { |
| + t.Fatal("gate sent provider writes") |
| + } |
| +} |
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index 151070584..d4c213962 100644 |
| --- a/internal/console/billingcheckout.go |
| +++ b/internal/console/billingcheckout.go |
| @@ -434,7 +434,7 @@ func customerKey(sqid string, attempt int) string { |
| // a new attempt with a new key. A new attempt is prepared and stored, with |
| // its provider-time stamp, before its first send; with no provider time |
| // nothing is stored or sent. Only a definite answer is bound. |
| -func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (string, error) { |
| +func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time, details ...billing.CustomerDetails) (string, error) { |
| b, err := s.store.BillingAccount(acct.ID) |
| if err != nil { |
| return "", err |
| @@ -453,7 +453,7 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| return "", errCheckoutFailed |
| } |
| started++ |
| - if err := s.startCustomerLocked(h, ctx, acct, b); err != nil { |
| + if err := s.startCustomerLocked(h, ctx, acct, b, details...); err != nil { |
| return "", err |
| } |
| } |
| @@ -474,7 +474,7 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| // startCustomerLocked prepares the next customer attempt and stores it on |
| // the billing row with its provider-time stamp, before anything is sent. |
| -func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount) error { |
| +func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, details ...billing.CustomerDetails) error { |
| _ = h |
| if err := s.requireBillingReady(); err != nil { |
| return err |
| @@ -484,7 +484,7 @@ func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *A |
| return errNoProviderTimeRefusal |
| } |
| attempt := b.CustomerAttempt + 1 |
| - p, err := s.billing.cfg.Provider.PrepareCustomer(acct.Sqid, customerKey(acct.Sqid, attempt)) |
| + p, err := s.billing.cfg.Provider.PrepareCustomer(acct.Sqid, customerKey(acct.Sqid, attempt), details...) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/console/billingcustomer.go b/internal/console/billingcustomer.go| new file mode 100644 |
| index 000000000..a1528bbe3 |
| --- /dev/null |
| +++ b/internal/console/billingcustomer.go |
| @@ -0,0 +1,65 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// Payment customers use the subscription customer's lock, journal and keys. |
| +// Adding a card alone leaves currency unset; the first purchase fixes it. |
| +func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct *Account, country, postal string, fixCurrency bool) (*billingAccount, error) { |
| + now := time.Now() |
| + if err := s.requireBillingReady(); err != nil { |
| + return nil, err |
| + } |
| + if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| + return nil, err |
| + } else if retiring { |
| + return nil, errBillingRetiring |
| + } |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if b == nil { |
| + b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}} |
| + } |
| + if fixCurrency && b.Currency == "" { |
| + currency, err := s.billing.cfg.Book.ChooseCurrency("", country) |
| + if err != nil { |
| + return nil, err |
| + } |
| + prior, err := s.store.CheckoutIntent(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if prior != nil && !intentTerminal(prior) && prior.Currency != currency { |
| + return nil, errCheckoutUncertain |
| + } |
| + b.Currency = currency |
| + if err := s.store.PutBillingState(*b); err != nil { |
| + return nil, err |
| + } |
| + } |
| + details := billing.CustomerDetails{Country: country, PostalCode: postal} |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, member := range members { |
| + if member.Role == RoleOwner { |
| + details.Email = member.Name |
| + break |
| + } |
| + } |
| + if details.Email == "" { |
| + return nil, errors.New("billing: account has no owner") |
| + } |
| + if _, err := s.ensureCustomerLocked(h, ctx, acct, now, details); err != nil { |
| + return nil, err |
| + } |
| + return s.store.BillingAccount(acct.ID) |
| +} |
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go| index 75967b567..ec7781840 100644 |
| --- a/internal/console/billingpage.go |
| +++ b/internal/console/billingpage.go |
| @@ -35,6 +35,7 @@ const ( |
| offerStop = "stop" |
| offerResume = "resume" |
| offerPortal = "portal" |
| + offerCard = "card" |
| offerConfirm = "confirm" |
| offerContinue = "continue" |
| offerStartOver = "start_over" |
| @@ -108,7 +109,10 @@ func decideBillingOwner(in billingPageInput) (string, []string) { |
| case len(in.Problems) > 0: |
| return "notice.problem", ifBound() |
| case in.Row != nil && (in.Row.Source == PlanSourceOperator || in.Row.Source == PlanSourceSponsored): |
| - return "notice.operator_plan", nil |
| + if bound { |
| + return "notice.operator_plan", []string{offerPortal} |
| + } |
| + return "notice.operator_plan", []string{offerCard} |
| // A sending row under no hold is one a crash left behind: Confirm now |
| // adopts it as unresolved and finishes it. |
| case op != nil && (op.State == opUnresolved || op.State == opSending): |
| @@ -120,7 +124,10 @@ func decideBillingOwner(in billingPageInput) (string, []string) { |
| case intent != nil && intent.State == intentCreating && !live: |
| return "notice.settling", []string{offerConfirm} |
| case !live: |
| - return "", []string{offerBuy} |
| + if bound { |
| + return "", []string{offerBuy, offerPortal} |
| + } |
| + return "", []string{offerBuy, offerCard} |
| case b.State == billing.StatePending: |
| return "notice.settling", nil |
| case b.Collecting: |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index bc0831c5a..0055737fe 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -9,6 +9,10 @@ package console |
| // here. The change.* keys below are the plan's drafts for Task 10, declared |
| // here because Confirm now and the refusals of this task use them. |
| var billingCopy = map[string]string{ |
| + // Drafts for the Luna pass: domain registration Plan 2, slice 1. |
| + "button.card": "Add a card", |
| + "card.failed": "We could not open the card setup page. Try again later.", |
| + |
| "change.done": "Your billing change is saved.", |
| "change.pending": "Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish.", |
| "change.declined": "Your card was declined, so nothing changed.", |
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go| index cd4008699..6bcad8dc9 100644 |
| --- a/internal/console/billingpage_test.go |
| +++ b/internal/console/billingpage_test.go |
| @@ -52,8 +52,8 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.problem", []string{"portal"}}, |
| {"another problem, unbound", billingPageInput{Ready: true, Problems: []string{problemUnknownCustomer}}, "notice.problem", nil}, |
| {"operator row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "business", Source: PlanSourceOperator}, Billing: free, |
| - Op: op(opUnresolved)}, "notice.operator_plan", nil}, |
| - {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored}}, "notice.operator_plan", nil}, |
| + Op: op(opUnresolved)}, "notice.operator_plan", []string{"portal"}}, |
| + {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored}}, "notice.operator_plan", []string{"card"}}, |
| {"op unresolved", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opUnresolved)}, |
| "notice.confirming", []string{"confirm", "portal"}}, |
| {"op sending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opSending)}, |
| @@ -68,8 +68,8 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.checkout_open", []string{"continue", "start_over"}}, |
| {"intent creating", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCreating)}, |
| "notice.settling", []string{"confirm"}}, |
| - {"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy"}}, |
| - {"no billing row", billingPageInput{Ready: true}, "", []string{"buy"}}, |
| + {"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy", "portal"}}, |
| + {"no billing row", billingPageInput{Ready: true}, "", []string{"buy", "card"}}, |
| {"intent open but live", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Intent: intent(intentOpen)}, |
| "", []string{"change", "stop", "portal"}}, |
| {"pending state", billingPageInput{Ready: true, Billing: paid(func(b *billingAccount) { b.State = billing.StatePending })}, |
| @@ -82,9 +82,9 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.seat_drift", []string{"match_seats", "change", "stop", "portal"}}, |
| {"paid", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil)}, "", []string{"change", "stop", "portal"}}, |
| // Terminal intents are ignored, whatever their state. |
| - {"intent completed", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCompleted)}, "", []string{"buy"}}, |
| - {"intent expired", billingPageInput{Ready: true, Billing: free, Intent: intent(intentExpired)}, "", []string{"buy"}}, |
| - {"intent abandoned", billingPageInput{Ready: true, Billing: free, Intent: intent(intentAbandoned)}, "", []string{"buy"}}, |
| + {"intent completed", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCompleted)}, "", []string{"buy", "portal"}}, |
| + {"intent expired", billingPageInput{Ready: true, Billing: free, Intent: intent(intentExpired)}, "", []string{"buy", "portal"}}, |
| + {"intent abandoned", billingPageInput{Ready: true, Billing: free, Intent: intent(intentAbandoned)}, "", []string{"buy", "portal"}}, |
| // A settled operation is not outstanding. |
| {"op applied", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opApplied)}, "", []string{"change", "stop", "portal"}}, |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 169eab9a9..a666128a5 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1399,6 +1399,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| // Plans 6b: the locked portal opens a provider portal session for the |
| // account's customer and writes nothing locally. |
| + "route POST /a/{sqid}/billing/card": claimNonApp("creates or reuses the account billing customer and opens a card setup session; writes only account billing state and names no app"), |
| "route POST /a/{sqid}/billing/portal": claimNonApp("opens a provider portal session for the account's customer and redirects the owner to it, writing nothing locally; names no app"), |
| // Plans 6b: an owner's Confirm now finishes an outstanding billing |
| // operation under the account's billing hold and refreshes the |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 723a3d270..b72d8e4d5 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -914,6 +914,22 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| + "route POST /a/{sqid}/billing/card": { |
| + setup: claimCheckoutWorld, |
| + do: claimFormReply("/a/bab/billing/card"), |
| + status: http.StatusSeeOther, loc: "https://checkout.example.test/c/", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake) |
| + fake.Lock() |
| + defer fake.Unlock() |
| + for _, p := range fake.Sent { |
| + if p.Kind == billing.PreparedSetupCheckout { |
| + return "" |
| + } |
| + } |
| + return "no card setup session was created" |
| + }, |
| + }, |
| "route POST /a/{sqid}/billing/portal": { |
| setup: claimBillingWorld, |
| do: claimFormReply("/a/bab/billing/portal"), |
diff --git a/internal/console/server.go b/internal/console/server.go| index f20927d19..6057e8c16 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1961,6 +1961,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // Plans 6b: an owner's way to the provider's locked portal for cards |
| // and invoices (billingportal.go). 404 with billing off. |
| s.registerRoute("POST /a/{sqid}/billing/portal", s.handleBillingPortal) |
| + s.registerRoute("POST /a/{sqid}/billing/card", s.handleBillingCard) |
| // The billing page (billingpage.go): member-readable, its forms the |
| // owner's. 404 with billing off. |
| s.registerRoute("GET /a/{sqid}/billing", s.handleBilling) |
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html| index 52cadfa5d..ab91aaba9 100644 |
| --- a/internal/console/templates/billing.html |
| +++ b/internal/console/templates/billing.html |
| @@ -144,6 +144,10 @@ |
| <input type="hidden" name="renewal" value="stop"> |
| <button class="linkish danger" type="submit">{{billingText "button.stop"}}</button> |
| </form></div>{{end}} |
| +{{if eq . "card"}}<div class="settings-row"><form method="post" action="{{$.Base}}/billing/card"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <button type="submit">{{billingText "button.card"}}</button> |
| +</form></div>{{end}} |
| {{if eq . "portal"}}<div class="settings-row"><form method="post" action="{{$.Base}}/billing/portal"> |
| <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| <button type="submit">{{billingText "button.portal"}}</button> |