billingstripe: one request per send for every kind; one class for a reused key; 409 lock conflicts not executed (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+192
−466
internal/billing/billing.go+11 −3internal/billing/billingtest/fake.go+3 −2internal/billing/billingtest/fake_test.go+2 −2internal/billingstripe/adapter.go+7 −1internal/billingstripe/adapter_test.go+12 −63internal/billingstripe/catalog.go+8 −0internal/billingstripe/client.go+54 −60internal/billingstripe/client_test.go+0 −314internal/billingstripe/prepared.go+13 −5internal/billingstripe/prepared_test.go+82 −16
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index bd6ec902f..a1e628ed2 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -181,7 +181,11 @@ type Prepared struct { |
| // Result is what a definite answer to a Send says. Which fields are set |
| // depends on the Prepared's kind. |
| type Result struct { |
| - Subscription *Subscription // a change or renewal |
| + // Subscription is the answer to a change or renewal. Its Collecting is |
| + // authoritative only from a Subscription read: a write's answer does |
| + // not carry the latest invoice, so there it reflects only the status |
| + // and a pending update. |
| + Subscription *Subscription |
| Checkout *CheckoutInfo // a Checkout create or expiry |
| Customer string // a customer create |
| Replayed bool // the provider replayed a stored answer (fact 7) |
| @@ -257,9 +261,13 @@ type Provider interface { |
| PrepareChange(req ChangeRequest) (Prepared, error) |
| PrepareRenewal(subscription string, renew bool, key string) (Prepared, error) |
| // Send makes exactly one request: p's bytes under p's key. A nil error |
| - // is definite success; otherwise the error is one of the outcome |
| + // is definite success. Otherwise the error is one of the outcome |
| // classes (ErrPaymentFailed, ErrRefused, ErrNotExecuted, ErrInFlight, |
| - // ErrNoResponse, ErrIndeterminate). |
| + // ErrNoResponse, ErrIndeterminate), or ErrIdempotencyMismatch, which is |
| + // none of them. A test double may also return errors outside all of |
| + // these (the billingtest Fake's ErrCrash): a caller treats any such |
| + // error as "stop and record nothing more", leaving the operation |
| + // unresolved. |
| Send(ctx context.Context, p Prepared) (Result, error) |
| // LiveSubscriptions names every live subscription of a customer, |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 06ed176c8..d8de4964c 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -7,7 +7,8 @@ |
| // - Per-key idempotency. Send stores the answer of every request that |
| // began executing under its key; the same bytes again replay it |
| // (Result.Replayed), a 5xx included; other bytes under the key are an |
| -// idempotency error (ErrRefused and ErrKeyReused). Keys can be pruned |
| +// idempotency error (billing.ErrIdempotencyMismatch and ErrKeyReused, |
| +// as the adapter reports it: not a refusal). Keys can be pruned |
| // after 24 h (PruneKeysOlderThan), after which the same bytes execute |
| // anew. |
| // - Pending updates: a ProrateNow change whose payment fails softly waits |
| @@ -983,7 +984,7 @@ func (f *Fake) send(ctx context.Context, p billing.Prepared) (billing.Result, er |
| d := f.respond(ctx) |
| switch { |
| case !e.same(p): |
| - return billing.Result{ProviderTime: d}, fmt.Errorf("%w: %w", billing.ErrRefused, ErrKeyReused) |
| + return billing.Result{ProviderTime: d}, fmt.Errorf("%w: %w", billing.ErrIdempotencyMismatch, ErrKeyReused) |
| case e.executing: |
| return billing.Result{ProviderTime: d}, fmt.Errorf("%w: 409 on key %s", billing.ErrInFlight, p.Key) |
| } |
diff --git a/internal/billing/billingtest/fake_test.go b/internal/billing/billingtest/fake_test.go| index 7e3c2170f..c4f309229 100644 |
| --- a/internal/billing/billingtest/fake_test.go |
| +++ b/internal/billing/billingtest/fake_test.go |
| @@ -105,8 +105,8 @@ func TestFakePreparedIdempotency(t *testing.T) { |
| // The same key with other bytes is an idempotency error, nothing applied. |
| other := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:1") |
| - if _, err := f.Send(ctx, other); !errors.Is(err, billing.ErrRefused) || !errors.Is(err, ErrKeyReused) { |
| - t.Fatalf("other body under the key: err = %v", err) |
| + if _, err := f.Send(ctx, other); !errors.Is(err, billing.ErrIdempotencyMismatch) || !errors.Is(err, ErrKeyReused) || errors.Is(err, billing.ErrRefused) { |
| + t.Fatalf("other body under the key: err = %v, want ErrIdempotencyMismatch and not ErrRefused", err) |
| } |
| if got := appsQty(t, f, "sub_1"); got != 5 { |
| t.Fatalf("a mismatch applied: apps = %d", got) |
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go| index 5b2d661fb..437249fac 100644 |
| --- a/internal/billingstripe/adapter.go |
| +++ b/internal/billingstripe/adapter.go |
| @@ -349,7 +349,9 @@ func (p *Provider) checkPortal(ctx context.Context) error { |
| } |
| // checkHouseCoupon is the configured house coupon: valid, in this mode, |
| -// 100% off with no amount off, forever, and not limited to some products. |
| +// 100% off with no amount off, forever, and unrestricted: not limited to |
| +// some products, and with no redemption limit or deadline that would later |
| +// invalidate it and fail every house Checkout at the provider. |
| func (p *Provider) checkHouseCoupon(ctx context.Context) error { |
| cp, err := p.client.GetCoupon(ctx, p.houseCoupon) |
| if err != nil { |
| @@ -369,6 +371,10 @@ func (p *Provider) checkHouseCoupon(ctx context.Context) error { |
| why = "not forever" |
| case len(cp.AppliesToProducts) > 0: |
| why = "limited to some products" |
| + case cp.MaxRedemptions != nil: |
| + why = "has a redemption limit" |
| + case cp.RedeemBy != nil: |
| + why = "has a redemption deadline" |
| } |
| if why != "" { |
| return fmt.Errorf("billing check: the house coupon: %s", why) |
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go| index c371e82ef..44f2cec66 100644 |
| --- a/internal/billingstripe/adapter_test.go |
| +++ b/internal/billingstripe/adapter_test.go |
| @@ -413,59 +413,6 @@ func TestCheckRefusesMismatchedPrices(t *testing.T) { |
| } |
| } |
| -func TestCreateCheckoutSendsItems(t *testing.T) { |
| - var form map[string][]string |
| - var idem string |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - _ = r.ParseForm() |
| - form = r.PostForm |
| - idem = r.Header.Get("Idempotency-Key") |
| - fmt.Fprint(w, `{"id":"cs_1","url":"https://checkout.stripe.com/c/pay/cs_1","status":"open","livemode":false,"currency":"usd"}`) |
| - })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - _, err := c.CreateCheckout(context.Background(), CreateCheckoutParams{ |
| - Items: []LineItem{{PriceID: "price_p", Quantity: 1}, {PriceID: "price_a", Quantity: 2}}, |
| - SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", CustomerID: "cus_1", Currency: "usd", |
| - Metadata: CheckoutMetadata{AccountSqid: "bab", IntentID: "intent_1", PriceBook: "example-v1", Currency: "usd"}, |
| - }, "idem-1") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for k, v := range map[string]string{ |
| - "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", "currency": "usd", |
| - "metadata[account_sqid]": "bab", "metadata[price_book]": "example-v1", "metadata[currency]": "usd", "metadata[checkout_intent]": "intent_1", |
| - "subscription_data[metadata][account_sqid]": "bab", "subscription_data[metadata][price_book]": "example-v1", |
| - } { |
| - if got := form[k]; len(got) != 1 || got[0] != v { |
| - t.Errorf("form[%q] = %v, want %q", k, got, v) |
| - } |
| - } |
| - for _, k := range []string{"metadata[terms_version]", "metadata[plan]", "metadata[band]", "line_items[2][price]"} { |
| - if _, ok := form[k]; ok { |
| - t.Errorf("form carries %q", k) |
| - } |
| - } |
| - if idem != "idem-1" { |
| - t.Errorf("Idempotency-Key = %q", idem) |
| - } |
| - for name, items := range map[string][]LineItem{ |
| - "no items": nil, |
| - "zero": {{PriceID: "price_p", Quantity: 0}}, |
| - "bad price id": {{PriceID: "price p", Quantity: 1}}, |
| - } { |
| - _, err := c.CreateCheckout(context.Background(), CreateCheckoutParams{ |
| - Items: items, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", CustomerID: "cus_1", Currency: "usd", |
| - Metadata: CheckoutMetadata{AccountSqid: "bab", IntentID: "intent_1", PriceBook: "example-v1", Currency: "usd"}, |
| - }, "idem-2") |
| - if err == nil { |
| - t.Errorf("%s: accepted", name) |
| - } |
| - } |
| -} |
| - |
| // lockedPortal is a portal configuration the readiness check accepts: |
| // active, test mode, payment methods and invoices only, address edits. |
| func lockedPortal() map[string]any { |
| @@ -484,7 +431,7 @@ func lockedPortal() map[string]any { |
| // 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"} |
| + "percent_off": 100, "amount_off": nil, "duration": "forever", "max_redemptions": nil, "redeem_by": nil} |
| } |
| func portalFeature(f *fakeStripe, name string) map[string]any { |
| @@ -541,15 +488,17 @@ func TestCheckRefusesUnlockedPortal(t *testing.T) { |
| 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, |
| + "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"}} }, |
| + "max redemptions": func(c map[string]any) { c["max_redemptions"] = 100 }, |
| + "redeem by": func(c map[string]any) { c["redeem_by"] = 1893456000 }, |
| + "missing": nil, |
| } |
| houseProvider := func(t *testing.T, base string) *Provider { |
| return prepProvider(t, base, func(c *ProviderConfig) { c.HouseCoupon = "house_forever" }) |
diff --git a/internal/billingstripe/catalog.go b/internal/billingstripe/catalog.go| index 18d957933..4531da63e 100644 |
| --- a/internal/billingstripe/catalog.go |
| +++ b/internal/billingstripe/catalog.go |
| @@ -235,6 +235,10 @@ type Coupon struct { |
| AmountOff *int64 |
| Duration string |
| AppliesToProducts []string |
| + // MaxRedemptions and RedeemBy are limits after which the coupon stops |
| + // being valid; nil when it has none. |
| + MaxRedemptions *int64 |
| + RedeemBy *int64 |
| } |
| func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| @@ -245,6 +249,8 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| PercentOff *float64 `json:"percent_off"` |
| AmountOff *int64 `json:"amount_off"` |
| Duration string `json:"duration"` |
| + MaxRedeem *int64 `json:"max_redemptions"` |
| + RedeemBy *int64 `json:"redeem_by"` |
| AppliesTo *struct { |
| Products []string `json:"products"` |
| } `json:"applies_to"` |
| @@ -265,6 +271,8 @@ func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| cp.PercentOff = raw.PercentOff |
| cp.AmountOff = raw.AmountOff |
| cp.Duration = raw.Duration |
| + cp.MaxRedemptions = raw.MaxRedeem |
| + cp.RedeemBy = raw.RedeemBy |
| if raw.AppliesTo != nil { |
| cp.AppliesToProducts = raw.AppliesTo.Products |
| } |
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go| index 315df1e18..e60a8699d 100644 |
| --- a/internal/billingstripe/client.go |
| +++ b/internal/billingstripe/client.go |
| @@ -12,6 +12,7 @@ package billingstripe |
| import ( |
| "bytes" |
| "context" |
| + "crypto/tls" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -75,13 +76,6 @@ type Error struct { |
| // earlier request under the same idempotency key (its |
| // Idempotent-Replayed header), and ran nothing now. |
| Replayed bool |
| - // SessionID and Session are set only for CodeCurrencyMismatch: the |
| - // checkout session the provider did create, which is not the one that |
| - // was asked for. It exists and is open. The caller decides what to do |
| - // with it from the session itself (whose it is, above all), not from |
| - // the id alone. |
| - SessionID string |
| - Session *Session |
| } |
| // RefusedParam reports whether Stripe refused the request outright as |
| @@ -109,7 +103,10 @@ func (e *Error) Error() string { |
| type Client struct { |
| secretKey string |
| baseURL string |
| - httpClient *http.Client |
| + httpClient *http.Client // reads: pooled connections |
| + // writeClient sends every POST, each on a connection of its own (see |
| + // newWriteTransport). |
| + writeClient *http.Client |
| } |
| // String and GoString redact the secret key so an accidental %v/%+v of a |
| @@ -134,19 +131,16 @@ func NewClient(secretKey string, opts ...Option) (*Client, error) { |
| if !strings.HasPrefix(secretKey, "rk_") { |
| return nil, &Error{Code: CodeInvalidParams} |
| } |
| + // Never follow a redirect: Stripe's API does not issue them, and |
| + // following one would replay the Authorization header (and thus the |
| + // restricted key) against a host we did not choose. Treat any 3xx as a |
| + // hard failure instead of a hop. |
| + noRedirect := func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| c := &Client{ |
| - secretKey: secretKey, |
| - baseURL: defaultBaseURL, |
| - httpClient: &http.Client{ |
| - Timeout: requestTimeout, |
| - // Never follow a redirect: Stripe's API does not issue them, and |
| - // following one would replay the Authorization header (and thus |
| - // the restricted key) against a host we did not choose. Treat any |
| - // 3xx as a hard failure instead of a hop. |
| - CheckRedirect: func(*http.Request, []*http.Request) error { |
| - return http.ErrUseLastResponse |
| - }, |
| - }, |
| + secretKey: secretKey, |
| + baseURL: defaultBaseURL, |
| + httpClient: &http.Client{Timeout: requestTimeout, CheckRedirect: noRedirect}, |
| + writeClient: &http.Client{Timeout: requestTimeout, CheckRedirect: noRedirect, Transport: newWriteTransport()}, |
| } |
| for _, opt := range opts { |
| opt(c) |
| @@ -154,6 +148,27 @@ func NewClient(secretKey string, opts ...Option) (*Client, error) { |
| return c, nil |
| } |
| +// newWriteTransport is the transport every POST goes through: HTTP/1.1, |
| +// one connection per request, never reused. |
| +// |
| +// net/http resends a request by itself when a reused connection drops |
| +// after the request was written, if it counts the request as replayable. |
| +// A POST with an Idempotency-Key header does whenever its body can be |
| +// rewound, and always when its body is empty, as an expiry's is (NewRequest |
| +// makes it http.NoBody). No body type gives an empty POST both a |
| +// Content-Length of 0 and no replay. A fresh connection is never retried, |
| +// so with keep-alives off a POST is exactly one request on the wire, and |
| +// every resend is the caller's decision. HTTP/2 is off for the same |
| +// reason: its transport retries streams on its own rules. Writes are rare, |
| +// so a handshake each costs little; reads keep pooled connections. |
| +func newWriteTransport() *http.Transport { |
| + t := http.DefaultTransport.(*http.Transport).Clone() |
| + t.DisableKeepAlives = true |
| + t.ForceAttemptHTTP2 = false |
| + t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{} |
| + return t |
| +} |
| + |
| // validIDRe matches the charset real Stripe object ids use. Interpolating |
| // an id into a URL path without this check is a path-traversal vector |
| // ("../../v1/customers") and a request-smuggling one. |
| @@ -204,10 +219,13 @@ func (c *Client) call(ctx context.Context, method, path string, form url.Values, |
| 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. |
| +// exchange makes one request with body as given, byte for byte. A POST is |
| +// exactly one request on the wire (newWriteTransport). A GET is a read on a |
| +// pooled connection: net/http may resend it by itself when a kept-alive |
| +// connection drops, which is harmless, so a read counted as one request is |
| +// the caller's count, not a wire guarantee. 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 == "" { |
| @@ -219,8 +237,10 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| reqURL += "?" + query |
| } |
| var rd io.Reader |
| + hc := c.httpClient |
| if method == http.MethodPost { |
| - rd = bytes.NewReader(body) |
| + rd = bytes.NewReader(body) // an exact Content-Length, 0 included |
| + hc = c.writeClient |
| } |
| req, err := http.NewRequestWithContext(ctx, method, reqURL, rd) |
| @@ -233,15 +253,9 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| 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) |
| + resp, err := hc.Do(req) |
| if err != nil { |
| if ctx.Err() != nil || isTimeout(err) { |
| return meta, &Error{Code: CodeTimeout} |
| @@ -599,10 +613,11 @@ type LineItem struct { |
| Quantity int64 |
| } |
| -// CreateCheckoutParams. Deliberately absent: CustomerEmail (when neither |
| -// CustomerID nor an email is set, Checkout collects the buyer's identity |
| -// itself), payment_method_types (it overrides the Dashboard's dynamic |
| -// methods) and currency_options (a price here is in one currency). |
| +// CreateCheckoutParams is a Checkout Session create, which checkoutForm |
| +// encodes and PrepareCheckout completes. Deliberately absent: |
| +// CustomerEmail (the customer is always the console's), payment_method_types |
| +// (it overrides the Dashboard's dynamic methods) and currency_options (a |
| +// price here is in one currency). |
| // |
| // Prices are fixed in each currency they are sold in, so a session is |
| // created in exactly the currency the buyer chose, and Adaptive Pricing, |
| @@ -630,8 +645,9 @@ type CreateCheckoutParams struct { |
| Currency string |
| } |
| -// CodeCurrencyMismatch: Stripe answered with a session that is not in the |
| -// currency asked for, or that has Adaptive Pricing or a conversion on it. |
| +// CodeCurrencyMismatch: Stripe answered a Checkout create with a session |
| +// that is not in the currency asked for, or that has Adaptive Pricing or a |
| +// conversion on it. |
| const CodeCurrencyMismatch = "currency_mismatch" |
| // FixedCurrency reports whether a session is in exactly currency, with no |
| @@ -641,28 +657,6 @@ func (s *Session) FixedCurrency(currency string) bool { |
| return validCurrency(currency) && s.Currency == currency && !s.AdaptivePricing && !s.Converted |
| } |
| -// CreateCheckout starts a subscription-mode Checkout Session at exactly the |
| -// configured price and quantity. idempotencyKey is required and is never |
| -// 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) { |
diff --git a/internal/billingstripe/client_test.go b/internal/billingstripe/client_test.go| index f49c26caf..d9b575d32 100644 |
| --- a/internal/billingstripe/client_test.go |
| +++ b/internal/billingstripe/client_test.go |
| @@ -22,10 +22,6 @@ func testClient(t *testing.T, base string) *Client { |
| return c |
| } |
| -func validMetadata() CheckoutMetadata { |
| - return CheckoutMetadata{AccountSqid: "acct_1", IntentID: "intent_test", PriceBook: "example-v1", Currency: "eur"} |
| -} |
| - |
| func TestNewClient_RequiresRestrictedKey(t *testing.T) { |
| if _, err := NewClient("sk_live_full_access"); err == nil { |
| t.Fatal("expected error for a non-restricted secret key") |
| @@ -35,316 +31,6 @@ func TestNewClient_RequiresRestrictedKey(t *testing.T) { |
| } |
| } |
| -// --- CreateCheckout: exact form shape --- |
| - |
| -func TestCreateCheckout_FormAndHeaders(t *testing.T) { |
| - var gotMethod, gotPath string |
| - var gotHeader http.Header |
| - var gotForm map[string][]string |
| - |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - gotMethod = r.Method |
| - gotPath = r.URL.Path |
| - gotHeader = r.Header.Clone() |
| - if err := r.ParseForm(); err != nil { |
| - t.Fatalf("ParseForm: %v", err) |
| - } |
| - gotForm = map[string][]string(r.PostForm) |
| - w.WriteHeader(http.StatusOK) |
| - _ = json.NewEncoder(w).Encode(map[string]any{ |
| - "id": "cs_test_1", |
| - "url": "https://checkout.stripe.com/c/pay/cs_test_1", |
| - "status": "open", |
| - "livemode": false, |
| - "currency": "eur", |
| - }) |
| - })) |
| - defer srv.Close() |
| - |
| - c := testClient(t, srv.URL) |
| - p := CreateCheckoutParams{ |
| - Currency: "eur", |
| - Items: []LineItem{{PriceID: "price_123", Quantity: 3}}, |
| - SuccessURL: "https://example.com/success", |
| - CancelURL: "https://example.com/cancel", |
| - CustomerID: "cus_abc", |
| - ClientReferenceID: "ref_1", |
| - Metadata: validMetadata(), |
| - } |
| - sess, err := c.CreateCheckout(context.Background(), p, "idem-key-1") |
| - if err != nil { |
| - t.Fatalf("CreateCheckout: %v", err) |
| - } |
| - if sess.ID != "cs_test_1" || sess.Status != "open" { |
| - t.Fatalf("unexpected session: %+v", sess) |
| - } |
| - |
| - if gotMethod != http.MethodPost { |
| - t.Errorf("method = %q, want POST", gotMethod) |
| - } |
| - if len(gotForm["customer_update[address]"]) != 0 || len(gotForm["billing_address_collection"]) != 0 { |
| - t.Fatal("checkout may replace validated tax country") |
| - } |
| - if gotPath != "/v1/checkout/sessions" { |
| - t.Errorf("path = %q", gotPath) |
| - } |
| - if got := gotHeader.Get("Authorization"); got != "Bearer rk_test_123" { |
| - t.Errorf("Authorization = %q", got) |
| - } |
| - if got := gotHeader.Get("Stripe-Version"); got != apiVersion { |
| - t.Errorf("Stripe-Version = %q, want %q", got, apiVersion) |
| - } |
| - if got := gotHeader.Get("Idempotency-Key"); got != "idem-key-1" { |
| - t.Errorf("Idempotency-Key = %q", got) |
| - } |
| - if got := gotHeader.Get("Content-Type"); got != "application/x-www-form-urlencoded" { |
| - t.Errorf("Content-Type = %q", got) |
| - } |
| - |
| - want := map[string]string{ |
| - "mode": "subscription", |
| - "line_items[0][price]": "price_123", |
| - "line_items[0][quantity]": "3", |
| - "success_url": "https://example.com/success", |
| - "cancel_url": "https://example.com/cancel", |
| - "automatic_tax[enabled]": "true", |
| - "client_reference_id": "ref_1", |
| - "customer": "cus_abc", |
| - "allow_promotion_codes": "true", |
| - "currency": "eur", |
| - "adaptive_pricing[enabled]": "false", |
| - "metadata[account_sqid]": "acct_1", |
| - "metadata[price_book]": "example-v1", |
| - "metadata[currency]": "eur", |
| - "metadata[checkout_intent]": "intent_test", |
| - "subscription_data[metadata][account_sqid]": "acct_1", |
| - "subscription_data[metadata][price_book]": "example-v1", |
| - "subscription_data[metadata][currency]": "eur", |
| - } |
| - for k, v := range want { |
| - got := gotForm[k] |
| - if len(got) != 1 || got[0] != v { |
| - t.Errorf("form[%q] = %v, want [%q]", k, got, v) |
| - } |
| - } |
| - forbidden := []string{"payment_method_types", "currency_options", "discounts[0][coupon]", "customer_email", "metadata[terms_version]", "metadata[plan]", "metadata[band]"} |
| - for _, k := range forbidden { |
| - if _, ok := gotForm[k]; ok { |
| - t.Errorf("form unexpectedly contains %q", k) |
| - } |
| - } |
| -} |
| - |
| -func TestCreateCheckout_HouseCouponSuppressesPromotionCodes(t *testing.T) { |
| - var gotForm map[string][]string |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - _ = r.ParseForm() |
| - gotForm = map[string][]string(r.PostForm) |
| - _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": "eur"}) |
| - })) |
| - defer srv.Close() |
| - |
| - c := testClient(t, srv.URL) |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", |
| - Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, |
| - SuccessURL: "https://example.com/s", |
| - CancelURL: "https://example.com/c", |
| - Metadata: validMetadata(), |
| - HouseCoupon: "house-100", |
| - } |
| - if _, err := c.CreateCheckout(context.Background(), p, "idem-2"); err != nil { |
| - t.Fatalf("CreateCheckout: %v", err) |
| - } |
| - if got := gotForm["discounts[0][coupon]"]; len(got) != 1 || got[0] != "house-100" { |
| - t.Errorf("discounts[0][coupon] = %v", got) |
| - } |
| - if _, ok := gotForm["allow_promotion_codes"]; ok { |
| - t.Error("allow_promotion_codes must be absent when a house coupon is set") |
| - } |
| -} |
| - |
| -// Prices are fixed per currency. Every session is asked for in one |
| -// currency with Adaptive Pricing off, a purchase priced from a book says |
| -// which book and currency in the metadata of the session and of the |
| -// subscription, and a session that comes back in another currency, with |
| -// Adaptive Pricing on, with a conversion, or with no currency at all, is |
| -// refused. |
| -func TestCreateCheckout_FixedCurrency(t *testing.T) { |
| - type response map[string]any |
| - ok := func(currency string) response { |
| - return response{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": currency} |
| - } |
| - with := func(r response, k string, v any) response { r[k] = v; return r } |
| - for name, tc := range map[string]struct { |
| - currency string |
| - answer response |
| - wantCode string |
| - }{ |
| - "usd": {"usd", ok("usd"), ""}, |
| - "gbp": {"gbp", ok("gbp"), ""}, |
| - "adaptive pricing reported off": {"gbp", with(ok("gbp"), "adaptive_pricing", map[string]any{"enabled": false}), ""}, |
| - "a null conversion": {"gbp", with(ok("gbp"), "currency_conversion", nil), ""}, |
| - "the session is in another": {"gbp", ok("eur"), CodeCurrencyMismatch}, |
| - "the session names no currency": {"gbp", response{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false}, CodeCurrencyMismatch}, |
| - "adaptive pricing came back on": {"gbp", with(ok("gbp"), "adaptive_pricing", map[string]any{"enabled": true}), CodeCurrencyMismatch}, |
| - "the session carries a conversion": {"gbp", with(ok("gbp"), "currency_conversion", map[string]any{"source_currency": "gbp", "fx_rate": "1.2"}), CodeCurrencyMismatch}, |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - var gotForm map[string][]string |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - _ = r.ParseForm() |
| - gotForm = map[string][]string(r.PostForm) |
| - _ = json.NewEncoder(w).Encode(tc.answer) |
| - })) |
| - defer srv.Close() |
| - meta := validMetadata() |
| - meta.PriceBook, meta.Currency = "2026-10-01-draft1", tc.currency |
| - p := CreateCheckoutParams{CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta, Currency: tc.currency} |
| - sess, err := testClient(t, srv.URL).CreateCheckout(context.Background(), p, "idem-3") |
| - for k, want := range map[string]string{ |
| - "currency": tc.currency, "adaptive_pricing[enabled]": "false", |
| - "metadata[currency]": tc.currency, "metadata[price_book]": "2026-10-01-draft1", |
| - "subscription_data[metadata][currency]": tc.currency, "subscription_data[metadata][price_book]": "2026-10-01-draft1", |
| - } { |
| - if got := gotForm[k]; len(got) != 1 || got[0] != want { |
| - t.Errorf("form[%q] = %v, want %q", k, got, want) |
| - } |
| - } |
| - if tc.wantCode == "" { |
| - if err != nil || !sess.FixedCurrency(tc.currency) { |
| - t.Fatalf("CreateCheckout: %+v %v", sess, err) |
| - } |
| - return |
| - } |
| - // The refusal names the session the provider did create, so |
| - // the caller can expire it. |
| - if e, isErr := err.(*Error); !isErr || e.Code != tc.wantCode || sess != nil || e.SessionID != "cs_1" { |
| - t.Fatalf("CreateCheckout: %+v %v, want %s naming cs_1 and no session", sess, err, tc.wantCode) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// A currency that is not a lower-case three-letter code, or metadata that |
| -// disagrees with it, or lacks a book or a currency, never reaches Stripe. |
| -func TestCreateCheckout_RefusesAMalformedCurrency(t *testing.T) { |
| - calls := 0 |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - calls++ |
| - _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": "eur"}) |
| - })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - base := CreateCheckoutParams{CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata(), Currency: "eur"} |
| - for name, edit := range map[string]func(p *CreateCheckoutParams){ |
| - "no currency": func(p *CreateCheckoutParams) { p.Currency = "" }, |
| - "upper case": func(p *CreateCheckoutParams) { p.Currency = "EUR" }, |
| - "not a code": func(p *CreateCheckoutParams) { p.Currency = "euro" }, |
| - "metadata in another currency": func(p *CreateCheckoutParams) { p.Metadata.PriceBook, p.Metadata.Currency = "b1", "usd" }, |
| - "metadata with a book and no currency": func(p *CreateCheckoutParams) { p.Metadata.Currency = "" }, |
| - "metadata with a currency and no book": func(p *CreateCheckoutParams) { p.Metadata.PriceBook = "" }, |
| - } { |
| - p := base |
| - edit(&p) |
| - if _, err := c.CreateCheckout(context.Background(), p, "idem"); err == nil { |
| - t.Errorf("%s: accepted", name) |
| - } |
| - } |
| - if calls != 0 { |
| - t.Fatalf("%d requests were sent", calls) |
| - } |
| -} |
| - |
| -func TestCreateCheckout_RequiresIdempotencyKey(t *testing.T) { |
| - calls := 0 |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - calls++ |
| - _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1"}) |
| - })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata()} |
| - _, err := c.CreateCheckout(context.Background(), p, "") |
| - if err == nil { |
| - t.Fatal("expected an error for a missing idempotency key") |
| - } |
| - if e, ok := err.(*Error); !ok || e.Code != CodeMissingIdempotencyKey { |
| - t.Fatalf("err = %v, want CodeMissingIdempotencyKey", err) |
| - } |
| - if calls != 0 { |
| - t.Fatalf("expected no HTTP request, got %d", calls) |
| - } |
| -} |
| - |
| -func TestCreateCheckout_MissingMetadataRejected(t *testing.T) { |
| - calls := 0 |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c"} |
| - _, err := c.CreateCheckout(context.Background(), p, "idem") |
| - if err == nil { |
| - t.Fatal("expected an error for incomplete checkout metadata") |
| - } |
| - if calls != 0 { |
| - t.Fatalf("expected no HTTP request, got %d", calls) |
| - } |
| -} |
| - |
| -func TestCreateCheckout_MissingIntentIDRejectedWithoutHTTPCall(t *testing.T) { |
| - calls := 0 |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - meta := validMetadata() |
| - meta.IntentID = "" |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta} |
| - _, err := c.CreateCheckout(context.Background(), p, "idem") |
| - if err == nil { |
| - t.Fatal("expected an error for a missing checkout intent id") |
| - } |
| - if e, ok := err.(*Error); !ok || e.Code != CodeInvalidParams { |
| - t.Fatalf("err = %v, want CodeInvalidParams", err) |
| - } |
| - if calls != 0 { |
| - t.Fatalf("expected no HTTP request, got %d", calls) |
| - } |
| -} |
| - |
| -func TestCreateCheckout_InvalidIntentIDRejectedWithoutHTTPCall(t *testing.T) { |
| - calls := 0 |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - meta := validMetadata() |
| - meta.IntentID = "../../etc/passwd" |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta} |
| - _, err := c.CreateCheckout(context.Background(), p, "idem") |
| - if err == nil { |
| - t.Fatal("expected an error for a malformed checkout intent id") |
| - } |
| - if e, ok := err.(*Error); !ok || e.Code != CodeInvalidParams { |
| - t.Fatalf("err = %v, want CodeInvalidParams", err) |
| - } |
| - if calls != 0 { |
| - t.Fatalf("expected no HTTP request, got %d", calls) |
| - } |
| -} |
| - |
| -func TestCreateCheckout_RejectsUnexpectedRedirectHost(t *testing.T) { |
| - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://evil.example.com/phish", "livemode": false}) |
| - })) |
| - defer srv.Close() |
| - c := testClient(t, srv.URL) |
| - p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata()} |
| - _, err := c.CreateCheckout(context.Background(), p, "idem") |
| - e, ok := err.(*Error) |
| - if !ok || e.Code != CodeUnexpectedRedirectURL { |
| - t.Fatalf("err = %v, want CodeUnexpectedRedirectURL", err) |
| - } |
| -} |
| - |
| func TestCreatePortal_ValidatesRedirectHost(t *testing.T) { |
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| _ = json.NewEncoder(w).Encode(map[string]any{"id": "bps_1", "url": "https://billing.stripe.com/session/bps_1"}) |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index 54814b41f..5c7135844 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -227,10 +227,15 @@ func decodeResult(prep billing.Prepared, raw json.RawMessage, date time.Time, re |
| // 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); |
| +// - a 409 saying a request under the same key is still executing |
| +// (idempotency_key_in_use, or an idempotency_error): ErrInFlight |
| +// (fact 3); |
| +// - any other 409, such as a lock on the object held by a concurrent |
| +// request: ErrNotExecuted (fact 2: a conflict with a concurrently |
| +// executing request begins no execution and saves nothing); |
| +// - an idempotency_error that is not a 409: 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; |
| @@ -255,7 +260,10 @@ func classify(err error) error { |
| case e.HTTPStatus == http.StatusPaymentRequired || e.StripeType == "card_error": |
| class = billing.ErrPaymentFailed |
| case e.HTTPStatus == http.StatusConflict: |
| - class = billing.ErrInFlight |
| + class = billing.ErrNotExecuted |
| + if e.StripeType == "idempotency_error" || e.StripeCode == "idempotency_key_in_use" { |
| + class = billing.ErrInFlight |
| + } |
| case e.StripeType == "idempotency_error": |
| class = billing.ErrIdempotencyMismatch |
| case e.HTTPStatus == http.StatusTooManyRequests: |
diff --git a/internal/billingstripe/prepared_test.go b/internal/billingstripe/prepared_test.go| index b92dbebb7..560d401e6 100644 |
| --- a/internal/billingstripe/prepared_test.go |
| +++ b/internal/billingstripe/prepared_test.go |
| @@ -85,6 +85,8 @@ func allPrepared(t *testing.T, p *Provider) map[string]billing.Prepared { |
| type captured struct { |
| method, path, key string |
| body []byte |
| + length int64 // the request's Content-Length, -1 when unknown |
| + chunked []string // its Transfer-Encoding |
| } |
| type capture struct { |
| @@ -94,7 +96,8 @@ type capture struct { |
| 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} |
| + got := captured{method: r.Method, path: r.URL.Path, key: r.Header.Get("Idempotency-Key"), body: b, |
| + length: r.ContentLength, chunked: r.TransferEncoding} |
| c.mu.Lock() |
| c.reqs = append(c.reqs, got) |
| c.mu.Unlock() |
| @@ -167,6 +170,9 @@ func TestPrepareIsDeterministic(t *testing.T) { |
| 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) |
| } |
| + if got.length != int64(len(a.Body)) || len(got.chunked) != 0 { |
| + t.Errorf("%s: sent with Content-Length %d, Transfer-Encoding %v; want %d, none", name, got.length, got.chunked, len(a.Body)) |
| + } |
| } |
| // The change's and renewal's parameters, exactly. |
| @@ -332,20 +338,29 @@ func TestSendVerbatimOneRequest(t *testing.T) { |
| 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 connection dropped after the request was written: the transport |
| + // must not resend it on its own, for any kind. On a pooled, kept-alive |
| + // connection net/http would: an Idempotency-Key header makes a POST |
| + // replayable when its body can be rewound, and always when it is empty |
| + // (Expire). The send before each drop would warm such a connection. |
| + for name, kind := range allPrepared(t, p) { |
| + mode.Store("ok") |
| + if _, err := p.Send(context.Background(), prep); err != nil { |
| + t.Fatalf("%s: warm the connection: %v", name, err) |
| + } |
| + before := c.count() |
| + mode.Store("drop") |
| + if _, err := p.Send(context.Background(), kind); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("%s: dropped: %v", name, err) |
| + } |
| + if got := c.count() - before; got != 1 { |
| + t.Errorf("%s: dropped connection: %d requests, want 1 (no transport retry)", name, got) |
| + } |
| + if got := c.last(); string(got.body) != string(kind.Body) || got.key != kind.Key { |
| + t.Errorf("%s: dropped request carried body %q key %q", name, got.body, got.key) |
| + } |
| } |
| + sent := c.count() |
| // A malformed Prepared is never sent. |
| for name, bad := range map[string]billing.Prepared{ |
| @@ -359,7 +374,7 @@ func TestSendVerbatimOneRequest(t *testing.T) { |
| t.Errorf("%s: %v", name, err) |
| } |
| } |
| - if c.count() != 4 { |
| + if c.count() != sent { |
| t.Errorf("a malformed Prepared was sent") |
| } |
| } |
| @@ -378,7 +393,9 @@ func TestOutcomeClasses(t *testing.T) { |
| {"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}, |
| + {"409 key in use, other type", &answer{409, `{"error":{"type":"invalid_request_error","code":"idempotency_key_in_use"}}`}, billing.ErrInFlight}, |
| + {"409 lock on the object", &answer{409, `{"error":{"type":"invalid_request_error","code":"lock_timeout"}}`}, billing.ErrNotExecuted}, |
| + {"409 unexplained", &answer{409, ``}, billing.ErrNotExecuted}, |
| {"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}, |
| @@ -837,3 +854,52 @@ func TestCollectingOf(t *testing.T) { |
| t.Errorf("sub = %+v, %v", sub, err) |
| } |
| } |
| + |
| +func TestPrepareCheckoutRefuses(t *testing.T) { |
| + p := prepProvider(t, "http://127.0.0.1:1", nil) |
| + cases := map[string]func(r *billing.CheckoutRequest){ |
| + "no items": func(r *billing.CheckoutRequest) { r.Items = nil }, |
| + "zero quantity": func(r *billing.CheckoutRequest) { r.Items[0].Quantity = 0 }, |
| + "bad price id": func(r *billing.CheckoutRequest) { r.Items[0].PriceID = "price p" }, |
| + "no success url": func(r *billing.CheckoutRequest) { r.SuccessURL = "" }, |
| + "no cancel url": func(r *billing.CheckoutRequest) { r.CancelURL = "" }, |
| + "no account": func(r *billing.CheckoutRequest) { r.AccountSqid = "" }, |
| + "no intent": func(r *billing.CheckoutRequest) { r.IntentID = "" }, |
| + "bad intent": func(r *billing.CheckoutRequest) { r.IntentID = "ci/1" }, |
| + "no book": func(r *billing.CheckoutRequest) { r.Book = "" }, |
| + "upper-case currency": func(r *billing.CheckoutRequest) { r.Currency = "USD" }, |
| + "no customer": func(r *billing.CheckoutRequest) { r.Customer = "" }, |
| + "bad customer": func(r *billing.CheckoutRequest) { r.Customer = "../cus" }, |
| + "bad coupon": func(r *billing.CheckoutRequest) { r.Coupon = "house/100" }, |
| + } |
| + for name, edit := range cases { |
| + r := checkoutRequest() |
| + r.Items = append([]billing.CheckoutItem(nil), r.Items...) |
| + edit(&r) |
| + if _, err := p.PrepareCheckout(r); err == nil { |
| + t.Errorf("%s: prepared", name) |
| + } |
| + } |
| +} |
| + |
| +// A Checkout answer that is not a fixed-currency session on Stripe's own |
| +// host is not the session asked for: indeterminate, never handed on. |
| +func TestSendCheckoutAnswerIsTheSessionAskedFor(t *testing.T) { |
| + cases := map[string]string{ |
| + "other currency": `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9","currency":"eur"}`, |
| + "no currency": `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9"}`, |
| + "adaptive pricing": `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9","currency":"usd","adaptive_pricing":{"enabled":true}}`, |
| + "converted": `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9","currency":"usd","currency_conversion":{"source_currency":"eur"}}`, |
| + "other host": `{"id":"cs_9","livemode":false,"status":"open","url":"https://checkout.example.com/c/pay/cs_9","currency":"usd"}`, |
| + } |
| + for name, body := range cases { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) })) |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, _ := p.PrepareCheckout(checkoutRequest()) |
| + res, err := p.Send(context.Background(), prep) |
| + if !errors.Is(err, billing.ErrIndeterminate) || res.Checkout != nil { |
| + t.Errorf("%s: %+v, %v", name, res.Checkout, err) |
| + } |
| + srv.Close() |
| + } |
| +} |