billing: one-off authorise-and-capture payments (Stripe Checkout payment mode)
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
6 files changed,
+810
−13
internal/billing/billing.go+39 −8internal/billing/billingtest/fake.go+130 −4internal/billing/billingtest/payment_test.go+125 −0internal/billingstripe/payment.go+179 −0internal/billingstripe/payment_test.go+329 −0internal/billingstripe/prepared.go+8 −1
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index a1e628ed2..436fe964a 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -143,6 +143,26 @@ type CheckoutRequest struct { |
| IdempotencyKey string |
| } |
| +type PaymentCheckoutRequest struct { |
| + AccountSqid, Customer, Currency string |
| + Amount int64 |
| + Description string |
| + Reference string |
| + SuccessURL, CancelURL string |
| + ExpiresAt time.Time |
| + Key string |
| +} |
| + |
| +func (PaymentCheckoutRequest) String() string { return "billing.PaymentCheckoutRequest{redacted}" } |
| +func (r PaymentCheckoutRequest) GoString() string { return r.String() } |
| + |
| +type PaymentInfo struct { |
| + SessionID, URL, PaymentIntent, Status string |
| + Authorised bool |
| + Amount, AmountTotal int64 |
| + Currency string |
| +} |
| + |
| // CheckoutState is a Checkout session's state. |
| type CheckoutState string |
| @@ -161,11 +181,14 @@ type CheckoutInfo struct { |
| // The kinds of Prepared. |
| const ( |
| - PreparedCustomer = "customer" |
| - PreparedCheckout = "checkout" |
| - PreparedExpire = "expire" |
| - PreparedChange = "change" |
| - PreparedRenewal = "renewal" |
| + PreparedCustomer = "customer" |
| + PreparedCheckout = "checkout" |
| + PreparedExpire = "expire" |
| + PreparedChange = "change" |
| + PreparedRenewal = "renewal" |
| + PreparedPaymentCheckout = "payment_checkout" |
| + PreparedCapture = "capture" |
| + PreparedCancelPayment = "cancel_payment" |
| ) |
| // Prepared is a write exactly as the adapter will send it: opaque to the |
| @@ -178,6 +201,9 @@ type Prepared struct { |
| Key string |
| } |
| +func (Prepared) String() string { return "billing.Prepared{redacted}" } |
| +func (p Prepared) GoString() string { return p.String() } |
| + |
| // Result is what a definite answer to a Send says. Which fields are set |
| // depends on the Prepared's kind. |
| type Result struct { |
| @@ -187,9 +213,10 @@ type Result struct { |
| // 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) |
| - ProviderTime time.Time // the response's Date header; zero when it had none |
| + Payment *PaymentInfo |
| + Customer string // a customer create |
| + Replayed bool // the provider replayed a stored answer (fact 7) |
| + ProviderTime time.Time // the response's Date header; zero when it had none |
| } |
| // InvoiceQuantities is a renewal invoice reduced to the quantity it billed |
| @@ -260,6 +287,10 @@ type Provider interface { |
| PrepareExpire(sessionID, key string) (Prepared, error) |
| PrepareChange(req ChangeRequest) (Prepared, error) |
| PrepareRenewal(subscription string, renew bool, key string) (Prepared, error) |
| + PreparePaymentCheckout(req PaymentCheckoutRequest) (Prepared, error) |
| + PaymentCheckout(ctx context.Context, sessionID string) (PaymentInfo, error) |
| + PrepareCapture(paymentIntent, key string) (Prepared, error) |
| + PrepareCancelPayment(paymentIntent, 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 |
| // classes (ErrPaymentFailed, ErrRefused, ErrNotExecuted, ErrInFlight, |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index d8de4964c..5d3a07a84 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -133,9 +133,10 @@ type Fake struct { |
| // Customers, Sessions and Invoices are the rest of the provider's |
| // state. AddSession and AddInvoice seed them with ids. |
| - Customers map[string]*Customer |
| - Sessions map[string]*Session |
| - Invoices map[string]*Invoice |
| + Customers map[string]*Customer |
| + Sessions map[string]*Session |
| + Invoices map[string]*Invoice |
| + paymentSessions map[string]*paymentSession |
| // CallsBy counts requests by method name: "Subscription", |
| // "CheckoutSubscription", "Check", "Send", "Checkout", "PortalURL", |
| @@ -269,6 +270,9 @@ func (f *Fake) init() { |
| if f.Sessions == nil { |
| f.Sessions = map[string]*Session{} |
| } |
| + if f.paymentSessions == nil { |
| + f.paymentSessions = map[string]*paymentSession{} |
| + } |
| if f.Invoices == nil { |
| f.Invoices = map[string]*Invoice{} |
| } |
| @@ -407,6 +411,11 @@ func (f *Fake) nextID(prefix string) string { |
| // open sessions expire. It also gives seeded items their ids. |
| func (f *Fake) settle() { |
| now := f.ProviderClock |
| + for _, s := range f.paymentSessions { |
| + if s.Status == "open" && !now.Before(s.Request.ExpiresAt) { |
| + s.Status = "expired" |
| + } |
| + } |
| for id, s := range f.Subs { |
| for i := range s.Items { |
| if s.Items[i].ItemID == "" { |
| @@ -436,6 +445,10 @@ func snapshot(s *billing.Subscription) *billing.Subscription { |
| } |
| func cloneResult(r billing.Result) billing.Result { |
| + if r.Payment != nil { |
| + c := *r.Payment |
| + r.Payment = &c |
| + } |
| if r.Subscription != nil { |
| r.Subscription = snapshot(r.Subscription) |
| } |
| @@ -812,6 +825,14 @@ func fromUnix(s int64) time.Time { |
| func pathFor(kind string, body any) string { |
| switch b := body.(type) { |
| + case *paymentCheckoutBody: |
| + return "/v1/checkout/sessions" |
| + case *paymentActionBody: |
| + action := "capture" |
| + if b.Cancel { |
| + action = "cancel" |
| + } |
| + return "/v1/payment_intents/" + b.Intent + "/" + action |
| case *customerBody: |
| return "/v1/customers" |
| case *checkoutBody: |
| @@ -892,6 +913,10 @@ 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.PreparedPaymentCheckout: |
| + body = &paymentCheckoutBody{} |
| + case billing.PreparedCapture, billing.PreparedCancelPayment: |
| + body = &paymentActionBody{} |
| case billing.PreparedCustomer: |
| body = &customerBody{} |
| case billing.PreparedCheckout: |
| @@ -920,6 +945,11 @@ func decode(p billing.Prepared) (any, error) { |
| // validate is the provider's parameter validation, before execution: a |
| // refusal here is not stored under the key (fact 2). |
| func (f *Fake) validate(body any) error { |
| + if b, ok := body.(*paymentCheckoutBody); ok { |
| + if b.Request.ExpiresAt.Before(f.ProviderClock.Add(30*time.Minute)) || b.Request.ExpiresAt.After(f.ProviderClock.Add(24*time.Hour)) { |
| + return billing.ErrRefused |
| + } |
| + } |
| if b, ok := body.(*checkoutBody); ok { |
| exp := fromUnix(b.ExpiresAt) |
| now := f.ProviderClock |
| @@ -986,7 +1016,7 @@ func (f *Fake) send(ctx context.Context, p billing.Prepared) (billing.Result, er |
| case !e.same(p): |
| 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) |
| + return billing.Result{ProviderTime: d}, fmt.Errorf("%w: 409", billing.ErrInFlight) |
| } |
| r := cloneResult(e.result) |
| r.Replayed, r.ProviderTime = true, d |
| @@ -1060,6 +1090,30 @@ func (f *Fake) land(l *lateSend) { |
| // execute applies a parsed request to the provider's state. |
| func (f *Fake) execute(body any) (billing.Result, error) { |
| switch b := body.(type) { |
| + case *paymentCheckoutBody: |
| + id := f.nextID("cs") |
| + s := &paymentSession{PaymentInfo: billing.PaymentInfo{SessionID: id, URL: "https://checkout.example.test/c/" + id, |
| + Status: "open", Amount: b.Request.Amount, AmountTotal: b.Request.Amount, Currency: b.Request.Currency}, Request: b.Request} |
| + f.paymentSessions[id] = s |
| + info := s.PaymentInfo |
| + return billing.Result{Payment: &info}, nil |
| + case *paymentActionBody: |
| + for _, s := range f.paymentSessions { |
| + if s.PaymentIntent != b.Intent { |
| + continue |
| + } |
| + if s.intentStatus != "requires_capture" { |
| + return billing.Result{}, billing.ErrRefused |
| + } |
| + s.intentStatus = "succeeded" |
| + if b.Cancel { |
| + s.intentStatus = "canceled" |
| + } |
| + s.Authorised = false |
| + info := billing.PaymentInfo{PaymentIntent: s.PaymentIntent, Status: s.intentStatus, AmountTotal: s.AmountTotal, Currency: s.Currency} |
| + return billing.Result{Payment: &info}, nil |
| + } |
| + return billing.Result{}, billing.ErrRefused |
| case *customerBody: |
| id := f.nextID("cus") |
| f.Customers[id] = &Customer{ID: id, Account: b.Account} |
| @@ -1387,3 +1441,75 @@ func (f *Fake) AddInvoice(inv *Invoice) string { |
| } |
| var _ billing.Provider = (*Fake)(nil) |
| + |
| +type paymentSession struct { |
| + billing.PaymentInfo |
| + Request billing.PaymentCheckoutRequest |
| + intentStatus string |
| +} |
| + |
| +type paymentCheckoutBody struct { |
| + Request billing.PaymentCheckoutRequest |
| +} |
| +type paymentActionBody struct { |
| + Intent string |
| + Cancel bool |
| +} |
| + |
| +func (f *Fake) PreparePaymentCheckout(req billing.PaymentCheckoutRequest) (billing.Prepared, error) { |
| + if req.AccountSqid == "" || req.Customer == "" || req.Currency == "" || req.Amount <= 0 || req.Description == "" || req.Reference == "" || req.SuccessURL == "" || req.CancelURL == "" || req.ExpiresAt.IsZero() { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + key := req.Key |
| + req.Key = "" |
| + return prepare(billing.PreparedPaymentCheckout, key, &paymentCheckoutBody{Request: req}) |
| +} |
| + |
| +func (f *Fake) PrepareCapture(paymentIntent, key string) (billing.Prepared, error) { |
| + if paymentIntent == "" { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + return prepare(billing.PreparedCapture, key, &paymentActionBody{Intent: paymentIntent}) |
| +} |
| + |
| +func (f *Fake) PrepareCancelPayment(paymentIntent, key string) (billing.Prepared, error) { |
| + if paymentIntent == "" { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + return prepare(billing.PreparedCancelPayment, key, &paymentActionBody{Intent: paymentIntent, Cancel: true}) |
| +} |
| + |
| +func (f *Fake) PaymentCheckout(ctx context.Context, sessionID string) (billing.PaymentInfo, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("PaymentCheckout") |
| + defer f.end() |
| + if f.Err != nil { |
| + return billing.PaymentInfo{}, f.Err |
| + } |
| + if f.timedOut() { |
| + return billing.PaymentInfo{}, billing.ErrNoResponse |
| + } |
| + f.respond(ctx) |
| + s, ok := f.paymentSessions[sessionID] |
| + if !ok { |
| + return billing.PaymentInfo{}, billing.ErrNotFound |
| + } |
| + return s.PaymentInfo, nil |
| +} |
| + |
| +func (f *Fake) CompletePaymentCheckout(sessionID string) (string, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + f.settle() |
| + s, ok := f.paymentSessions[sessionID] |
| + if !ok || s.Status != "open" { |
| + return "", billing.ErrRefused |
| + } |
| + s.Status = "complete" |
| + s.PaymentIntent = f.nextID("pi") |
| + s.intentStatus = "requires_capture" |
| + s.Authorised = true |
| + return s.PaymentIntent, nil |
| +} |
diff --git a/internal/billing/billingtest/payment_test.go b/internal/billing/billingtest/payment_test.go| new file mode 100644 |
| index 000000000..da36f8f3e |
| --- /dev/null |
| +++ b/internal/billing/billingtest/payment_test.go |
| @@ -0,0 +1,125 @@ |
| +package billingtest |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func fakePaymentRequest() billing.PaymentCheckoutRequest { |
| + return billing.PaymentCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", Currency: "eur", Amount: 1500, Description: "example.com", Reference: "purchase_1", |
| + SuccessURL: "https://console.example.com/done", CancelURL: "https://console.example.com/cancel", ExpiresAt: t0.Add(time.Hour), Key: "payment-key"} |
| +} |
| + |
| +func TestFakePaymentLifecycle(t *testing.T) { |
| + for _, cancel := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "capture", true: "cancel"}[cancel], func(t *testing.T) { |
| + f := newFake(t) |
| + ctx := context.Background() |
| + prep, err := f.PreparePaymentCheckout(fakePaymentRequest()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Calls != 0 { |
| + t.Fatal("Prepare made a call") |
| + } |
| + res, err := f.Send(ctx, prep) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if res.Payment == nil || res.Payment.Authorised || res.Payment.Status != "open" { |
| + t.Fatalf("open: %+v", res.Payment) |
| + } |
| + id := res.Payment.SessionID |
| + if _, err := f.CompletePaymentCheckout(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + info, err := f.PaymentCheckout(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !info.Authorised || info.PaymentIntent == "" || info.Amount != 1500 || info.AmountTotal != 1500 || info.Currency != "eur" { |
| + t.Fatalf("authorised: %+v", info) |
| + } |
| + prepare := f.PrepareCapture |
| + status := "succeeded" |
| + if cancel { |
| + prepare = f.PrepareCancelPayment |
| + status = "canceled" |
| + } |
| + action, err := prepare(info.PaymentIntent, "action-key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.LoseNextResponse = true |
| + if _, err := f.Send(ctx, action); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("lost: %v", err) |
| + } |
| + done, err := f.Send(ctx, action) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !done.Replayed || done.Payment == nil || done.Payment.Status != status { |
| + t.Fatalf("replay: %+v", done) |
| + } |
| + done.Payment.Status = "mutated" |
| + replay, err := f.Send(ctx, action) |
| + if err != nil || replay.Payment.Status != status { |
| + t.Fatal("caller mutated stored answer") |
| + } |
| + info, err = f.PaymentCheckout(ctx, id) |
| + if err != nil || info.Authorised { |
| + t.Fatalf("settled: %+v, %v", info, err) |
| + } |
| + if cancel { |
| + capture, err := f.PrepareCapture(info.PaymentIntent, "capture-after-cancel") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.Send(ctx, capture); !errors.Is(err, billing.ErrRefused) { |
| + t.Fatalf("capture after cancel: %v", err) |
| + } |
| + } |
| + replay, err = f.Send(ctx, prep) |
| + if err != nil || !replay.Replayed || replay.Payment.Status != "open" { |
| + t.Fatal("create replay was not frozen") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestFakePaymentExpiryAndKeyMismatch(t *testing.T) { |
| + f := newFake(t) |
| + ctx := context.Background() |
| + req := fakePaymentRequest() |
| + prep, err := f.PreparePaymentCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res, err := f.Send(ctx, prep) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Amount++ |
| + different, err := f.PreparePaymentCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.Send(ctx, different); !errors.Is(err, billing.ErrIdempotencyMismatch) { |
| + t.Fatalf("changed request: %v", err) |
| + } |
| + f.AdvanceProvider(time.Hour) |
| + info, err := f.PaymentCheckout(ctx, res.Payment.SessionID) |
| + if err != nil || info.Status != "expired" || info.Authorised { |
| + t.Fatalf("expired: %+v, %v", info, err) |
| + } |
| + if _, err := f.CompletePaymentCheckout(info.SessionID); !errors.Is(err, billing.ErrRefused) { |
| + t.Fatalf("completed expired session: %v", err) |
| + } |
| + if _, err := f.PaymentCheckout(ctx, "cs_missing"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("missing session: %v", err) |
| + } |
| +} |
diff --git a/internal/billingstripe/payment.go b/internal/billingstripe/payment.go| new file mode 100644 |
| index 000000000..afa1635a4 |
| --- /dev/null |
| +++ b/internal/billingstripe/payment.go |
| @@ -0,0 +1,179 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func (p *Provider) PreparePaymentCheckout(req billing.PaymentCheckoutRequest) (billing.Prepared, error) { |
| + if !validID(req.Customer) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + if req.AccountSqid == "" || req.Reference == "" || !validCurrency(req.Currency) || req.Amount <= 0 || req.Description == "" || |
| + req.SuccessURL == "" || req.CancelURL == "" || req.ExpiresAt.IsZero() || req.ExpiresAt.Unix() <= 0 { |
| + 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"}, |
| + } |
| + return prepared(billing.PreparedPaymentCheckout, "/v1/checkout/sessions", form, req.Key) |
| +} |
| + |
| +func (p *Provider) PrepareCapture(paymentIntent, key string) (billing.Prepared, error) { |
| + if !validID(paymentIntent) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + return prepared(billing.PreparedCapture, "/v1/payment_intents/"+paymentIntent+"/capture", url.Values{}, key) |
| +} |
| + |
| +func (p *Provider) PrepareCancelPayment(paymentIntent, key string) (billing.Prepared, error) { |
| + if !validID(paymentIntent) { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidID} |
| + } |
| + return prepared(billing.PreparedCancelPayment, "/v1/payment_intents/"+paymentIntent+"/cancel", url.Values{}, key) |
| +} |
| + |
| +type paymentIntent struct { |
| + ID string `json:"id"` |
| + Status string `json:"status"` |
| + Amount *int64 `json:"amount"` |
| + Currency string `json:"currency"` |
| +} |
| + |
| +func (pi paymentIntent) valid() bool { |
| + if !validID(pi.ID) || pi.Amount == nil || *pi.Amount <= 0 || !validCurrency(pi.Currency) { |
| + return false |
| + } |
| + switch pi.Status { |
| + case "requires_payment_method", "requires_confirmation", "requires_action", "processing", "requires_capture", "canceled", "succeeded": |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +func paymentSessionInfo(raw json.RawMessage) (billing.PaymentInfo, error) { |
| + var s struct { |
| + ID string `json:"id"` |
| + URL string `json:"url"` |
| + Mode string `json:"mode"` |
| + Status string `json:"status"` |
| + LiveMode *bool `json:"livemode"` |
| + Amount *int64 `json:"amount_subtotal"` |
| + AmountTotal *int64 `json:"amount_total"` |
| + Currency string `json:"currency"` |
| + PaymentIntent idOrExpanded `json:"payment_intent"` |
| + AdaptivePricing struct { |
| + Enabled bool `json:"enabled"` |
| + } `json:"adaptive_pricing"` |
| + CurrencyConversion json.RawMessage `json:"currency_conversion"` |
| + } |
| + if err := json.Unmarshal(raw, &s); err != nil { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + if !validID(s.ID) || s.Mode != "payment" || s.LiveMode == nil || s.Amount == nil || *s.Amount <= 0 || s.AmountTotal == nil || *s.AmountTotal < *s.Amount || !validCurrency(s.Currency) { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + if s.AdaptivePricing.Enabled || (len(s.CurrencyConversion) > 0 && string(s.CurrencyConversion) != "null") { |
| + return billing.PaymentInfo{}, &Error{Code: CodeCurrencyMismatch} |
| + } |
| + switch s.Status { |
| + case "open", "complete", "expired": |
| + default: |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + if s.URL != "" { |
| + if err := validateRedirectURL(s.URL, "checkout.stripe.com"); err != nil { |
| + return billing.PaymentInfo{}, err |
| + } |
| + } |
| + info := billing.PaymentInfo{SessionID: s.ID, URL: s.URL, PaymentIntent: s.PaymentIntent.ID, Status: s.Status, Amount: *s.Amount, AmountTotal: *s.AmountTotal, Currency: s.Currency} |
| + if s.PaymentIntent.ID != "" && !validID(s.PaymentIntent.ID) { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + if s.PaymentIntent.Object != nil { |
| + var pi paymentIntent |
| + if err := json.Unmarshal(s.PaymentIntent.Object, &pi); err != nil || !pi.valid() || pi.Currency != s.Currency || *pi.Amount != *s.AmountTotal { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + info.Authorised = s.Status == "complete" && pi.Status == "requires_capture" |
| + } else if s.Status == "complete" { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + return info, nil |
| +} |
| + |
| +func (p *Provider) PaymentCheckout(ctx context.Context, sessionID string) (billing.PaymentInfo, error) { |
| + if !validID(sessionID) { |
| + return billing.PaymentInfo{}, &Error{Code: CodeInvalidID} |
| + } |
| + var raw json.RawMessage |
| + err := p.client.do(ctx, http.MethodGet, "/v1/checkout/sessions/"+sessionID, url.Values{"expand[]": {"payment_intent"}}, "", &raw) |
| + if notFound(err) { |
| + return billing.PaymentInfo{}, billing.ErrNotFound |
| + } |
| + if err != nil { |
| + return billing.PaymentInfo{}, err |
| + } |
| + info, err := paymentSessionInfo(raw) |
| + if err != nil { |
| + return billing.PaymentInfo{}, err |
| + } |
| + if info.SessionID != sessionID { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + return info, nil |
| +} |
| + |
| +func paymentResult(prep billing.Prepared, raw json.RawMessage) (billing.PaymentInfo, error) { |
| + if prep.Kind == billing.PreparedPaymentCheckout { |
| + info, err := paymentSessionInfo(raw) |
| + if err != nil { |
| + return billing.PaymentInfo{}, err |
| + } |
| + form, err := url.ParseQuery(string(prep.Body)) |
| + if err != nil { |
| + return billing.PaymentInfo{}, &Error{Code: CodeInvalidParams} |
| + } |
| + amount, err := strconv.ParseInt(form.Get("line_items[0][price_data][unit_amount]"), 10, 64) |
| + if err != nil || amount != info.Amount || form.Get("line_items[0][price_data][currency]") != info.Currency { |
| + return billing.PaymentInfo{}, &Error{Code: CodeCurrencyMismatch} |
| + } |
| + return info, nil |
| + } |
| + var pi paymentIntent |
| + if err := json.Unmarshal(raw, &pi); err != nil || !pi.valid() { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + action, status := "capture", "succeeded" |
| + if prep.Kind == billing.PreparedCancelPayment { |
| + action, status = "cancel", "canceled" |
| + } |
| + if prep.Path != "/v1/payment_intents/"+pi.ID+"/"+action || pi.Status != status { |
| + return billing.PaymentInfo{}, &Error{Code: CodeDecodeError} |
| + } |
| + return billing.PaymentInfo{PaymentIntent: pi.ID, Status: pi.Status, AmountTotal: *pi.Amount, Currency: pi.Currency}, nil |
| +} |
diff --git a/internal/billingstripe/payment_test.go b/internal/billingstripe/payment_test.go| new file mode 100644 |
| index 000000000..b3fc86830 |
| --- /dev/null |
| +++ b/internal/billingstripe/payment_test.go |
| @@ -0,0 +1,329 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func paymentRequest() billing.PaymentCheckoutRequest { |
| + return billing.PaymentCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", Currency: "eur", Amount: 1500, |
| + Description: "example.com", Reference: "purchase_1", SuccessURL: "https://console.example.com/done", CancelURL: "https://console.example.com/cancel", |
| + ExpiresAt: providerDate.Add(time.Hour), Key: "payment-key"} |
| +} |
| + |
| +func paymentSessionJSON(status, intentStatus string) string { |
| + var pi any |
| + if intentStatus != "" { |
| + pi = map[string]any{"id": "pi_1", "status": intentStatus, "amount": 1845, "currency": "eur"} |
| + } |
| + b, _ := json.Marshal(map[string]any{"id": "cs_1", "mode": "payment", "livemode": false, "status": status, |
| + "url": "https://checkout.stripe.com/c/pay/cs_1", "currency": "eur", "amount_subtotal": 1500, "amount_total": 1845, "payment_intent": pi}) |
| + return string(b) |
| +} |
| + |
| +func TestPaymentCheckoutForm(t *testing.T) { |
| + var cap capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cap.add(r) |
| + fmt.Fprint(w, paymentSessionJSON("open", "")) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + req := paymentRequest() |
| + prep, err := p.PreparePaymentCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cap.count() != 0 { |
| + t.Fatal("Prepare made a request") |
| + } |
| + 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"}, |
| + "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"}, |
| + "success_url": {req.SuccessURL}, "cancel_url": {req.CancelURL}, |
| + } |
| + got, err := url.ParseQuery(string(prep.Body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range want { |
| + if !reflect.DeepEqual(got[k], v) { |
| + t.Errorf("form field %s differs", k) |
| + } |
| + } |
| + if got.Get("adaptive_pricing[enabled]") != "false" || got.Get("customer_update[address]") != "auto" { |
| + t.Error("fixed pricing or tax address collection missing") |
| + } |
| + res, err := p.Send(context.Background(), prep) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := cap.last() |
| + if sent.method != "POST" || sent.path != "/v1/checkout/sessions" || sent.key != req.Key || string(sent.body) != string(prep.Body) { |
| + t.Fatal("Send changed request") |
| + } |
| + if res.Payment == nil || res.Payment.SessionID != "cs_1" || res.Payment.Authorised || res.Payment.Amount != 1500 || res.Payment.AmountTotal != 1845 || res.Payment.Currency != "eur" { |
| + t.Fatalf("payment: %+v", res.Payment) |
| + } |
| +} |
| + |
| +func TestPaymentCheckoutAuthorised(t *testing.T) { |
| + for _, tc := range []struct { |
| + session, intent string |
| + want bool |
| + }{ |
| + {"complete", "requires_capture", true}, {"complete", "requires_payment_method", false}, {"open", "requires_capture", false}, |
| + {"complete", "succeeded", false}, {"complete", "canceled", false}, {"expired", "", false}, |
| + } { |
| + t.Run(tc.session+"_"+tc.intent, func(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != "GET" || r.URL.Path != "/v1/checkout/sessions/cs_1" || r.URL.Query().Get("expand[]") != "payment_intent" { |
| + t.Error("wrong payment read") |
| + } |
| + fmt.Fprint(w, paymentSessionJSON(tc.session, tc.intent)) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + info, err := p.PaymentCheckout(context.Background(), "cs_1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if info.Authorised != tc.want || info.Status != tc.session { |
| + t.Fatalf("payment: %+v", info) |
| + } |
| + if tc.intent != "" && info.PaymentIntent != "pi_1" { |
| + t.Error("missing payment intent") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCaptureAndCancelUseIdempotencyKey(t *testing.T) { |
| + for _, op := range []string{"capture", "cancel"} { |
| + t.Run(op, func(t *testing.T) { |
| + var cap capture |
| + status := "succeeded" |
| + if op == "cancel" { |
| + status = "canceled" |
| + } |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cap.add(r) |
| + fmt.Fprintf(w, `{"id":"pi_1","status":%q,"amount":1845,"currency":"eur"}`, status) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prepare := p.PrepareCapture |
| + if op == "cancel" { |
| + prepare = p.PrepareCancelPayment |
| + } |
| + prep, err := prepare("pi_1", "operation-key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cap.count() != 0 { |
| + t.Fatal("Prepare made a request") |
| + } |
| + res, err := p.Send(context.Background(), prep) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := cap.last() |
| + if sent.method != "POST" || sent.path != "/v1/payment_intents/pi_1/"+op || sent.key != "operation-key" || len(sent.body) != 0 { |
| + t.Fatal("wrong keyed payment operation") |
| + } |
| + if res.Payment == nil || res.Payment.PaymentIntent != "pi_1" || res.Payment.Status != status || res.Payment.Authorised { |
| + t.Fatalf("payment: %+v", res.Payment) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCaptureLostAnswerIsIndeterminate(t *testing.T) { |
| + var cap capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cap.add(r) |
| + conn, _, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + conn.Close() |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, err := p.PrepareCapture("pi_1", "capture-key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res, err := p.Send(context.Background(), prep) |
| + if !errors.Is(err, billing.ErrNoResponse) && !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("lost answer: %v", err) |
| + } |
| + if res.Payment != nil || cap.count() != 1 { |
| + t.Fatal("lost answer returned success or retried") |
| + } |
| +} |
| + |
| +func TestPaymentRefusesInvalidInputs(t *testing.T) { |
| + p := prepProvider(t, "http://127.0.0.1:1", nil) |
| + for _, edit := range []func(*billing.PaymentCheckoutRequest){ |
| + func(r *billing.PaymentCheckoutRequest) { r.Customer = "../bad" }, func(r *billing.PaymentCheckoutRequest) { r.AccountSqid = "" }, |
| + func(r *billing.PaymentCheckoutRequest) { r.Currency = "EUR" }, func(r *billing.PaymentCheckoutRequest) { r.Amount = 0 }, |
| + func(r *billing.PaymentCheckoutRequest) { r.Description = "" }, func(r *billing.PaymentCheckoutRequest) { r.Reference = "" }, |
| + func(r *billing.PaymentCheckoutRequest) { r.SuccessURL = "" }, func(r *billing.PaymentCheckoutRequest) { r.CancelURL = "" }, |
| + func(r *billing.PaymentCheckoutRequest) { r.ExpiresAt = time.Time{} }, func(r *billing.PaymentCheckoutRequest) { r.Key = "" }, |
| + } { |
| + req := paymentRequest() |
| + edit(&req) |
| + if _, err := p.PreparePaymentCheckout(req); err == nil { |
| + t.Error("invalid request accepted") |
| + } |
| + } |
| + for _, prepare := range []func(string, string) (billing.Prepared, error){p.PrepareCapture, p.PrepareCancelPayment} { |
| + if _, err := prepare("../bad", "key"); err == nil { |
| + t.Error("invalid intent accepted") |
| + } |
| + if _, err := prepare("pi_1", ""); err == nil { |
| + t.Error("empty key accepted") |
| + } |
| + } |
| + if _, err := p.PaymentCheckout(context.Background(), "../bad"); err == nil { |
| + t.Error("invalid session accepted") |
| + } |
| +} |
| + |
| +func TestPaymentFormattingRedactsKeys(t *testing.T) { |
| + req := paymentRequest() |
| + req.Key = "secret-idempotency-canary" |
| + p := prepProvider(t, "http://127.0.0.1:1", nil) |
| + prep, err := p.PreparePaymentCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, v := range []any{req, &req, prep, &prep, p, p.client} { |
| + for _, format := range []string{"%v", "%+v", "%#v"} { |
| + s := fmt.Sprintf(format, v) |
| + for _, secret := range []string{req.Key, "rk_test_abc", "whsec_primary"} { |
| + if strings.Contains(s, secret) { |
| + t.Fatal("formatted value contains a key or secret") |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestPaymentWriteOutcomes(t *testing.T) { |
| + for _, op := range []string{"checkout", "capture", "cancel"} { |
| + t.Run(op, func(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + status int |
| + body string |
| + want error |
| + }{ |
| + {"declined", 402, `{"error":{"type":"card_error"}}`, billing.ErrPaymentFailed}, |
| + {"in_flight", 409, `{"error":{"code":"idempotency_key_in_use"}}`, billing.ErrInFlight}, |
| + {"rate_limit", 429, `{}`, billing.ErrNotExecuted}, |
| + {"refused", 400, `{}`, billing.ErrRefused}, |
| + {"mismatch", 400, `{"error":{"type":"idempotency_error"}}`, billing.ErrIdempotencyMismatch}, |
| + {"server_error", 500, `{}`, billing.ErrIndeterminate}, |
| + {"null", 200, `null`, billing.ErrIndeterminate}, |
| + {"empty", 200, `{}`, billing.ErrIndeterminate}, |
| + {"malformed", 200, `{"secret":`, billing.ErrIndeterminate}, |
| + {"wrong_intent", 200, `{"id":"pi_wrong","status":"succeeded","amount":1845,"currency":"eur"}`, billing.ErrIndeterminate}, |
| + {"not_settled", 200, `{"id":"pi_1","status":"requires_capture","amount":1845,"currency":"eur"}`, billing.ErrIndeterminate}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Idempotent-Replayed", "true") |
| + w.Header().Set("Date", providerDate.Format(http.TimeFormat)) |
| + w.WriteHeader(tc.status) |
| + fmt.Fprint(w, tc.body) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + var prep billing.Prepared |
| + var err error |
| + switch op { |
| + case "checkout": |
| + prep, err = p.PreparePaymentCheckout(paymentRequest()) |
| + case "capture": |
| + prep, err = p.PrepareCapture("pi_1", "key") |
| + case "cancel": |
| + prep, err = p.PrepareCancelPayment("pi_1", "key") |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res, err := p.Send(context.Background(), prep) |
| + if !errors.Is(err, tc.want) || res.Payment != nil || !res.Replayed || !res.ProviderTime.Equal(providerDate) { |
| + t.Fatalf("result %+v, error %v", res, err) |
| + } |
| + }) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPaymentCheckoutRejectsUntrustedResponse(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edit func(map[string]any) |
| + }{ |
| + {"wrong_session", func(s map[string]any) { s["id"] = "cs_other" }}, |
| + {"wrong_mode", func(s map[string]any) { s["mode"] = "subscription" }}, |
| + {"missing_amount", func(s map[string]any) { delete(s, "amount_subtotal") }}, |
| + {"missing_total", func(s map[string]any) { delete(s, "amount_total") }}, |
| + {"wrong_total", func(s map[string]any) { s["amount_total"] = 1 }}, |
| + {"missing_livemode", func(s map[string]any) { delete(s, "livemode") }}, |
| + {"bad_status", func(s map[string]any) { s["status"] = "unknown" }}, |
| + {"bad_redirect", func(s map[string]any) { s["url"] = "https://attacker.example/c" }}, |
| + {"unexpanded_intent", func(s map[string]any) { s["payment_intent"] = "pi_1" }}, |
| + {"missing_intent", func(s map[string]any) { s["payment_intent"] = nil }}, |
| + {"wrong_intent_amount", func(s map[string]any) { s["payment_intent"].(map[string]any)["amount"] = 1500 }}, |
| + {"wrong_intent_currency", func(s map[string]any) { s["payment_intent"].(map[string]any)["currency"] = "usd" }}, |
| + {"adaptive_pricing", func(s map[string]any) { s["adaptive_pricing"] = map[string]any{"enabled": true} }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var s map[string]any |
| + if err := json.Unmarshal([]byte(paymentSessionJSON("complete", "requires_capture")), &s); err != nil { |
| + t.Fatal(err) |
| + } |
| + tc.edit(s) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(s) })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + info, err := p.PaymentCheckout(context.Background(), "cs_1") |
| + if err == nil || info.Authorised { |
| + t.Fatalf("accepted untrusted response: %+v", info) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPaymentCheckoutNotFound(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"code":"resource_missing"}}`) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + if _, err := p.PaymentCheckout(context.Background(), "cs_1"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("missing session: %v", err) |
| + } |
| +} |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index 00c1ec7bc..d09fd5b45 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -171,7 +171,8 @@ 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.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) |
| } |
| @@ -196,6 +197,12 @@ 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.PreparedPaymentCheckout, billing.PreparedCapture, billing.PreparedCancelPayment: |
| + info, err := paymentResult(prep, raw) |
| + if err != nil { |
| + return err |
| + } |
| + res.Payment = &info |
| case billing.PreparedCustomer: |
| var cus Customer |
| if err := json.Unmarshal(raw, &cus); err != nil { |