Files
commerce/api/billing/payment_core.go
0a8179bd77 Routing rules are policy: currency, country, card, fallback, methods; versioned, validated, simulated (#53)
* routing: every rule about which processor takes which card is policy, versioned, validated and simulated

The SuperAdmin routing policy now carries, as lists (no maps): currencyRules, countryRules
(buyer geography), issuerCountryRules and brandRules (applied only where card metadata is
already known, i.e. a saved card's stored brand and issuing country; a new card is tokenized
inside the processor's own form and nothing is asked of the browser), fallback (the order tried
when the preferred processor is ineligible or down, before any payment exists), per-method
switches (the Payment Element is told to exclude the ones that are off), sticky on/off, and
paypalOn/cryptoOn. Defaults are today's behaviour exactly: no rules, sticky, every method on.

Decision order, fixed and tested: saved card -> merchant eligibility -> the buyer's explicit
method -> admin overrides (currency, buyer country, issuing country, brand) -> sticky
placement -> split weight -> fallback. Decide returns the chain: all seven steps, each applied
or skipped, with why. A saved card or renewal stays on its own processor whatever the policy says.

Every save is validated against what the merchant accounts can take now (a currency rule
needs a processor that takes that currency; a rule naming Square needs a Square location with
card processing; unknown brand, country, currency, method or duplicate rule is refused with a
400) and a refusal changes nothing (recorded as routing.refused). Every save creates a new
immutable version (who, when, diff against the previous, note); the active version is a pointer;
the history is listable and any version restorable as a NEW version after revalidation
against current eligibility. Reset drops one payer's or an org's placements. All audited.
Preview (POST /v1/billing/routing/preview) answers the effective route and the chain for a
sample. The view lists per-currency eligibility so a form offers only valid choices. The policy
is read from the store at each checkout, so a change reaches the next one with no restart.

Routes (platform-only): GET/PUT /v1/billing/routing, POST .../preview, POST .../reset,
GET .../versions, POST .../restore.

Testing: payment/routing and api/billing: each rule changes routing as configured, ineligible
overrides refused at save (8 kinds) with nothing changed and refusals audited, saved card ignores
every rule, the chain is seven steps in order, sticky off re-evaluates and reset clears a
placement (audited), versions immutable/listed/restored as new/refused when ineligible, a
policy change reaches the next checkout, fallback order only before payment and never after a
Square attempt, defaults equal today's. Mutation: removing ValidateRouting fails the refusal test.
Full local suites with Stripe test keys: all pass except models/ossaccrual and models/sbomrecord,
which fail the same way on main.
Risk: high (billing). Rows written before this read as defaults for the new fields (sticky on).
A PUT body that omits the new fields keeps their defaults.
How to revert: git revert this commit; policy rows keep their extra JSON, ignored.


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

* routing: the FX markup and the country-to-currency table are policy; quotes are disclosed; decisions bind at creation

FX markup (fxSpreadBps, default 200, 0 to 1000) and the country-to-local-currency table
(localCurrencies [{country, currency}]; built-in defaults equal the old table; usd switches
local currency off for a country) are policy, versioned and audited like the rest. fx.Quote
takes the spread per call. Save refuses: unknown countries, zero- and three-decimal
currencies, currencies Stripe cannot take, currencies with no rate source, duplicates.

The country table is a DEFAULT, never a restriction. Route and intent accept an explicit
currency (and method): a DE buyer may choose USD; Pix in USD is refused with a 400 saying
what Pix is paid in. The route/intent answer carries quote {amount, currency, usdCents,
rate, markupBps}, calculated before the buyer authorizes; the intent charges exactly
quote.amount (tested against Stripe test mode). The quote is float-safe: 945.0000000000001
is 945, not 946.

Brand and issuer-country rules apply only where card metadata is verified before selection (a
saved card's stored brand and issuing country); for a new card the chain says "not applicable:
card metadata unknown before selection". The browser is not asked for them.

Apple Pay and Google Pay: Stripe cannot exclude a wallet by type on an intent, but takes a
Payment Method Configuration per intent. Commerce keeps its own (copying the default's
preferences, wallets as the admin set them, found again by name), passes its id on the
intent, and methodNotes states each switch's enforceability as data. Proven against Stripe test mode.

Decisions bind at creation: the policy version is stored on the pending intent, the Square
attempt marker and the decision record, and returned on the intent; a topup.intent.opened
billing event carries it. A policy change reaches only NEW attempts (tested mid-checkout).

Testing: new unit tests for spread/table/quote/explicit currency/refusals/versions/diff/restore
and the card-rule chain note; Stripe test-mode tests for the wallet configuration, the disclosed
quote equal to the charge, a mid-checkout policy change moving nothing, and a new checkout taking
the new version. Full local suites with Stripe keys pass except models/ossaccrual and
models/sbomrecord, which fail the same way on main.
Risk: high (billing). Quote shape and PutQuoted/Record/Begin signatures change; rows written
before read as defaults (spread 200, no table entries).
How to revert: git revert this commit.


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

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-11-13 19:42:00 -08:00

588 lines
26 KiB
Go

// Copyright 2014-present Hanzo AI Inc. Licensed under MIT OR Apache-2.0.
package billing
// The CARD MONEY MOVE, as one core with no HTTP in it.
//
// Taking a payment used to exist only as TopupWithToken, a *zip.Ctx handler. That
// shape is not a limitation of the money logic — it is a limitation of where the
// logic was WRITTEN. A handler that reads its inputs off a request can only ever
// be reached by something holding a request, which meant the one operation that
// turns a card into a balance was unreachable from a typed op, and therefore
// invisible to every projection a typed op feeds: the OpenAPI operation, the MCP
// tool an agent calls, the generated SDK method, the CLI command.
//
// So the core moved here and grew an input instead of a request. TakePayment is
// the WHOLE money move — bounds, idempotency, processor selection, charge, ledger
// credit, balance read-back — and it takes values. TopupWithToken is now a
// projection of it that reads those values off a *zip.Ctx, and the typed op in
// the host is another projection that gets them from a decoded body. There is
// exactly ONE charge path underneath both, which is the only reason it is safe
// to have two endpoints: a second implementation of "charge a card and credit the
// ledger" is a second set of bounds to drift, a second idempotency derivation to
// disagree, and eventually a double charge nobody can explain.
//
// WHAT THIS CORE DOES NOT DO, on purpose:
//
// - It does not resolve WHO is paying. Subject arrives already bounded to the
// caller's org (inOrgSubject), because the bound belongs to the identity
// boundary and each endpoint has its own: the browser endpoint reads ?user= behind
// EdgeAuth, the typed endpoint reads the validated tenant off the context. A core
// that resolved identity from its input would let either endpoint hand it a
// subject the caller never proved, which is the whole IDOR class.
// - It does not read the environment for its idempotency key. The key arrives
// as a value; an empty one falls back to the SAME windowKey derivation the
// header-less browser path has always used, so the two endpoints cannot drift
// into disagreeing about what "the same request" means.
// - It does not choose sandbox or production. That is org.TestMode(), exactly
// as before — the caller
// cannot ask for a test charge, because a caller that could would be able to
// mint spendable balance from a sandbox card.
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/hanzoai/commerce/log"
"github.com/hanzoai/commerce/mintauth"
"github.com/hanzoai/commerce/models/idempotencykey"
"github.com/hanzoai/commerce/models/organization"
"github.com/hanzoai/commerce/models/paymentorg"
"github.com/hanzoai/commerce/models/pendingintent"
"github.com/hanzoai/commerce/models/routingpolicy"
"github.com/hanzoai/commerce/models/transaction"
"github.com/hanzoai/commerce/models/types/currency"
"github.com/hanzoai/commerce/payment/processor"
"github.com/hanzoai/commerce/datastore"
)
// TakePaymentIn is the whole input of a card money move. Every field is a VALUE
// the caller resolved — nothing is read from a request, an environment variable
// or a header inside the core.
type TakePaymentIn struct {
// SourceID is the single-use payment token: a Square Web Payments SDK nonce
// from the browser, or a Square sandbox test nonce. It is the ONLY thing that
// stands in for a card here — the PAN never reaches this process. A card the
// subject already SAVED is charged by the other endpoint (Topup → chargeAndCredit),
// never through this core.
SourceID string
// AmountCents is the charge in whole cents. Bounded server-side by
// topupBounds; an out-of-range amount is refused before any money moves.
AmountCents int64
// Currency is the ISO code. Empty means usd.
Currency string
// Subject is the billing key to credit, ALREADY bounded to the caller's own
// org by the endpoint that resolved it (inOrgSubject). The core trusts it and
// cannot re-derive it — see the package note.
Subject string
// Ledger is the org whose books the subject's wallet is in, resolved by the host
// from the caller's identity (commerce cannot derive it); empty is the org the
// card is charged in. The credit is posted there, by this core, and nowhere else.
Ledger string
// IdempotencyKey is the caller's explicit retry key. Empty falls back to the
// windowed derivation over the stable request facts, which is what the
// browser path does when it sends no X-Idempotency-Key.
IdempotencyKey string
// Provider names the explicit fiat payment processor ("square" or "paypal")
// when SourceID belongs to a specific rail (e.g. an approved PayPal Order ID).
// Empty uses the registry's default fiat selection.
Provider string
// Payer is who is paying: the receipt goes to Payer.Email and the processor's
// records name the person, not the billing key.
Payer PayerIn
}
// TakePaymentOut is the settled result. The first three fields are the response
// body TopupWithToken has always sent, with the same names, so the browser
// contract is unchanged and an idempotency replay of a record written before
// this split still decodes.
type TakePaymentOut struct {
// TransactionID is the ledger deposit's id — the receipt for the credit.
TransactionID string `json:"transactionId"`
// There is no balance here. A balance is read from the ledger the spend gate
// reads, after the host has credited it, and only the host knows that ledger:
// the host sets balanceCents on the answer it sends. Reading commerce's own
// per-subject table here reported a different number than /v1/billing/balance.
// Status is "ok" on a settled charge. A failure is a fault, never a status.
Status string `json:"status"`
// ProcessorRef is the PROCESSOR's own reference for the charge (Square's
// payment id). It is the only field here that proves money actually moved at
// the gateway rather than merely in our ledger, which is why it is returned
// rather than only logged.
ProcessorRef string `json:"processorRef,omitempty"`
// Test reports which bucket this credited: true is a sandbox charge crediting
// the TEST balance, false is live money. It is stated rather than inferred so
// no reader has to guess whether a receipt is real.
Test bool `json:"test"`
// AmountCents and Currency are what settled, sealed with the answer so a replay
// posts the same credit again if the first attempt's ledger write was lost. A
// record sealed before these existed decodes without them and posts nothing: it
// was credited by the path that wrote it.
AmountCents int64 `json:"amountCents,omitempty"`
Currency string `json:"currency,omitempty"`
}
// PaymentFault is a money-path failure carrying the status the endpoint must answer
// with. The core cannot write an HTTP response — it has no request — but the
// status is part of the money contract (402 declined is not 500 broken, and a
// dunning workflow reads the difference), so it travels with the failure instead
// of being re-derived per endpoint.
type PaymentFault struct {
// Status is the HTTP status this failure means.
Status int
// Message is the caller-safe explanation.
Message string
// Err is the underlying cause, for logs. Never sent to the caller verbatim.
Err error
}
func (f *PaymentFault) Error() string {
if f.Err != nil {
return fmt.Sprintf("%s: %v", f.Message, f.Err)
}
return f.Message
}
func fault(status int, msg string, err error) *PaymentFault {
return &PaymentFault{Status: status, Message: msg, Err: err}
}
// TakePayment charges a single-use card token and credits the subject's balance,
// exactly once.
//
// It is the ONE card money move in this package: the browser's top-up and the
// typed op an agent calls are both projections of this function, so the bounds,
// the idempotency derivation and the ledger write cannot drift between them.
//
// The order is deliberate and is the difference between a refund and a
// reconciliation: bounds are checked BEFORE the guard, the guard is taken BEFORE
// the charge, and the credit happens AFTER the charge settles. A failure before
// the charge RELEASES the guard so a later attempt with a fresh nonce is not
// wedged; a failure after it does NOT, because the money already moved and a
// same-key retry must not charge a second time.
//
// The returned balance is read back from the same key just credited, so the
// number handed to the caller is the number the balance endpoint will report
// rather than an optimistic local sum.
func TakePayment(ctx context.Context, org *organization.Organization, in TakePaymentIn) (*TakePaymentOut, *PaymentFault) {
if org == nil {
return nil, fault(401, "missing identity headers", nil)
}
if in.SourceID == "" {
return nil, fault(400, "sourceId is required", nil)
}
if in.Subject == "" {
return nil, fault(401, "missing identity headers", nil)
}
db := datastore.New(org.Namespaced(ctx))
// Server-authoritative amount bounds (money-critical). This is the ONLY
// enforcement: a scripted or agent-driven request never passes through the
// console's client-side cap, so the floor and ceiling must bind here.
minCents, maxCents := topupBounds()
if in.AmountCents < minCents || in.AmountCents > maxCents {
return nil, fault(400, fmt.Sprintf("amountCents must be between %d and %d", minCents, maxCents), nil)
}
cur := normalizeCurrency(in.Currency)
// ONE idempotency derivation, shared with every other card money move: the
// caller's explicit key, else the stable request facts — the AMOUNT, never
// the single-use nonce — bucketed into a coarse window.
idemKey := in.IdempotencyKey
if idemKey == "" {
idemKey = windowKey("amount:" + fmt.Sprint(in.AmountCents) + ":cur:" + string(cur))
}
// The gateway key names the attempt's source too. A processor saves the
// first answer under a key — a decline, a 3-D Secure step — and replays it to
// any later request under the same key; a buyer who retries with another card
// for the same amount would be told the first card was declined again. The
// guard above is what keeps one ATTEMPT from charging twice.
squareKey := gatewayKey("topup", in.Subject, idemKey+":"+tokenTag(in.SourceID))
rec, replay, gerr := idemBegin(db, "billing-topup:"+in.Subject, idemKey)
if gerr != nil {
// The guard store is unavailable, so a first attempt cannot be told from a
// retry. Refuse. Proceeding is not defensible here: a re-tokenized retry
// carries a FRESH nonce, so in exactly this case the nonce backstop does
// not exist. Refusing costs a retry; proceeding costs a second real charge.
log.Error("topup idempotency Begin failed (org=%s): %v", in.Subject, gerr)
return nil, fault(503, "billing is temporarily unavailable; please retry", gerr)
}
if replay {
if rec.Status == idempotencykey.StatusCompleted && rec.Response != "" {
out, derr := decodeTakePaymentOut(rec.Response)
if derr != nil {
return nil, fault(500, "could not read the completed payment record", derr)
}
if f := bankTaken(ctx, org, in, out); f != nil {
return nil, f
}
return out, nil
}
return nil, fault(409, "top-up already in progress", nil)
}
// abandon releases the guard so a later attempt (with a fresh nonce) is not
// wedged. Called ONLY on pre-credit failures where no balance moved; the dead
// nonce prevents any double-charge on a same-nonce retry.
abandon := func() {
if rec != nil {
_ = rec.Delete()
}
}
chargeReq := processor.PaymentRequest{
Token: in.SourceID,
Amount: currency.Cents(in.AmountCents),
Currency: cur,
IdempotencyKey: squareKey,
Description: fmt.Sprintf("Top-up %d %s for org %s", in.AmountCents, cur, in.Subject),
ReceiptEmail: strings.TrimSpace(in.Payer.Email),
// An intent the buyer authenticated is bound to the account it was made for.
Metadata: map[string]interface{}{"hanzo_subject": in.Subject, "org": org.Name, "user": strings.ToLower(in.Subject)},
}
// The per-org processor registry. The global registry holds the webhook
// verifier, so a charge goes through the org-scoped one.
reg := processorsForOrg(org)
var (
proc processor.PaymentProcessor
err error
)
if prov := strings.ToLower(strings.TrimSpace(in.Provider)); prov != "" {
proc, err = reg.Get(processor.ProcessorType(prov))
if err == nil && (proc == nil || !proc.IsAvailable(ctx)) {
err = fmt.Errorf("processor %s is not available", prov)
}
} else {
proc, err = reg.SelectProcessor(ctx, chargeReq)
}
if err != nil {
abandon()
log.Error("No processor available for token topup: %v", err)
return nil, fault(422, "no payment processor available", err)
}
// A PaymentIntent the buyer authenticated is a bearer token for ITS payment:
// credited once, whatever key the request carries. The guard is permanent for
// a payment that settles and released when it does not.
releaseIntent := func() {}
var intentGuard *idempotencykey.IdempotencyKey
ownsIntent := false
if strings.HasPrefix(in.SourceID, "pi_") {
// Only an intent commerce registered for a wallet — a top-up's or a reload's,
// for this buyer — is a top-up. A plan's pays for a plan; one commerce never
// sent to the buyer's bank is not ours to credit.
if reg, found, rerr := pendingintent.Get(in.SourceID); rerr != nil {
abandon()
return nil, fault(503, "billing is temporarily unavailable; please retry", rerr)
} else if !found || (reg.Purpose != pendingintent.Topup && reg.Purpose != pendingintent.Reload) || !strings.EqualFold(reg.Subject, in.Subject) {
abandon()
return nil, fault(422, "this payment was not made for a top-up of this account", nil)
} else if reg.PaidCurrency != "" {
// A local-method payment settles in the currency it was quoted in and is
// credited the quote, by the verified webhook or the reconciler: the amount
// a browser states here is not the quote.
abandon()
return nil, fault(422, "this payment settles on its own; check your balance in a moment", nil)
}
// ONE claim per intent, in the system namespace, shared by the webhook, the
// reconciler, a top-up and a sale: whoever holds it credits. A claim that is
// not ours leaves us the READ-ONLY verification below and nothing else.
ig, replayed, ierr := idemBegin(webhookGuardDB(ctx), "billing-intent", in.SourceID)
if ierr != nil {
abandon()
return nil, fault(503, "billing is temporarily unavailable; please retry", ierr)
}
intentGuard, ownsIntent = ig, !replayed
if ownsIntent {
releaseIntent = func() {
if ig != nil {
_ = ig.Delete()
}
}
}
}
// Currencies: the host credits USD balances only; a charge in another currency
// would be taken and stranded.
if proc.Type() == processor.Stripe && cur != currency.USD {
releaseIntent()
abandon()
return nil, fault(422, "top-ups are in US dollars", nil)
}
// A new card is charged only for a buyer with room for another payment waiting on
// their bank: asked here, before Stripe makes an intent, so a refusal leaves nothing
// at Stripe. Finishing an intent that already exists is not a new one and is not
// refused.
if proc.Type() == processor.Stripe && !strings.HasPrefix(in.SourceID, "pi_") {
if cerr := atCap(in.Subject); cerr != nil {
releaseIntent()
abandon()
return nil, fault(429, cerr.Error(), cerr)
}
}
// A Square charge is marked begun before it is made and ended when its outcome is
// known, so routing never offers this payer another processor while it is not.
polV := 0
if proc.Type() == processor.Square {
_, polV, _ = ReadRoutingVersioned(ctx, org.Name)
if berr := routingpolicy.Begin(ctx, org.Name, in.Subject, string(processor.Square), squareKey, polV); berr != nil {
log.Warn("routing: the Square attempt was not marked: %v", berr)
}
}
result, err := proc.Charge(ctx, chargeReq)
if proc.Type() == processor.Square && result != nil {
if eerr := routingpolicy.End(ctx, org.Name, in.Subject, squareKey); eerr != nil {
log.Warn("routing: the Square attempt was not closed: %v", eerr)
}
}
// A Stripe call that got NO answer (a dropped connection, a timeout) may have
// charged the card. The attempt's guard stays held, so a retry — whose new card
// token would be a new Stripe key — is refused rather than charged twice, and
// the buyer is told the payment is unconfirmed, never that the card was declined.
if err != nil && proc.Type() == processor.Stripe && !answered(err) {
log.Error("RECONCILE: Stripe top-up for %s got no answer; the guard stays held: %v", in.Subject, err)
return nil, fault(503, "the payment could not be confirmed and may have gone through; check your balance before trying again", err)
}
// A card sent to its bank for authentication: the intent is recorded with its
// buyer and amount BEFORE the answer that sends them, so it is credited whether
// or not their browser comes back.
if rerr := registerAction(result, err, org, in.Subject, pendingintent.Topup, in.AmountCents, cur); rerr != nil {
releaseIntent()
abandon()
return nil, fault(429, rerr.Error(), rerr)
}
if err != nil || (result != nil && !result.Success) {
releaseIntent()
abandon()
log.Error("Charge failed for token topup (org=%s): %v", in.Subject, err)
declineMsg := parseCardDeclineReason(result, err)
if declineMsg == "" {
declineMsg = "charge declined"
}
return nil, fault(402, declineMsg, err)
}
// An intent the buyer finished may already have been credited — by its webhook,
// which arrives as soon as their bank confirms, before this request. Credit
// once: answer the credit that is there.
if strings.HasPrefix(in.SourceID, "pi_") {
if _, found, perr := paymentorg.Get(result.ProcessorRef); perr == nil && found {
ownedHere := ownsIntent
// The credit's own receipt: the row stamped with the charge. None yet means
// the claim holder is mid-credit.
stamped := transaction.New(db)
if sfound, serr := stamped.Query().Filter("SourceKind=", chargeSourceKind(proc.Type())).Filter("SourceId=", result.ProcessorRef).Get(); serr != nil || !sfound {
abandon()
return nil, fault(409, "this payment is being applied; check your balance in a moment", nil)
}
if ownedHere && intentGuard != nil {
_ = idempotencykey.Complete(intentGuard, result.ProcessorRef)
}
settleWallet(in.SourceID)
return &TakePaymentOut{TransactionID: stamped.Id(), Status: "ok", ProcessorRef: result.ProcessorRef, Test: org.TestMode()}, nil
}
// Credited by nobody yet, and the claim is another's: that holder is
// crediting it now. Not ours to credit a second time.
if !ownsIntent {
abandon()
return nil, fault(409, "this payment is being applied; check your balance in a moment", nil)
}
}
// Credit the canonical balance for the subject the caller's endpoint bounded.
trans := transaction.New(db)
trans.Type = transaction.Deposit
trans.DestinationId = in.Subject
trans.DestinationKind = "iam-user"
trans.Currency = cur
trans.Amount = currency.Cents(in.AmountCents)
trans.Notes = fmt.Sprintf("Top-up via %s (ref: %s)", proc.Type(), result.ProcessorRef)
trans.Tags = "topup"
// THE PROCESSOR'S OWN REFERENCE FOR THIS CHARGE, stamped on the row the charge
// wrote. It is what lets the provider's later callback recognise a payment this
// endpoint already took, and it is the difference between crediting a top-up once and
// crediting it twice.
//
// The callback settles asynchronously for the payments that have no endpoint
// (webhooks.go), and it identifies the ones that DO by looking this pair up. The
// pair was never written here, so the lookup matched nothing on every in-session
// charge, and the callback read its own endpoint's payment as one nobody had handled.
trans.SourceKind = chargeSourceKind(proc.Type())
trans.SourceId = result.ProcessorRef
// Ledger test-ness MUST follow the charge environment (org.TestMode): a Square
// sandbox charge credits the TEST bucket, never the live spendable one.
// test == credit-bucket == read-bucket == charge-env.
test := org.TestMode()
trans.Test = test
// The card token was charged (result.Success): a settled payment IS the mint
// authority, so authorize THIS write at the ledger sink (money-in == credit).
trans.SetContext(mintauth.WithAuthorized(trans.Context()))
if err := trans.Create(); err != nil {
// Charge settled but the credit failed. Leave the guard STARTED so a
// same-key retry 409s rather than re-charging, and log for manual
// reconciliation. The money moved; the dead nonce blocks a re-charge.
log.Error("RECONCILE: charge succeeded (ref=%s) but deposit failed for org %s: %v",
result.ProcessorRef, in.Subject, err)
return nil, fault(500, "charge succeeded but balance credit failed; contact support", err)
}
// Where this payment's receipt lives, so its processor's refund or dispute finds
// it: those callbacks name the payment and no org.
if err := paymentorg.Put(result.ProcessorRef, org.Name, in.Subject, "", 0, test); err != nil {
log.Warn("payment %s: the org index was not written: %v", result.ProcessorRef, err)
}
out := &TakePaymentOut{
TransactionID: trans.Id(),
Status: "ok",
ProcessorRef: result.ProcessorRef,
Test: test,
AmountCents: in.AmountCents,
Currency: string(cur),
}
// Seal the guard with the exact success body so a retry replays it verbatim —
// no second charge, identical answer.
if rec != nil {
if body, mErr := encodeTakePaymentOut(out); mErr == nil {
_ = idempotencykey.Complete(rec, body)
}
}
// The intent is spent for good: completed, so it is never claimed again as a
// crashed attempt.
if intentGuard != nil && ownsIntent {
_ = idempotencykey.Complete(intentGuard, trans.Id())
}
if intentGuard != nil {
settleWallet(in.SourceID)
}
// The spendable credit, after the charge is sealed so that a refusal here is
// recovered by the caller's retry (the replay above posts it again).
if f := bankTaken(ctx, org, in, out); f != nil {
return nil, f
}
return out, nil
}
// bankTaken posts a settled payment to the spendable ledger, keyed on the processor's
// reference. It is safe to ask again for the same payment, which is the whole recovery
// from a ledger that was down: the answer to a retry is the same posting.
func bankTaken(ctx context.Context, org *organization.Organization, in TakePaymentIn, out *TakePaymentOut) *PaymentFault {
if out.AmountCents <= 0 {
return nil
}
err := bankAt(ctx, org, in.Ledger, in.Subject, normalizeCurrency(out.Currency),
receipt{TransactionId: out.TransactionID, ProcessorRef: out.ProcessorRef, AmountCents: out.AmountCents}, "Top-up via card")
if err != nil {
log.Error("RECONCILE: payment %s was taken and the spendable balance was NOT credited: org=%s subject=%s: %v — a retry of the same request posts it again",
out.ProcessorRef, org.Name, in.Subject, err)
return fault(503, "your payment was received and your balance is still being updated; repeat the request to finish", err)
}
return nil
}
// PaymentRecord is a settled payment as the ledger holds it — the receipt a
// caller reads back after TakePayment returned its id.
type PaymentRecord struct {
// ID is the ledger transaction id, which is what TakePayment returned.
ID string `json:"id"`
// Subject is the billing key this payment credited.
Subject string `json:"subject"`
// AmountCents is the credited amount in whole cents.
AmountCents int64 `json:"amountCents"`
// Currency is the ISO code.
Currency string `json:"currency"`
// Status is the payment's state. A deposit in this ledger is written only
// AFTER the processor settled the charge, so a record that exists is a
// payment that succeeded — "settled" is the only truthful value here, and it
// is stated rather than left for a reader to assume.
Status string `json:"status"`
// Test reports whether this credited the TEST bucket (a sandbox charge) or
// live money. A receipt that does not say which is a receipt that can be
// mistaken for the other.
Test bool `json:"test"`
// Notes is the ledger memo, which carries the processor and its reference.
Notes string `json:"notes,omitempty"`
// CreatedAt is when the credit was written, RFC3339.
CreatedAt string `json:"createdAt,omitempty"`
}
// ReadPayment loads one settled payment out of the org's own ledger namespace.
//
// The org scopes the read by construction: the datastore is namespaced to it, so
// an id from another tenant simply is not found rather than being found and then
// filtered — there is no window in which the wrong row is in hand. A row that is
// not a deposit is not a payment and is refused as not-found, so this cannot be
// used to enumerate usage debits.
func ReadPayment(ctx context.Context, org *organization.Organization, id string) (*PaymentRecord, *PaymentFault) {
if org == nil {
return nil, fault(401, "missing identity headers", nil)
}
if strings.TrimSpace(id) == "" {
return nil, fault(400, "payment id is required", nil)
}
db := datastore.New(org.Namespaced(ctx))
t := transaction.New(db)
if err := t.GetById(strings.TrimSpace(id)); err != nil {
return nil, fault(404, "payment not found", err)
}
if t.Type != transaction.Deposit {
return nil, fault(404, "payment not found", nil)
}
rec := &PaymentRecord{
ID: t.Id(),
Subject: t.DestinationId,
AmountCents: int64(t.Amount),
Currency: string(t.Currency),
Status: "settled",
Test: t.Test,
Notes: t.Notes,
}
if !t.CreatedAt.IsZero() {
rec.CreatedAt = t.CreatedAt.UTC().Format(time.RFC3339)
}
return rec, nil
}
// normalizeCurrency is the ONE currency default, shared by both endpoints so a
// missing currency cannot mean usd on one and empty on the other.
func normalizeCurrency(code string) currency.Type {
cur := currency.Type(strings.ToLower(strings.TrimSpace(code)))
if cur == "" {
return currency.USD
}
return cur
}
// encodeTakePaymentOut renders the sealed idempotency body. It is the SAME
// marshal the fresh answer uses, which is what makes a replay byte-identical to
// the original rather than merely equivalent.
func encodeTakePaymentOut(out *TakePaymentOut) (string, error) {
b, err := json.Marshal(out)
if err != nil {
return "", err
}
return string(b), nil
}
// decodeTakePaymentOut reads a sealed body back. A record written before the
// core split carries only the original three fields; the rest decode as their
// zero values, which is honest — that receipt genuinely does not record them.
func decodeTakePaymentOut(body string) (*TakePaymentOut, error) {
var out TakePaymentOut
if err := json.Unmarshal([]byte(body), &out); err != nil {
return nil, err
}
return &out, nil
}