carlos / platform Public

billingstripe: read balance movements and charges

billing.Provider gains MoneyMovements, ChargePayments and AccountCreated.
The Stripe provider reads balance transactions (created window, source
expanded, through listAll so a long list is ErrIncomplete), maps a charge
and its refunds to one Payment per balance movement (refund debits and
failed-refund reversals each with their own movement and tax share), and
reads the account's created time. charge.succeeded, charge.captured and
charge.refunded become EventPayment, and stripe-setup.sh subscribes the
endpoint to them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 763d2dfa2bf024a17d364809dc1d41b0bd40ea52 parent 6b5274e
8 files changed, +888 −7
  • cmd/console/stripesetup_script_test.go +11 −2
  • internal/billing/billing.go +10 −0
  • internal/billingstripe/adapter.go +6 −0
  • internal/billingstripe/adapter_test.go +10 −1
  • internal/billingstripe/merchant.go +17 −4
  • internal/billingstripe/money.go +392 −0
  • internal/billingstripe/money_test.go +439 −0
  • scripts/stripe-setup.sh +3 −0
diff --git a/cmd/console/stripesetup_script_test.go b/cmd/console/stripesetup_script_test.go
index 06fe505e2..71ad51b06 100644
--- a/cmd/console/stripesetup_script_test.go
+++ b/cmd/console/stripesetup_script_test.go
@@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "reflect"
"regexp"
"slices"
"strconv"
@@ -369,6 +370,9 @@ func TestStripeSetupLiveApply(t *testing.T) {
if we := fw.Objects["webhook_endpoints"][0]; we["url"] != "https://console.example.com/billing/webhook" || we["api_version"] != "2025-02-24.acacia" {
t.Errorf("webhook endpoint %v at %v", we["url"], we["api_version"])
}
+ if got := fw.Objects["webhook_endpoints"][0]["enabled_events"]; !reflect.DeepEqual(got, webhookEvents) {
+ t.Errorf("webhook endpoint events %v, want %v", got, webhookEvents)
+ }
for _, want := range []string{"CARLOS_BILLING=live", `"2026-11-01-v1/pack/apps/gbp":"price_`, "rk_live_"} {
if !strings.Contains(stdout, want) {
t.Errorf("stdout lacks %q:\n%s", want, stdout)
@@ -538,14 +542,19 @@ func TestStripeSetupRefusesBashX(t *testing.T) {
}
}
+// webhookEvents is every event the console's endpoint subscribes to, in
+// the script's order.
+var webhookEvents = []any{"checkout.session.completed", "customer.subscription.created", "customer.subscription.updated",
+ "customer.subscription.deleted", "invoice.paid", "invoice.payment_failed",
+ "charge.succeeded", "charge.captured", "charge.refunded"}
+
// A Connect application's endpoint at the console's URL is not the
// account's endpoint: it is ignored, and the account's own is made.
func TestStripeSetupIgnoresConnectEndpoint(t *testing.T) {
w := newStripeWorld(t, sandboxAccount, false)
connect := map[string]any{"id": "we_Connect", "object": "webhook_endpoint", "livemode": false, "status": "enabled",
"application": "ca_Other", "url": "https://console.example.com/billing/webhook", "api_version": "2025-02-24.acacia",
- "enabled_events": []any{"checkout.session.completed", "customer.subscription.created", "customer.subscription.updated",
- "customer.subscription.deleted", "invoice.paid", "invoice.payment_failed"}}
+ "enabled_events": webhookEvents}
w.save(fakeStripeWorld{Account: sandboxAccount, Objects: map[string][]map[string]any{"webhook_endpoints": {connect}}})
if stdout, stderr, code := w.run(nil, "--apply"); code != 0 {
t.Fatalf("apply failed (%d):\n%s\n%s", code, stdout, stderr)
diff --git a/internal/billing/billing.go b/internal/billing/billing.go
index 404c5209d..6584dda76 100644
--- a/internal/billing/billing.go
+++ b/internal/billing/billing.go
@@ -363,6 +363,16 @@ type Provider interface {
// ClockProbe is one cheap read whose only purpose is the response's
// Date header, observed into ctx's ClockRecorder.
ClockProbe(ctx context.Context) error
+
+ // MoneyMovements is every balance movement created in [from, to),
+ // oldest first. Exhaustive: ErrIncomplete past MaxListPages pages.
+ MoneyMovements(ctx context.Context, from, to time.Time) ([]Movement, error)
+ // ChargePayments reads a charge and its refunds: one Payment per
+ // balance movement they made. ErrNotFound when the provider has no
+ // such charge; Captured false, and nothing else, when no money moved.
+ ChargePayments(ctx context.Context, charge string) (ChargeRecord, error)
+ // AccountCreated is when the provider account was opened.
+ AccountCreated(ctx context.Context) (time.Time, error)
}
// FindItem is the subscription's item whose price is for kind and name
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go
index 30ad8dc0d..4cae5acda 100644
--- a/internal/billingstripe/adapter.go
+++ b/internal/billingstripe/adapter.go
@@ -185,6 +185,12 @@ func (p *Provider) ParseEvent(raw []byte, header http.Header, now time.Time) (bi
if ev.Type == "checkout.session.completed" {
out.Kind = billing.EventCheckout
}
+ case "charge.succeeded", "charge.captured", "charge.refunded":
+ if err := json.Unmarshal(ev.Object, &obj); err != nil || !validID(obj.ID) {
+ return billing.Event{}, fmt.Errorf("%w: %s has no usable charge id", billing.ErrBadEvent, ev.Type)
+ }
+ out.Object = obj.ID
+ out.Kind = billing.EventPayment
case "invoice.paid", "invoice.payment_failed":
if err := json.Unmarshal(ev.Object, &obj); err != nil {
return billing.Event{}, fmt.Errorf("%w: %s object does not decode", billing.ErrBadEvent, ev.Type)
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go
index 544785b67..1b4e33141 100644
--- a/internal/billingstripe/adapter_test.go
+++ b/internal/billingstripe/adapter_test.go
@@ -121,7 +121,10 @@ func TestParseEventKinds(t *testing.T) {
{"invoice.paid", `{"id":"in_4","subscription":null}`, billing.EventIgnored, ""},
{"invoice.payment_failed", `{"id":"in_5"}`, billing.EventIgnored, ""},
{"checkout.session.completed", `{"id":"cs_1"}`, billing.EventCheckout, "cs_1"},
- {"charge.refunded", `{"id":"ch_1"}`, billing.EventIgnored, ""},
+ {"charge.succeeded", `{"id":"ch_1","object":"charge"}`, billing.EventPayment, "ch_1"},
+ {"charge.captured", `{"id":"ch_2","object":"charge","invoice":"in_1"}`, billing.EventPayment, "ch_2"},
+ {"charge.refunded", `{"id":"py_3","object":"charge"}`, billing.EventPayment, "py_3"},
+ {"charge.failed", `{"id":"ch_4"}`, billing.EventIgnored, ""},
}
for _, tc := range cases {
raw, h := signedEvent(t, "whsec_primary", now, tc.typ, false, tc.object)
@@ -159,6 +162,12 @@ func TestParseEventKinds(t *testing.T) {
"subscription with no id": func() ([]byte, http.Header) {
return signedEvent(t, "whsec_primary", now, "customer.subscription.updated", false, `{"object":"subscription"}`)
},
+ "charge with a bad id": func() ([]byte, http.Header) {
+ return signedEvent(t, "whsec_primary", now, "charge.refunded", false, `{"id":"ch/1"}`)
+ },
+ "charge with no id": func() ([]byte, http.Header) {
+ return signedEvent(t, "whsec_primary", now, "charge.succeeded", false, `{"object":"charge"}`)
+ },
"checkout with a bad id": func() ([]byte, http.Header) {
return signedEvent(t, "whsec_primary", now, "checkout.session.completed", false, `{"id":"cs 1"}`)
},
diff --git a/internal/billingstripe/merchant.go b/internal/billingstripe/merchant.go
index 18f0e3de6..098434350 100644
--- a/internal/billingstripe/merchant.go
+++ b/internal/billingstripe/merchant.go
@@ -6,21 +6,34 @@ import (
"errors"
"net/http"
"strings"
+ "time"
)
// MerchantAccount reads the account belonging to the credential, without a
// Connect account selector. The caller pins its expected merchant ID.
func (c *Client) MerchantAccount(ctx context.Context) (string, error) {
+ id, _, err := c.merchantAccount(ctx)
+ return id, err
+}
+
+// merchantAccount is MerchantAccount with the account's created time, zero
+// when the answer carried none.
+func (c *Client) merchantAccount(ctx context.Context) (string, time.Time, error) {
var account struct {
- ID string `json:"id"`
+ ID string `json:"id"`
+ Created int64 `json:"created"`
}
if err := c.do(ctx, http.MethodGet, "/v1/account", nil, "", &account); err != nil {
- return "", err
+ return "", time.Time{}, err
}
if !validID(account.ID) || !strings.HasPrefix(account.ID, "acct_") {
- return "", &Error{Code: CodeDecodeError}
+ return "", time.Time{}, &Error{Code: CodeDecodeError}
+ }
+ var created time.Time
+ if account.Created > 0 {
+ created = time.Unix(account.Created, 0).UTC()
}
- return account.ID, nil
+ return account.ID, created, nil
}
type Product struct {
diff --git a/internal/billingstripe/money.go b/internal/billingstripe/money.go
new file mode 100644
index 000000000..f7be233fe
--- /dev/null
+++ b/internal/billingstripe/money.go
@@ -0,0 +1,392 @@
+package billingstripe
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/url"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// balanceTxn is a Stripe balance transaction: one movement of the
+// account's balance. Amount and Fee are signed, in Currency's minor units.
+type balanceTxn struct {
+ ID string
+ Type string
+ Amount int64
+ Fee int64
+ Currency string
+ Created time.Time
+ Source idOrExpanded
+}
+
+// UnmarshalJSON decodes a balance transaction strictly: a null object, or
+// one missing its id or created time, cannot pass. A balance transaction
+// carries no livemode; the charge it belongs to does.
+func (t *balanceTxn) UnmarshalJSON(b []byte) error {
+ var raw struct {
+ ID *string `json:"id"`
+ Type string `json:"type"`
+ Amount int64 `json:"amount"`
+ Fee int64 `json:"fee"`
+ Currency string `json:"currency"`
+ Created *int64 `json:"created"`
+ Source idOrExpanded `json:"source"`
+ }
+ if err := json.Unmarshal(b, &raw); err != nil {
+ return err
+ }
+ if raw.ID == nil || !validID(*raw.ID) || raw.Created == nil {
+ return errors.New("billingstripe: balance transaction missing id or created")
+ }
+ *t = balanceTxn{ID: *raw.ID, Type: raw.Type, Amount: raw.Amount, Fee: raw.Fee,
+ Currency: raw.Currency, Created: time.Unix(*raw.Created, 0).UTC(), Source: raw.Source}
+ return nil
+}
+
+// expandedTxn is an expanded balance transaction field: nil when null, an
+// error when Stripe sent a bare id although the read asked to expand it.
+func expandedTxn(v idOrExpanded) (*balanceTxn, error) {
+ if v.Object == nil {
+ if v.ID != "" {
+ return nil, errors.New("billingstripe: balance transaction not expanded")
+ }
+ return nil, nil
+ }
+ var t balanceTxn
+ if err := json.Unmarshal(v.Object, &t); err != nil {
+ return nil, err
+ }
+ return &t, nil
+}
+
+// chargeInvoice is what a charge's invoice says about the payment.
+type chargeInvoice struct {
+ BillingReason string
+ Tax int64
+ Subscription string
+}
+
+// stripeRefund is a refund and the movements it made.
+type stripeRefund struct {
+ ID string
+ Amount int64
+ Charge string
+ Currency string
+ Status string
+ Txn *balanceTxn // the debit, nil until there is one
+ FailureTxn *balanceTxn // the reversal of a failed refund
+}
+
+func (r *stripeRefund) UnmarshalJSON(b []byte) error {
+ var raw struct {
+ ID *string `json:"id"`
+ Amount int64 `json:"amount"`
+ Charge idOrExpanded `json:"charge"`
+ Currency string `json:"currency"`
+ Status string `json:"status"`
+ BalanceTransaction idOrExpanded `json:"balance_transaction"`
+ FailureBalanceTransaction idOrExpanded `json:"failure_balance_transaction"`
+ }
+ if err := json.Unmarshal(b, &raw); err != nil {
+ return err
+ }
+ if raw.ID == nil || !validID(*raw.ID) {
+ return errors.New("billingstripe: refund missing id")
+ }
+ txn, err := expandedTxn(raw.BalanceTransaction)
+ if err != nil {
+ return err
+ }
+ failure, err := expandedTxn(raw.FailureBalanceTransaction)
+ if err != nil {
+ return err
+ }
+ *r = stripeRefund{ID: *raw.ID, Amount: raw.Amount, Charge: raw.Charge.ID, Currency: raw.Currency,
+ Status: raw.Status, Txn: txn, FailureTxn: failure}
+ return nil
+}
+
+// stripeCharge is a charge read with its balance transaction, invoice and
+// refunds expanded.
+type stripeCharge struct {
+ ID string
+ LiveMode bool
+ Amount int64 // as captured
+ Currency string
+ Captured bool
+ Customer string
+ PaymentIntent string
+ Txn *balanceTxn
+ Invoice *chargeInvoice
+ Refunds []stripeRefund
+ RefundsMore bool
+}
+
+// UnmarshalJSON decodes a charge strictly: a null object, or one missing
+// "id" or "livemode", cannot pass (see Subscription.UnmarshalJSON).
+func (c *stripeCharge) UnmarshalJSON(b []byte) error {
+ var raw struct {
+ ID *string `json:"id"`
+ LiveMode *bool `json:"livemode"`
+ Amount int64 `json:"amount"`
+ AmountCaptured *int64 `json:"amount_captured"`
+ Currency string `json:"currency"`
+ Captured bool `json:"captured"`
+ Customer idOrExpanded `json:"customer"`
+ PaymentIntent idOrExpanded `json:"payment_intent"`
+ BalanceTransaction idOrExpanded `json:"balance_transaction"`
+ Invoice idOrExpanded `json:"invoice"`
+ Refunds *struct {
+ Data []stripeRefund `json:"data"`
+ HasMore bool `json:"has_more"`
+ } `json:"refunds"`
+ }
+ if err := json.Unmarshal(b, &raw); err != nil {
+ return err
+ }
+ if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil {
+ return errors.New("billingstripe: charge response missing id or livemode")
+ }
+ if !validID(*raw.ID) {
+ return errors.New("billingstripe: charge id has unexpected shape")
+ }
+ txn, err := expandedTxn(raw.BalanceTransaction)
+ if err != nil {
+ return err
+ }
+ *c = stripeCharge{
+ ID: *raw.ID, LiveMode: *raw.LiveMode, Amount: raw.Amount, Currency: raw.Currency, Captured: raw.Captured,
+ Customer: raw.Customer.ID, PaymentIntent: raw.PaymentIntent.ID, Txn: txn,
+ }
+ if raw.AmountCaptured != nil {
+ c.Amount = *raw.AmountCaptured
+ }
+ if raw.Invoice.Object == nil && raw.Invoice.ID != "" {
+ return errors.New("billingstripe: charge invoice not expanded")
+ }
+ if raw.Invoice.Object != nil {
+ var inv struct {
+ BillingReason string `json:"billing_reason"`
+ Tax *int64 `json:"tax"`
+ Subscription idOrExpanded `json:"subscription"`
+ }
+ if err := json.Unmarshal(raw.Invoice.Object, &inv); err != nil {
+ return err
+ }
+ c.Invoice = &chargeInvoice{BillingReason: inv.BillingReason, Subscription: inv.Subscription.ID}
+ if inv.Tax != nil {
+ c.Invoice.Tax = *inv.Tax
+ }
+ }
+ if raw.Refunds != nil {
+ c.Refunds, c.RefundsMore = raw.Refunds.Data, raw.Refunds.HasMore
+ }
+ return nil
+}
+
+// movementKindOf maps a balance transaction type onto the neutral kind.
+func movementKindOf(typ string) billing.MovementKind {
+ switch typ {
+ case "charge", "payment":
+ return billing.MovementCharge
+ case "refund", "payment_refund":
+ return billing.MovementRefund
+ case "refund_failure", "payment_failure_refund":
+ return billing.MovementRefundFailure
+ case "stripe_fee", "tax_fee":
+ return billing.MovementFee
+ default:
+ return billing.MovementOther
+ }
+}
+
+// unixCeil is t in whole seconds, rounded up: the first second at or after
+// t. Stripe's created times are whole seconds, so created[gte]=unixCeil(from)
+// and created[lt]=unixCeil(to) is exactly [from, to).
+func unixCeil(t time.Time) int64 {
+ s := t.Unix()
+ if t.Nanosecond() > 0 {
+ s++
+ }
+ return s
+}
+
+// MoneyMovements reads every balance movement created in [from, to),
+// oldest first. Exhaustive: billing.ErrIncomplete past MaxListPages pages.
+func (p *Provider) MoneyMovements(ctx context.Context, from, to time.Time) ([]billing.Movement, error) {
+ q := url.Values{
+ "created[gte]": {strconv.FormatInt(unixCeil(from), 10)},
+ "created[lt]": {strconv.FormatInt(unixCeil(to), 10)},
+ "expand[]": {"data.source"},
+ }
+ out := []billing.Movement{}
+ err := p.client.listAll(ctx, "/v1/balance_transactions", q, func(raw json.RawMessage) (string, error) {
+ var t balanceTxn
+ if err := json.Unmarshal(raw, &t); err != nil {
+ return "", err
+ }
+ m := billing.Movement{
+ ID: t.ID, Kind: movementKindOf(t.Type), Type: t.Type, Source: t.Source.ID,
+ Amount: t.Amount, Fee: t.Fee, Currency: t.Currency, At: t.Created,
+ }
+ switch m.Kind {
+ case billing.MovementCharge:
+ m.Charge = t.Source.ID
+ case billing.MovementRefund, billing.MovementRefundFailure:
+ if t.Source.Object != nil {
+ var r struct {
+ Charge idOrExpanded `json:"charge"`
+ }
+ if err := json.Unmarshal(t.Source.Object, &r); err != nil {
+ return "", err
+ }
+ m.Charge = r.Charge.ID
+ }
+ }
+ out = append(out, m)
+ return t.ID, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ // Stripe lists newest first.
+ slices.SortStableFunc(out, func(a, b billing.Movement) int {
+ if c := a.At.Compare(b.At); c != 0 {
+ return c
+ }
+ return strings.Compare(a.ID, b.ID)
+ })
+ return out, nil
+}
+
+// chargeKindOf is what a charge paid for, from its invoice's billing
+// reason. Only a subscription's first and renewal invoices are its
+// payments; a change's proration and anything else is once-off.
+func chargeKindOf(inv *chargeInvoice) (billing.PaymentKind, string) {
+ if inv == nil {
+ return billing.PaymentOnceOff, billing.ReasonOther
+ }
+ switch inv.BillingReason {
+ case "subscription_create":
+ return billing.PaymentSubscription, billing.ReasonFirst
+ case "subscription_cycle":
+ return billing.PaymentSubscription, billing.ReasonRenewal
+ case "subscription_update":
+ return billing.PaymentOnceOff, billing.ReasonChange
+ default:
+ return billing.PaymentOnceOff, billing.ReasonOther
+ }
+}
+
+// ChargePayments reads a charge and its refunds: one Payment per balance
+// movement they made. ErrNotFound when Stripe has no such charge; Captured
+// false, and nothing else, when no money moved.
+func (p *Provider) ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error) {
+ if !validID(charge) {
+ return billing.ChargeRecord{}, &Error{Code: CodeInvalidID}
+ }
+ q := url.Values{"expand[]": {
+ "balance_transaction", "invoice", "refunds",
+ "refunds.data.balance_transaction", "refunds.data.failure_balance_transaction",
+ }}
+ var ch stripeCharge
+ err := p.client.do(ctx, http.MethodGet, "/v1/charges/"+charge, q, "", &ch)
+ if notFound(err) {
+ return billing.ChargeRecord{}, billing.ErrNotFound
+ }
+ if err != nil {
+ return billing.ChargeRecord{}, err
+ }
+ if ch.ID != charge {
+ return billing.ChargeRecord{}, &Error{Code: CodeDecodeError}
+ }
+ if !ch.Captured || ch.Txn == nil {
+ return billing.ChargeRecord{}, nil
+ }
+ refunds := ch.Refunds
+ if ch.RefundsMore {
+ refunds = nil
+ rq := url.Values{"charge": {charge}, "expand[]": {"data.balance_transaction", "data.failure_balance_transaction"}}
+ err := p.client.listAll(ctx, "/v1/refunds", rq, func(raw json.RawMessage) (string, error) {
+ var r stripeRefund
+ if err := json.Unmarshal(raw, &r); err != nil {
+ return "", err
+ }
+ if r.Charge != charge {
+ return "", errors.New("billingstripe: a refund of another charge")
+ }
+ refunds = append(refunds, r)
+ return r.ID, nil
+ })
+ if err != nil {
+ return billing.ChargeRecord{}, err
+ }
+ }
+
+ kind, reason := chargeKindOf(ch.Invoice)
+ c := billing.Payment{
+ Movement: ch.Txn.ID, Source: ch.ID, Kind: kind, Reason: reason,
+ Customer: ch.Customer, PaymentIntent: ch.PaymentIntent, Charge: ch.ID,
+ Amount: ch.Amount, Currency: ch.Currency,
+ Settled: ch.Txn.Amount, Fee: ch.Txn.Fee, SettledCurrency: ch.Txn.Currency,
+ At: ch.Txn.Created, LiveMode: ch.LiveMode,
+ }
+ if ch.Invoice != nil {
+ c.Tax, c.Subscription = ch.Invoice.Tax, ch.Invoice.Subscription
+ }
+ c.SettledTax = billing.SettledShare(c.Tax, c.Amount, c.Settled)
+ rec := billing.ChargeRecord{Captured: true, Charge: c}
+
+ for _, r := range refunds {
+ if r.Txn == nil && r.FailureTxn == nil {
+ continue // pending with no movement yet, or canceled
+ }
+ currency := r.Currency
+ if currency == "" {
+ currency = ch.Currency
+ }
+ amount := -r.Amount
+ tax := billing.SettledShare(c.Tax, c.Amount, amount)
+ base := billing.Payment{
+ Source: r.ID, Kind: billing.PaymentRefund, Reason: billing.ReasonOther,
+ Customer: c.Customer, Subscription: c.Subscription, PaymentIntent: c.PaymentIntent, Charge: ch.ID,
+ Currency: currency, LiveMode: ch.LiveMode,
+ }
+ if r.Txn != nil {
+ d := base
+ d.Movement, d.Amount, d.Tax = r.Txn.ID, amount, tax
+ d.Settled, d.Fee, d.SettledCurrency, d.At = r.Txn.Amount, r.Txn.Fee, r.Txn.Currency, r.Txn.Created
+ d.SettledTax = billing.SettledShare(d.Tax, d.Amount, d.Settled)
+ rec.Refunds = append(rec.Refunds, d)
+ }
+ if r.FailureTxn != nil {
+ v := base
+ v.Reason = billing.ReasonReversed
+ v.Movement, v.Amount, v.Tax = r.FailureTxn.ID, -amount, -tax
+ v.Settled, v.Fee, v.SettledCurrency, v.At = r.FailureTxn.Amount, r.FailureTxn.Fee, r.FailureTxn.Currency, r.FailureTxn.Created
+ v.SettledTax = billing.SettledShare(v.Tax, v.Amount, v.Settled)
+ rec.Refunds = append(rec.Refunds, v)
+ }
+ }
+ return rec, nil
+}
+
+// AccountCreated is when the provider account was opened: no money moved
+// before it.
+func (p *Provider) AccountCreated(ctx context.Context) (time.Time, error) {
+ id, created, err := p.client.merchantAccount(ctx)
+ if err != nil {
+ return time.Time{}, err
+ }
+ if id != p.account || created.IsZero() {
+ return time.Time{}, &Error{Code: CodeDecodeError}
+ }
+ return created, nil
+}
diff --git a/internal/billingstripe/money_test.go b/internal/billingstripe/money_test.go
new file mode 100644
index 000000000..8e86f5359
--- /dev/null
+++ b/internal/billingstripe/money_test.go
@@ -0,0 +1,439 @@
+package billingstripe
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+var moneyT0 = time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
+
+func txnJSON(id, typ string, amount, fee int64, currency string, at time.Time, source string) string {
+ return fmt.Sprintf(`{"id":%q,"object":"balance_transaction","type":%q,"amount":%d,"fee":%d,"net":%d,"currency":%q,"created":%d,"source":%s}`,
+ id, typ, amount, fee, amount-fee, currency, at.Unix(), source)
+}
+
+func TestMoneyMovementsMapsTypes(t *testing.T) {
+ refund := `{"id":"re_1","object":"refund","amount":2904,"charge":"ch_2","currency":"eur","status":"succeeded"}`
+ failed := `{"id":"re_2","object":"refund","amount":1000,"charge":"ch_1","currency":"eur","status":"failed"}`
+ // Stripe lists newest first.
+ page := []string{
+ txnJSON("txn_6", "payout", -5000, 0, "eur", moneyT0.Add(6*time.Hour), `"po_1"`),
+ txnJSON("txn_5", "stripe_fee", -45, 0, "eur", moneyT0.Add(5*time.Hour), `null`),
+ txnJSON("txn_4", "refund_failure", 1000, 0, "eur", moneyT0.Add(4*time.Hour), failed),
+ txnJSON("txn_3", "refund", -2904, 0, "eur", moneyT0.Add(3*time.Hour), refund),
+ txnJSON("txn_2", "payment", 2904, 60, "eur", moneyT0.Add(2*time.Hour), `{"id":"py_2","object":"charge"}`),
+ txnJSON("txn_1", "charge", 2610, 106, "eur", moneyT0.Add(1*time.Hour), `{"id":"ch_1","object":"charge"}`),
+ }
+ var got url.Values
+ var path string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got, path = r.URL.Query(), r.URL.Path
+ if r.Method != http.MethodGet {
+ t.Errorf("method %s", r.Method)
+ }
+ fmt.Fprintf(w, `{"object":"list","data":[%s],"has_more":false}`, strings.Join(page, ","))
+ }))
+ defer srv.Close()
+ from, to := moneyT0, moneyT0.Add(24*time.Hour)
+ ms, err := prepProvider(t, srv.URL, nil).MoneyMovements(context.Background(), from, to)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path != "/v1/balance_transactions" || got.Get("created[gte]") != fmt.Sprint(from.Unix()) ||
+ got.Get("created[lt]") != fmt.Sprint(to.Unix()) || !slices.Equal(got["expand[]"], []string{"data.source"}) {
+ t.Errorf("request %s %v", path, got)
+ }
+ want := []billing.Movement{
+ {ID: "txn_1", Kind: billing.MovementCharge, Type: "charge", Source: "ch_1", Charge: "ch_1", Amount: 2610, Fee: 106, Currency: "eur", At: moneyT0.Add(1 * time.Hour)},
+ {ID: "txn_2", Kind: billing.MovementCharge, Type: "payment", Source: "py_2", Charge: "py_2", Amount: 2904, Fee: 60, Currency: "eur", At: moneyT0.Add(2 * time.Hour)},
+ {ID: "txn_3", Kind: billing.MovementRefund, Type: "refund", Source: "re_1", Charge: "ch_2", Amount: -2904, Currency: "eur", At: moneyT0.Add(3 * time.Hour)},
+ {ID: "txn_4", Kind: billing.MovementRefundFailure, Type: "refund_failure", Source: "re_2", Charge: "ch_1", Amount: 1000, Currency: "eur", At: moneyT0.Add(4 * time.Hour)},
+ {ID: "txn_5", Kind: billing.MovementFee, Type: "stripe_fee", Amount: -45, Currency: "eur", At: moneyT0.Add(5 * time.Hour)},
+ {ID: "txn_6", Kind: billing.MovementOther, Type: "payout", Source: "po_1", Amount: -5000, Currency: "eur", At: moneyT0.Add(6 * time.Hour)},
+ }
+ if len(ms) != len(want) {
+ t.Fatalf("got %d movements: %+v", len(ms), ms)
+ }
+ for i := range want {
+ if ms[i] != want[i] {
+ t.Errorf("movement %d:\n got %+v\nwant %+v", i, ms[i], want[i])
+ }
+ }
+}
+
+func TestMoneyMovementKinds(t *testing.T) {
+ for typ, want := range map[string]billing.MovementKind{
+ "charge": billing.MovementCharge, "payment": billing.MovementCharge,
+ "refund": billing.MovementRefund, "payment_refund": billing.MovementRefund,
+ "refund_failure": billing.MovementRefundFailure, "payment_failure_refund": billing.MovementRefundFailure,
+ "stripe_fee": billing.MovementFee, "tax_fee": billing.MovementFee,
+ "payout": billing.MovementOther, "adjustment": billing.MovementOther, "": billing.MovementOther,
+ } {
+ if got := movementKindOf(typ); got != want {
+ t.Errorf("%q: %s, want %s", typ, got, want)
+ }
+ }
+}
+
+func TestMoneyMovementsIncomplete(t *testing.T) {
+ ls := &listServer{t: t}
+ for i := 0; i < billing.MaxListPages*100+1; i++ {
+ id := fmt.Sprintf("txn_%05d", i)
+ ls.ids = append(ls.ids, id)
+ ls.objects = append(ls.objects, txnJSON(id, "charge", 100, 0, "eur", moneyT0, `{"id":"ch_1","object":"charge"}`))
+ }
+ srv := httptest.NewServer(ls)
+ defer srv.Close()
+ ms, err := prepProvider(t, srv.URL, nil).MoneyMovements(context.Background(), moneyT0, moneyT0.Add(time.Hour))
+ if !errors.Is(err, billing.ErrIncomplete) || ms != nil {
+ t.Fatalf("ms = %d, err = %v; want ErrIncomplete", len(ms), err)
+ }
+ if ls.requests() != billing.MaxListPages {
+ t.Errorf("%d requests, want %d", ls.requests(), billing.MaxListPages)
+ }
+}
+
+func TestMoneyMovementsRefusesMalformed(t *testing.T) {
+ for name, obj := range map[string]string{
+ "no id": `{"object":"balance_transaction","type":"charge","amount":1,"currency":"eur","created":1}`,
+ "bad id": `{"id":"txn 1","type":"charge","amount":1,"currency":"eur","created":1}`,
+ "no created": `{"id":"txn_1","type":"charge","amount":1,"currency":"eur"}`,
+ "null": `null`,
+ } {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"data":[%s],"has_more":false}`, obj)
+ }))
+ if _, err := prepProvider(t, srv.URL, nil).MoneyMovements(context.Background(), moneyT0, moneyT0.Add(time.Hour)); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ srv.Close()
+ }
+}
+
+// chargeServer serves one charge and, optionally, its refunds list.
+type chargeServer struct {
+ t *testing.T
+ mu sync.Mutex
+ charge string // JSON, served at /v1/charges/ch_1
+ refunds *listServer
+ queries map[string][]url.Values
+}
+
+func (s *chargeServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ s.mu.Lock()
+ if s.queries == nil {
+ s.queries = map[string][]url.Values{}
+ }
+ s.queries[r.URL.Path] = append(s.queries[r.URL.Path], r.URL.Query())
+ s.mu.Unlock()
+ if r.Method != http.MethodGet {
+ s.t.Errorf("method %s", r.Method)
+ }
+ switch {
+ case r.URL.Path == "/v1/charges/ch_1" && s.charge != "":
+ fmt.Fprint(w, s.charge)
+ case r.URL.Path == "/v1/refunds" && s.refunds != nil:
+ s.refunds.ServeHTTP(w, r)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ fmt.Fprint(w, `{"error":{"type":"invalid_request_error","code":"resource_missing"}}`)
+ }
+}
+
+type chargeFixture struct {
+ currency string
+ amount int64
+ captured bool
+ txn string // "" null
+ invoice string // "" null
+ refunds []string
+ refundsHasMore bool
+}
+
+func (f chargeFixture) json() string {
+ txn, inv := f.txn, f.invoice
+ if txn == "" {
+ txn = "null"
+ }
+ if inv == "" {
+ inv = "null"
+ }
+ return fmt.Sprintf(`{"id":"ch_1","object":"charge","livemode":false,"amount":%d,"amount_captured":%d,"currency":%q,"captured":%v,`+
+ `"customer":"cus_1","payment_intent":"pi_1","created":%d,"balance_transaction":%s,"invoice":%s,`+
+ `"refunds":{"object":"list","data":[%s],"has_more":%v}}`,
+ f.amount, f.amount, f.currency, f.captured, moneyT0.Unix(), txn, inv, strings.Join(f.refunds, ","), f.refundsHasMore)
+}
+
+func invoiceJSON(reason string, tax int64, sub string) string {
+ return fmt.Sprintf(`{"id":"in_1","object":"invoice","billing_reason":%q,"tax":%d,"subscription":%q}`, reason, tax, sub)
+}
+
+func refundJSON(id string, amount int64, status, txn, failure string) string {
+ if txn == "" {
+ txn = "null"
+ }
+ if failure == "" {
+ failure = "null"
+ }
+ return fmt.Sprintf(`{"id":%q,"object":"refund","amount":%d,"charge":"ch_1","currency":"eur","status":%q,"balance_transaction":%s,"failure_balance_transaction":%s}`,
+ id, amount, status, txn, failure)
+}
+
+func chargePayments(t *testing.T, cs *chargeServer) (billing.ChargeRecord, error) {
+ t.Helper()
+ srv := httptest.NewServer(cs)
+ t.Cleanup(srv.Close)
+ return prepProvider(t, srv.URL, nil).ChargePayments(context.Background(), "ch_1")
+}
+
+func TestChargePaymentsSubscriptionFirst(t *testing.T) {
+ cs := &chargeServer{t: t, charge: chargeFixture{
+ currency: "usd", amount: 2800, captured: true,
+ txn: txnJSON("txn_ch", "charge", 2610, 106, "eur", moneyT0.Add(time.Minute), `"ch_1"`),
+ invoice: invoiceJSON("subscription_create", 0, "sub_1"),
+ }.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := billing.Payment{
+ Movement: "txn_ch", Source: "ch_1", Kind: billing.PaymentSubscription, Reason: billing.ReasonFirst,
+ Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_1", Charge: "ch_1",
+ Amount: 2800, Tax: 0, Currency: "usd", Settled: 2610, Fee: 106, SettledTax: 0, SettledCurrency: "eur",
+ At: moneyT0.Add(time.Minute),
+ }
+ if !rec.Captured || rec.Charge != want || len(rec.Refunds) != 0 {
+ t.Errorf("record %+v\nwant charge %+v", rec, want)
+ }
+ q := cs.queries["/v1/charges/ch_1"][0]
+ wantExpand := []string{"balance_transaction", "invoice", "refunds", "refunds.data.balance_transaction", "refunds.data.failure_balance_transaction"}
+ if got := slices.Sorted(slices.Values(q["expand[]"])); !slices.Equal(got, wantExpand) {
+ t.Errorf("expand %v", got)
+ }
+
+ cs.charge = chargeFixture{
+ currency: "usd", amount: 2800, captured: true,
+ txn: txnJSON("txn_ch", "charge", 2610, 106, "eur", moneyT0, `"ch_1"`),
+ invoice: invoiceJSON("subscription_cycle", 0, "sub_1"),
+ }.json()
+ rec, err = chargePayments(t, cs)
+ if err != nil || rec.Charge.Kind != billing.PaymentSubscription || rec.Charge.Reason != billing.ReasonRenewal {
+ t.Errorf("cycle: %+v %v", rec.Charge, err)
+ }
+}
+
+func TestChargePaymentsTaxAndRefund(t *testing.T) {
+ cs := &chargeServer{t: t, charge: chargeFixture{
+ currency: "eur", amount: 2904, captured: true,
+ txn: txnJSON("txn_ch", "charge", 2904, 60, "eur", moneyT0, `"ch_1"`),
+ invoice: invoiceJSON("subscription_create", 504, "sub_1"),
+ refunds: []string{refundJSON("re_1", 2904, "succeeded", txnJSON("txn_re", "refund", -2904, 0, "eur", moneyT0.Add(time.Hour), `"re_1"`), "")},
+ }.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec.Charge.Tax != 504 || rec.Charge.SettledTax != 504 {
+ t.Errorf("charge %+v", rec.Charge)
+ }
+ if len(rec.Refunds) != 1 {
+ t.Fatalf("refunds %+v", rec.Refunds)
+ }
+ r := rec.Refunds[0]
+ want := billing.Payment{
+ Movement: "txn_re", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonOther,
+ Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_1", Charge: "ch_1",
+ Amount: -2904, Tax: -504, Currency: "eur", Settled: -2904, SettledTax: -504, SettledCurrency: "eur",
+ At: moneyT0.Add(time.Hour),
+ }
+ if r != want {
+ t.Errorf("refund\n got %+v\nwant %+v", r, want)
+ }
+ if net := (rec.Charge.Settled - rec.Charge.SettledTax) + (r.Settled - r.SettledTax); net != 0 {
+ t.Errorf("charge plus full refund nets %d revenue", net)
+ }
+}
+
+func TestChargePaymentsFailedRefund(t *testing.T) {
+ cs := &chargeServer{t: t, charge: chargeFixture{
+ currency: "eur", amount: 2904, captured: true,
+ txn: txnJSON("txn_ch", "charge", 2904, 60, "eur", moneyT0, `"ch_1"`),
+ invoice: invoiceJSON("subscription_cycle", 504, "sub_1"),
+ refunds: []string{refundJSON("re_1", 2904, "failed",
+ txnJSON("txn_re", "refund", -2904, 0, "eur", moneyT0.Add(time.Hour), `"re_1"`),
+ txnJSON("txn_rf", "refund_failure", 2904, 0, "eur", moneyT0.Add(2*time.Hour), `"re_1"`))},
+ }.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rec.Refunds) != 2 {
+ t.Fatalf("refunds %+v", rec.Refunds)
+ }
+ d, v := rec.Refunds[0], rec.Refunds[1]
+ if d.Movement != "txn_re" || d.Kind != billing.PaymentRefund || d.Reason == billing.ReasonReversed || d.Amount != -2904 || d.Tax != -504 || d.SettledTax != -504 {
+ t.Errorf("debit %+v", d)
+ }
+ if v.Movement != "txn_rf" || v.Source != "re_1" || v.Kind != billing.PaymentRefund || v.Reason != billing.ReasonReversed ||
+ v.Amount != 2904 || v.Tax != 504 || v.Settled != 2904 || v.SettledTax != 504 || v.At != moneyT0.Add(2*time.Hour) || v.Charge != "ch_1" {
+ t.Errorf("reversal %+v", v)
+ }
+ if d.Amount+v.Amount != 0 || d.Tax+v.Tax != 0 || d.Settled+v.Settled != 0 || d.SettledTax+v.SettledTax != 0 {
+ t.Errorf("debit and reversal do not cancel: %+v %+v", d, v)
+ }
+
+ // A refund with no movement yet, or canceled before one, gives nothing.
+ cs.charge = chargeFixture{
+ currency: "eur", amount: 2904, captured: true,
+ txn: txnJSON("txn_ch", "charge", 2904, 60, "eur", moneyT0, `"ch_1"`),
+ refunds: []string{refundJSON("re_2", 100, "pending", "", ""), refundJSON("re_3", 100, "canceled", "", "")},
+ }.json()
+ rec, err = chargePayments(t, cs)
+ if err != nil || len(rec.Refunds) != 0 {
+ t.Errorf("movementless refunds: %+v %v", rec.Refunds, err)
+ }
+}
+
+func TestChargePaymentsUpdateIsOnceOff(t *testing.T) {
+ cs := &chargeServer{t: t, charge: chargeFixture{
+ currency: "eur", amount: 1200, captured: true,
+ txn: txnJSON("txn_ch", "charge", 1200, 30, "eur", moneyT0, `"ch_1"`),
+ invoice: invoiceJSON("subscription_update", 200, "sub_1"),
+ }.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil || rec.Charge.Kind != billing.PaymentOnceOff || rec.Charge.Reason != billing.ReasonChange ||
+ rec.Charge.Tax != 200 || rec.Charge.Subscription != "sub_1" {
+ t.Errorf("update: %+v %v", rec.Charge, err)
+ }
+
+ cs.charge = chargeFixture{
+ currency: "eur", amount: 1200, captured: true,
+ txn: txnJSON("txn_ch", "charge", 1200, 30, "eur", moneyT0, `"ch_1"`),
+ invoice: invoiceJSON("manual", 200, ""),
+ }.json()
+ rec, err = chargePayments(t, cs)
+ if err != nil || rec.Charge.Kind != billing.PaymentOnceOff || rec.Charge.Reason != billing.ReasonOther {
+ t.Errorf("manual invoice: %+v %v", rec.Charge, err)
+ }
+
+ cs.charge = chargeFixture{
+ currency: "eur", amount: 1200, captured: true,
+ txn: txnJSON("txn_ch", "charge", 1200, 30, "eur", moneyT0, `"ch_1"`),
+ }.json()
+ rec, err = chargePayments(t, cs)
+ if err != nil || rec.Charge.Kind != billing.PaymentOnceOff || rec.Charge.Reason != billing.ReasonOther ||
+ rec.Charge.Tax != 0 || rec.Charge.SettledTax != 0 || rec.Charge.Subscription != "" {
+ t.Errorf("no invoice: %+v %v", rec.Charge, err)
+ }
+}
+
+func TestChargePaymentsUncaptured(t *testing.T) {
+ cs := &chargeServer{t: t, charge: chargeFixture{currency: "eur", amount: 1200, captured: false}.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil || rec.Captured || rec.Charge != (billing.Payment{}) || len(rec.Refunds) != 0 {
+ t.Errorf("uncaptured: %+v %v", rec, err)
+ }
+ // Captured but with no balance transaction: no money moved.
+ cs.charge = chargeFixture{currency: "eur", amount: 1200, captured: true}.json()
+ if rec, err := chargePayments(t, cs); err != nil || rec.Captured {
+ t.Errorf("no movement: %+v %v", rec, err)
+ }
+ cs.charge = ""
+ if _, err := chargePayments(t, cs); !errors.Is(err, billing.ErrNotFound) {
+ t.Errorf("404: %v", err)
+ }
+ if _, err := prepProvider(t, "http://127.0.0.1:1", nil).ChargePayments(context.Background(), "../ch_1"); err == nil || errors.Is(err, billing.ErrNotFound) {
+ t.Errorf("bad id: %v", err)
+ }
+}
+
+func TestChargePaymentsRefusesMalformed(t *testing.T) {
+ for name, body := range map[string]string{
+ "null": `null`,
+ "no livemode": `{"id":"ch_1","captured":true}`,
+ "other charge": strings.Replace(chargeFixture{currency: "eur", amount: 1, captured: true, txn: txnJSON("txn_ch", "charge", 1, 0, "eur", moneyT0, `"ch_1"`)}.json(), `"id":"ch_1"`, `"id":"ch_2"`, 1),
+ "txn unexpanded": chargeFixture{currency: "eur", amount: 1, captured: true, txn: `"txn_ch"`}.json(),
+ "invoice unexpanded": chargeFixture{currency: "eur", amount: 1, captured: true, txn: txnJSON("txn_ch", "charge", 1, 0, "eur", moneyT0, `"ch_1"`), invoice: `"in_1"`}.json(),
+ } {
+ cs := &chargeServer{t: t, charge: body}
+ if _, err := chargePayments(t, cs); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+func TestChargePaymentsRefundPages(t *testing.T) {
+ ls := &listServer{t: t}
+ for i := 0; i < 150; i++ {
+ id := fmt.Sprintf("re_%04d", i)
+ ls.ids = append(ls.ids, id)
+ ls.objects = append(ls.objects, refundJSON(id, 10, "succeeded",
+ txnJSON(fmt.Sprintf("txn_%04d", i), "refund", -10, 0, "eur", moneyT0.Add(time.Hour), fmt.Sprintf("%q", id)), ""))
+ }
+ // The charge carries the first refunds only.
+ cs := &chargeServer{t: t, refunds: ls, charge: chargeFixture{
+ currency: "eur", amount: 5000, captured: true,
+ txn: txnJSON("txn_ch", "charge", 5000, 100, "eur", moneyT0, `"ch_1"`),
+ refunds: ls.objects[:10],
+ refundsHasMore: true,
+ }.json()}
+ rec, err := chargePayments(t, cs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rec.Refunds) != 150 {
+ t.Fatalf("%d refunds, want 150", len(rec.Refunds))
+ }
+ seen := map[string]bool{}
+ for _, r := range rec.Refunds {
+ if seen[r.Movement] {
+ t.Errorf("movement %s twice", r.Movement)
+ }
+ seen[r.Movement] = true
+ }
+ qs := cs.queries["/v1/refunds"]
+ if len(qs) != 2 {
+ t.Fatalf("%d refund list requests, want 2", len(qs))
+ }
+ for _, q := range qs {
+ if q.Get("charge") != "ch_1" || !slices.Equal(slices.Sorted(slices.Values(q["expand[]"])), []string{"data.balance_transaction", "data.failure_balance_transaction"}) {
+ t.Errorf("refund list query %v", q)
+ }
+ }
+}
+
+func TestAccountCreated(t *testing.T) {
+ created := time.Date(2019, 3, 4, 5, 6, 7, 0, time.UTC)
+ for body, ok := range map[string]bool{
+ fmt.Sprintf(`{"id":"acct_1","object":"account","created":%d}`, created.Unix()): true,
+ `{"id":"acct_1","object":"account"}`: false,
+ fmt.Sprintf(`{"id":"acct_2","created":%d}`, created.Unix()): false,
+ `null`: false,
+ } {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/v1/account" {
+ t.Errorf("%s %s", r.Method, r.URL.Path)
+ }
+ fmt.Fprint(w, body)
+ }))
+ at, err := prepProvider(t, srv.URL, nil).AccountCreated(context.Background())
+ srv.Close()
+ if ok && (err != nil || !at.Equal(created)) {
+ t.Errorf("%s: %v %v", body, at, err)
+ }
+ if !ok && err == nil {
+ t.Errorf("%s: accepted (%v)", body, at)
+ }
+ }
+}
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh
index 5fc236c7d..09cf2ab41 100755
--- a/scripts/stripe-setup.sh
+++ b/scripts/stripe-setup.sh
@@ -110,6 +110,9 @@ readonly WEBHOOK_EVENTS=(
customer.subscription.deleted
invoice.paid
invoice.payment_failed
+ charge.succeeded
+ charge.captured
+ charge.refunded
)
readonly WEBHOOK_PATH="/billing/webhook"