Files
commerce/api/billing/schedule.go
89940a839b Stripe is the only processor for new charges, end to end (#42)
* payment: Square first, Stripe wherever Square cannot take the payment

Stripe was held out of every new charge by a default deny set. It is now
the fallback, by one rule: processor.Registry.Fiat walks the priority
order (Square, Stripe, ...) and returns the first processor that can take
the payment — registered, not denied, configured, in the currency, and,
for a processor that reports its reach, in the buyer's country and by the
buyer's method. A processor the caller names is that processor or none,
never a substitute, since a token belongs to the processor that minted
it. SelectProcessor, the hosted checkout and both public configs read
this one rule.

- Square reports its reach (the eight countries, card, Apple Pay, Google
  Pay, Cash App Pay); Stripe reports card, Apple Pay and Google Pay from
  any country. Registry.Cards is Fiat's answer for a card, per currency.
- COMMERCE_DISABLED_PROCESSORS denies nothing by default; the "none"
  sentinel is gone with the default it overrode.
- Stripe keys: the org's own, else the deployment's of the org's kind
  (STRIPE_SECRET_KEY/STRIPE_PUBLISHABLE_KEY live,
  STRIPE_TEST_SECRET_KEY/STRIPE_TEST_PUBLISHABLE_KEY test); a key whose
  prefix names the other kind is dropped.
- The Stripe provider sends an Idempotency-Key (fitted to 255) on money
  moves, and a PaymentIntent that requires 3-D Secure is a failed charge:
  it used to read as Success, which TakePayment would have credited.
- Saved-card charges name Square: the card on file is Square's.
- GET /v1/commerce/org carries cards (per currency, for the caller's
  country) and stripe {publishableKey, environment}; Square and Stripe are
  enabled only where the rule gives them a currency. GET
  /v1/billing/settings carries cards and stripe as well.

stripetest serves Stripe's contract over HTTP (the OpenAPI spec's
parameters, Stripe's fixtures, its documented test cards and idempotency
rules); the provider and TakePayment tests run the real code against it.
The tests that pinned "Stripe never wins" now pin the rule.


Co-authored-by: Hanzo Dev <[email protected]>

* payment: refuse sanctioned buyers, keep Stripe off top-ups, fix hosted-checkout country gate

From the red review of the Stripe fallback:

- Stripe cannot fund a prepaid balance yet: its refunds and disputes reach
  this service only through a webhook receiver that verifies Stripe's
  signature and maps charge.refunded / charge.dispute.* onto a clawback,
  and neither exists, so credit taken through Stripe could be charged back
  and kept. TakePayment refuses a Stripe-processed top-up before Stripe is
  called.
- processor.Sanctioned (CU, IR, KP, SY, RU, BY) is refused by every
  processor in canTake, so Cards and Fiat offer no card form there.
- Hosted checkout no longer gates Square on the buyer's country (Square's
  countries are where a seller can be); only sanctioned buyers are refused.
- Stripe key slots are checked by prefix: a secret key misfiled as the
  publishable key is never published.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: Stripe is the only processor for new charges, end to end

COMMERCE_CHARGE_PROCESSORS (default "stripe", "*" for all) is the one policy for
which processors take a NEW charge; the deny set is every type it does not name.
Another processor comes back by naming it, not by restoring code. Payment
config, the checkout's providers and the card vault all follow it.

Existing customers do not lapse: a card on file is charged by the processor that
vaulted it (Registry.Existing, which ignores the policy), so a subscription
bought with a Square card renews on Square until its owner saves a card with
Stripe. Cards saved now are vaulted with the processor the policy selects.

Stripe, natively:
- Vault is a SetupIntent (verified, off-session consent); the card on file is the
  PaymentMethod it saved, charged off-session for renewals and reloads. One
  customer per subject, found by reference.
- A card that needs 3-D Secure is an ActionRequired answer, not a decline: the
  refusal carries {code, id, clientSecret} for Stripe.js, and a PaymentIntent the
  buyer then authenticated is completed by naming it ("pi_…"): for its own
  amount and account only, and credited once whatever key the request carries.
  Plan purchases and reloads still decline such a card (see the pay change).
- A 4xx from Stripe is an Answer (it said no, nothing moved).
- The gateway key names the attempt's source (top-up) or card (sale), so a
  decline Stripe replays under a key is not replayed at the next card.
- Webhook receiver: Stripe's signature is checked with STRIPE_WEBHOOK_SECRET,
  each event is applied once (the delivery guard), and payment_intent.succeeded,
  refund.created/updated and charge.dispute.* are mapped onto settlement,
  refund clawback and dispute withhold/restore. Test-mode events book as test
  money. Other events are acknowledged and move nothing.
- Hosted checkout applies a coupon on Stripe as a one-time coupon of the quoted
  discount.
- Sanctioned buyers are refused by every processor; hosted checkout no longer
  gates Square on the buyer's country.

Tests run against Stripe's real test mode with Stripe's test cards (top-up,
decline then another card, 3-D Secure, finished intent, refund, dispute and win,
plan purchase and renewal, auto-reload, declining reload) and a Square renewal
under the Stripe-only policy.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: close the red review's blocking findings on Stripe-only

- A finished 3-D Secure intent's guard is COMPLETED after the credit, so it is not
  re-claimed as a crashed attempt after five minutes and credited again.
- A Stripe call that got no answer (dropped connection, timeout) may have
  charged: the attempt's guard, card and coupon use stay held, and the buyer is
  told the payment is unconfirmed, not declined. Only Stripe's own refusal
  releases a guard. Retrying with a re-tokenized card is refused instead of
  charging twice.
- Top-ups through Stripe are in US dollars, the only currency the host credits.
- The treasury sweep of deposits already received uses the registered MPC
  processor, outside the new-charge policy.
- A Stripe-Signature carrying several v1 values (a secret being rolled) is
  admitted when any matches.
- Tests: the intent guard, a lost answer under a live Stripe, and the stale
  checkout tests (which assumed Square under the Stripe-only default).

Co-authored-by: Hanzo Dev <[email protected]>

* payment: finish 3-D Secure for plans, saves and top-ups, and settle abandoned intents

- Pending intents (models/pendingintent): a PaymentIntent that sends a buyer to
  their bank is recorded with its buyer, amount and purpose BEFORE the answer that
  sends them. The intent's webhook credits a wallet's (top-up, reload) whether or
  not the browser comes back, and the browser's own request credits nothing more.
  The reconciler (run with the renewal sweep) settles what no webhook or sale did:
  money taken for a wallet is credited, money taken for a plan whose sale never
  finished is refunded, an intent that never succeeded is closed. No money taken
  waits on an alarm.
- A card being saved is answered with its SetupIntent ("seti_…") and the retry that
  names the finished one saves the card, for that customer only. A plan's first
  period is charged on-session so the bank can ask, answered with its
  PaymentIntent, and the retry that names the finished intent finishes the sale on
  the card already saved, for its own amount and account, once.
- A card's country is read from the card (PaymentMethod card.country) and a
  sanctioned one is refused by the processor itself on every path: top-up, sale,
  saved-card charge and reload.
- A saved card's vault facts (customer, token, fingerprint, country) cannot be
  written by a caller: PATCH and the create-merge leave them alone. An org's own
  Stripe keys are checked by prefix and mode like the deployment's, and hosted
  checkout uses only those.
- hanzo.yml gains the stripe-test-mode gate.

Tests, against Stripe's real test mode: the step recorded for its buyer, a closed
tab credited by the webhook and not again by the browser, the reconciler crediting
and refunding, a card save finished from a SetupIntent, a plan finished from the
buyer's intent (and refused for another buyer's, and for a second plan), the card
country read from Stripe. Stripe's test cards are issued in no sanctioned country,
so the refusal of one is proved by the shared rule, not by a card.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: one claim per intent, and a refunded intent is not money in hand

From the third red review:

- completeIntent refuses a PaymentIntent whose charge was refunded in whole or
  part, or not received in full, and fails closed when the card cannot be read.
  An intent the reconciler refunded no longer reads as redeemable.
- ONE claim (`billing-intent`, system namespace) per intent across the webhook,
  the reconciler, the browser's top-up and a sale: whoever holds it credits, the
  others verify read-only and answer the credit that is there. The reconciler's
  refund takes the claim and completes it, so a refunded intent can never be
  redeemed. A claim is given back when its holder fails to credit.
- A sale is finished only by an intent registered for THIS sale (a plan's, this
  buyer's, this amount); a plan's registered intent cannot be a top-up, and a
  top-up's cannot buy a plan. A saved card's plan purchase may finish from an
  intent too.
- A buyer may have five unfinished bank steps at once; the reconciler does at
  most fifty Stripe calls a sweep and reads orgs with a plain Get.

Tests, against Stripe's real test mode: a refunded intent redeemed as a top-up and
as a sale, one intent one use, the browser then the webhook credits once, and the
cap.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: close pending rows on every path, answer a replay with its receipt, credit only sound charges

From the fourth red review:

- A top-up finished in the browser, a webhook for an intent already accounted for,
  and the reconciler's sweep all close the intent's pending row, so the buyer's
  cap and the reconciler are not held by money already credited. Open lists the
  oldest first.
- A replayed intent answers the credit's own receipt id (the row stamped with the
  charge), or 409 while its holder is mid-credit: never a 200 with no receipt,
  which the host reads as a permanent failure.
- The webhook that finds the intent's claim held by a path still crediting answers
  a retry, so a holder that gives the claim back is not left with nothing to
  credit it.
- The webhook and the reconciler credit only a SOUND charge — captured in full,
  not refunded, not disputed — and completeIntent asks the same (Provider.
  ChargeSound).
- A saved card's plan purchase may name the card beside the finished intent.

Tests against Stripe's real test mode: a finished top-up closes its row and its
replay answers the receipt, a charge refunded before any credit is credited by
neither the webhook nor the reconciler, and a saved card's plan from its intent.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: a webhook never closes a plan's row; the reconciler pages, backs off and alarms; renewals move to Stripe

From the independent red review of f68f03d98:

- CRITICAL: the webhook closed a 3-D Secure SALE's pending row, so an abandoned plan
  purchase was charged with no plan, no refund and no alarm. settleWallet closes
  only a wallet's row; a plan's or an invoice's is closed only by the sale (or the
  payment) finishing, or by the reconciler's refund. TestRed_SaleWebhookClosesRow
  SoReconcilerNeverRefunds.
- The reconciler reads ALL due rows, round-robin across orgs (twenty an org, four
  hundred a sweep), backs a row that errors off (5 minutes doubling to 6 hours),
  closes one that fails twelve sweeps with an alarm naming the money it may hold,
  and cancels at Stripe an intent abandoned for 48 hours.
- A Stripe card saved, or made the default, moves the subscriptions that renew on a
  card of another processor onto it; a card removed hands its renewals to the
  subject's default (Stripe first) card. "Renew on Square until a Stripe card is
  saved" is now both halves.
- A past-due invoice is paid on-session: the buyer's press of "pay" charges with
  the buyer present, so a bank that wants them is answered as the step, the intent
  is recorded for the invoice, and the next press finishes it. The off-session
  renewal still goes past due rather than lapsing.
- charge.refunded is read: the refunds on the charge are listed from Stripe and each
  taken back once by its own id, beside refund.created/updated. StripeWebhookEvents
  pins the endpoint's event list, which universe registers.
- Stripe-only is the default only where Stripe is keyed: with no policy and no
  Stripe key every configured processor keeps taking payments, with an alarm — a
  crash-looping host or a site that takes no payment is worse than the processors it
  did configure.
- Top-ups accept only intents commerce registered for a wallet and for that buyer;
  the webhook's receipt is deduped in the payer's org; the soundness check is never
  skipped and uses the recorded org's keys, and an unsound charge raises an alarm;
  customerIDOf prefers squareCustomerId for Square rows.

Tests, against Stripe's real test mode: the sale webhook leaves the row so the
reconciler refunds, charge.refunded alone claws back once, a flood in one org does
not hold another's good row and backs off and closes, plus the renewal re-pointing
and the policy fallback.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: an invoice's recorded intent is settled from, never charged beside

From the re-review of 33b90066e:

- The off-session collector (the cron's first collection and dunning's retries)
  checks the invoice's recorded intent first. If the buyer finished their bank's
  step it settles the invoice from that payment and charges nothing more; if the
  buyer has not, it leaves the invoice waiting (no second charge); the buyer's own
  press of "pay" is answered the same step again, not a new charge.
- An invoice intent that no longer matches what is owed (a part-payment landed
  since) is finished for what is owed: the excess is refunded after the charge is
  verified, and an intent that took less than is owed is refunded in full and the
  buyer asked again.
- A row that is only waiting on its buyer is not looked at again before its 48
  hours are up; a row whose Stripe amount does not match what was registered backs
  off and closes after the same strikes as any other failure, instead of alarming
  every sweep.
- A card's detach and the renewal re-pointing use the card's owner (the caller's
  subject, or for staff the subject the card is filed under) and refuse an empty
  one, which would have listed every subject's subscriptions.

Tests against Stripe's real test mode: the buyer authenticates and the dunning
retry runs with exactly one charge; the retry leaves a waiting invoice alone and
"pay" answers the step again; the buyer authenticates, a part-payment lands, they
press pay, and it finishes with the excess returned.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: the excess refund of an invoice intent is not a refund of the invoice

The refund commerce makes to return what an invoice intent took beyond what was
owed is tagged (metadata hanzo_excess). The invoice is paid in full, so the
webhook's refund event neither records it against the invoice nor claws back nor
stops the buyer's auto-reload; charge.refunded skips it too. A live test covers it:
invoice paid, 500 excess refunded, Refunded() 0 and the reload still on (it fails
without the tag).

The policy's comments no longer say it "defaults to stripe": production and the
test networks say so explicitly; unset is Stripe alone only where Stripe is keyed.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: the stripe-test-mode gate reads its keys from KMS /deploy

STRIPE_TEST_SECRET_KEY and STRIPE_TEST_PUBLISHABLE_KEY (test mode only) come from KMS
org hanzo, path /deploy, env prod, with the bearer the job's KMS login minted, by the
same routes hanzoai/ci's get uses; both are masked, either missing fails the gate
loudly, and a key that is not test-mode is refused.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: go-unit leaves the Stripe test-mode tests to their own gate

They need Stripe's test keys and fail without them by design.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: the stripe-test-mode script parses

An apostrophe inside the ${VAR:?message} word opened a quote.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode asks the endpoint ci asks, and logs what KMS answered

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode names the identity KMS refuses

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode does not re-vendor plans; builds compile the vendored bytes

Co-authored-by: Hanzo Dev <[email protected]>

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-11-12 17:47:27 -08:00

172 lines
6.5 KiB
Go

package billing
// schedule.go — a card plan that starts when the plan held now runs out.
//
// A plan paid outside checkout (a wire, an invoice raised in the processor's own
// dashboard, a comp) never renews: its next period arrives only when the next
// payment is recorded, and with none it lapses at its end (engine.Over). Nor does a
// plan the balance used to renew: a plan's period is never paid from prepaid money
// (engine.CollectInvoice). Such a subscriber who subscribes by card is not charged
// today for a period already covered. The card is kept on file now, the card plan
// opens SCHEDULED at the held plan's end, and the renewal sweep charges the card
// for its first period at that start, as it charges a trial's first paid period.
// The held plan is set to end there, so the two never overlap and nothing is paid
// twice.
//
// A scheduled row confers nothing before its start: every reader of a plan asks
// for an active or trialing row, and this is neither. Its first charge declining
// leaves it past due, as any renewal's does.
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/hanzoai/commerce/datastore"
"github.com/hanzoai/commerce/log"
"github.com/hanzoai/commerce/models/idempotencykey"
"github.com/hanzoai/commerce/models/organization"
"github.com/hanzoai/commerce/models/paymentmethod"
"github.com/hanzoai/commerce/models/plan"
"github.com/hanzoai/commerce/models/subscription"
"github.com/hanzoai/commerce/models/types/currency"
)
// prepaidSource reports whether a sale's source names prepaid money rather than a
// card. A plan is never bought with it.
func prepaidSource(source string) bool {
switch strings.ToLower(strings.TrimSpace(source)) {
case "balance", "credits", "credit", "prepaid":
return true
}
return false
}
// prepaidRenewed reports whether a row was opened to renew from prepaid money —
// bought from the balance, or with a wallet that keeps no card — which no
// renewal does any more: its next period is charged to a card on file, and it
// holds none.
func prepaidRenewed(s *subscription.Subscription) bool {
return s.Type != subscription.External && strings.EqualFold(strings.TrimSpace(s.DefaultPaymentMethod), "credits")
}
// followed reports whether a card sale for the subject holding s starts when s
// ends rather than today: s is active, will not renew by card, and has not ended.
func followed(s *subscription.Subscription) bool {
return s.Status == subscription.Active && !s.EndCancel &&
(s.Type == subscription.External || prepaidRenewed(s)) &&
s.PeriodEnd.After(time.Now())
}
// scheduledFor is the subject's card plan waiting to start, nil when none waits.
// A read that fails answers nil, as billingSubscription does: the one-plan rule
// is then held by the sale lease and the stable processor key.
func scheduledFor(db *datastore.Datastore, subject string, test bool) *subscription.Subscription {
subs, err := userSubscriptions(db, subject, test)
if err != nil {
return nil
}
for _, s := range subs {
if s.Status == subscription.Scheduled && !strings.EqualFold(strings.TrimSpace(s.ProviderType), "bundle") {
return s
}
}
return nil
}
// schedule shapes a freshly started row to open at start on the card it names:
// nothing is served or charged before then, and the period it owes first begins
// there (engine.IsDue).
func schedule(sub *subscription.Subscription, start time.Time) {
sub.Status = subscription.Scheduled
sub.TrialStart, sub.TrialEnd = time.Time{}, time.Time{}
sub.Start, sub.PeriodStart, sub.PeriodEnd = start, start, start
}
// saleTerms is what a priced sale decided, carried into the act that opens it.
type saleTerms struct {
planID, slug string
qty int
lines []subscription.Line
seats, charge, list int64
cur currency.Type
promoPercent int
promoName string
customer int64
}
// scheduleSale opens the card plan a subject holding a plan that will not renew
// by card bought: SCHEDULED at starts, the held plan's end, on the card pm, with
// nothing charged now. The held plan is set to end at starts; were that to fail,
// the new row is withdrawn and nothing stands but the card on file.
func scheduleSale(ctx context.Context, db *datastore.Datastore, org *organization.Organization, in SubscribeIn, rec *idempotencykey.IdempotencyKey, p *plan.Plan, pm *paymentmethod.PaymentMethod, held *subscription.Subscription, starts time.Time, t saleTerms, unvault, abandon func()) (*saleOutcome, error) {
if !pm.IsDefault {
pm.IsDefault = true
if err := pm.Update(); err != nil {
log.Error("subscribe: failed to mark method %s default (subject=%s): %v", pm.Id(), in.Subject, err)
}
}
sub, err := createSubscription(db, p, &createSubscriptionRequest{
UserId: in.Subject,
PlanId: t.planID,
StoreId: in.StoreID,
DefaultPaymentMethod: pm.Id(),
Quantity: t.qty,
Metadata: map[string]interface{}{"source": "subscribe/card", "follows": held.Id()},
Test: org.TestMode(),
priced: t.lines,
starts: starts,
provider: string(providerOf(pm)),
promoPercent: t.promoPercent,
promoName: t.promoName,
customerCents: t.customer,
})
if err != nil {
unvault()
abandon()
return nil, err
}
// The held plan ends where the card plan starts. A fresh read, since a row read
// by query is not bound to the store.
prior := subscription.New(db)
if err := prior.GetById(held.Id()); err == nil {
prior.EndCancel = true
prior.CanceledAt = time.Now()
err = prior.Update()
}
if err != nil {
withdraw(db, sub)
unvault()
abandon()
return nil, fmt.Errorf("subscribe: subscription %s could not be set to end at %s, so the card plan was not opened: %w",
held.Id(), starts.UTC().Format(time.RFC3339), err)
}
at := starts
sale := &Sale{
SubscriptionID: sub.Id(),
PlanID: t.planID,
Level: in.Level,
Interval: p.Interval,
PaymentMethodID: pm.Id(),
Seats: t.seats,
Category: p.Category,
Currency: string(t.cur),
Status: "ok",
StartsAt: &at,
StartsCents: t.charge,
Follows: held.Id(),
}
if rec != nil {
if body, mErr := json.Marshal(sale); mErr == nil {
_ = idempotencykey.Complete(rec, string(body))
}
}
noticeSale(ctx, saleNote{
Org: org.Name, Email: in.Email, Plan: p, Seats: t.seats, Sale: sale,
ListCents: t.list, PromoName: t.promoName, Test: org.TestMode(),
})
return &saleOutcome{Sale: sale, Sub: sub}, nil
}