Docs/Ecosystem/Tally: Multi-Module Go Billing

Tally: Multi-Module Go Billing

Add billing to Go apps with Tally: seven standalone modules covering pure-Go Stripe and Paddle drivers, credits, webhooks, a PCI SAQ A portal, and Sight.

github.com/fletchhq/tally

tallypkg.go.devtally/stripepkg.go.devtally/paddlepkg.go.devtally/portalpkg.go.dev

Updated 2026-12-06 fletch docs show tally/tally 9 min read

On this page

Tally is a seven-module Go billing toolkit for Fletch apps and standalone Go services. Every module builds with CGO_ENABLED=0, keeps currency amounts in integer minor units, and avoids third-party payment SDKs.

Introduction

Billing code tends to tangle provider webhooks, plan entitlements, invoice views, and database state into one fragile package. Tally splits those concerns into seven standalone Go modules around a stdlib-only core so your binary only links the provider, store, queue, and UI layers you run.

Because tally/portal and tally/sight talk strictly to tally.Service, moving between Stripe and Paddle Billing v2 is a provider configuration change rather than a rewrite.

Installation and module layout

Install the core module plus the drivers and adapters you need:

go get github.com/fletchhq/tally@v0.1.0
go get github.com/fletchhq/tally/stripe@v0.1.0
go get github.com/fletchhq/tally/nock@v0.1.0

Tally ships as 7 Go modules (plus a runnable reference application in examples/saas with swap_test.go):

Module Dependencies Role
github.com/fletchhq/tally Go stdlib Money, billables, catalog DSL, subscription state machine, entitlements, credits ledger, HTTP middleware, and tally/tallytest
github.com/fletchhq/tally/stripe stdlib + tally Pure-Go Stripe provider (flexible billing, meters, Checkout, Billing Portal, webhooks); zero stripe-go
github.com/fletchhq/tally/paddle stdlib + tally Pure-Go Paddle Billing v2 Merchant-of-Record provider (tax-inclusive invoices, hosted checkout, pause, webhooks)
github.com/fletchhq/tally/nock tally + nock SQLite and Postgres tally.Store and tally.CreditStore with atomic credit debits
github.com/fletchhq/tally/quiver tally + quiver Transactional webhook dispatch, nightly reconciliation, and usage outbox draining
github.com/fletchhq/tally/portal tally + Fletch UI/security leaves Drop-in customer billing portal enforced as PCI SAQ A with strict nonce CSP
github.com/fletchhq/tally/sight tally + sight Local-only admin billing plugin (PluginID() == "tally") with capability-gated RBAC actions

The exported surface of the root github.com/fletchhq/tally module is frozen by testdata/api_freeze.txt and checked by TestAPIFreeze.

Core concepts (github.com/fletchhq/tally)

Money in integer minor units

Every price, invoice total, refund, and credit entry uses tally.Money in integer minor units. Never convert prices to float64.

type Money struct {
	Amount   int64
	Currency string
}

Use tally.USD(cents), tally.EUR(cents), tally.GBP(pence), or tally.NewMoney(amount, currency) to construct amounts.

Polymorphic billables

Any domain model (user, organization, workspace, or project) can own subscriptions, invoices, and credits by implementing tally.Billable:

type Billable interface {
	BillableRef() BillableRef
	BillingEmail() string
	BillingName() string
}

Models may optionally implement tally.BillingLocaler (preferred locale) and tally.BillingAddresser (billing address). Address billables with tally.Ref(typ, id) and tally.ParseBillableRef(s), then register each kind with tally.WithKinds(...):

tally.Kind("org", resolveOrg,
	tally.Authorize(canManageOrgBilling),
	tally.Eligible(orgEligibleForBilling),
)

Authorize enforces access checks for portal and service calls. Eligible gates whether a billable can start or change billing state.

Catalog DSL

Define plans and add-ons in Go using tally.BuildCatalog(...) (returns an error) or tally.NewCatalog(...) (panics on invalid definitions):

cat, err := tally.BuildCatalog(
	tally.Plan("starter", "Starter",
		tally.Description("For solo builders."),
		tally.TrialDays(14),
		tally.Features("exports"),
		tally.Limit("projects", 3),
		tally.Monthly(tally.USD(1500), tally.Version(1)),
		tally.Yearly(tally.USD(15000), tally.Version(1)),
	),
	tally.Plan("pro", "Pro",
		tally.Description("For growing teams."),
		tally.Popular(),
		tally.Features("exports", "sso", "audit_log"),
		tally.Limit("projects", 50),
		tally.Monthly(tally.USD(2900), tally.PerSeat(), tally.MinSeats(1), tally.MaxSeats(100), tally.Version(1)),
		tally.Yearly(tally.USD(29000), tally.PerSeat(), tally.MinSeats(1), tally.MaxSeats(100), tally.Version(1)),
	),
	tally.Addon("tokens", "Extra Tokens",
		tally.Hidden(),
		tally.Metered("api_tokens", tally.PerUnit(tally.USD(1)), tally.Meter("API Tokens")),
	),
)

tally.Version(v) produces immutable lookup keys such as pro.monthly.v1, keeping existing subscribers grandfathered when you publish v2. Preview provider sync changes with svc.SyncCatalog(ctx, tally.SyncOptions{DryRun: true}) before applying them with DryRun: false.

Service setup, state machine, and entitlements

Construct a service with tally.New(provider, store, opts...):

svc := tally.New(provider, store,
	tally.WithCatalog(cat),
	tally.WithKinds(orgKind),
	tally.WithDispatcher(tallyquiver.Dispatcher(q)),
	tally.WithPastDuePolicy(tally.PastDueAllowFor(72*time.Hour)),
	tally.WithLowBalanceThreshold(1000),
)

Available service options are WithCatalog, WithKinds, WithDispatcher, WithListener, WithClock, WithPastDuePolicy, WithExemptCheck, WithMaxRefundAmount, and WithLowBalanceThreshold.

Subscriptions transition across eight canonical tally.Status values (incomplete, incomplete_expired, trialing, active, past_due, unpaid, canceled, paused) through pure functions tally.Apply(prev, next) and tally.ApplyInvoice(prev, next, at). Past-due access is controlled by tally.PastDueAllow, tally.PastDueBlock, or tally.PastDueAllowFor(d).

Call svc.Banner(ctx, ref) to resolve a single prioritized UI banner across four tones (BannerTrialing, BannerPastDue, BannerActionRequired with ActionRequired SCA redirect, and BannerGracePeriod).

Check entitlements in Go with svc.Can(ctx, ref, feature) and svc.Limit(ctx, ref, key), or guard HTTP routes with stdlib middleware:

mux.Handle("/reports/", tally.RequireFeature(svc, refFromReq, "exports", onDeny)(reportsHandler))

Tally ships three route guards: tally.RequireSubscription, tally.RequirePlan, and tally.RequireFeature.

Service methods by group

Group Methods
Checkout & portal Checkout, Portal, SyncCheckout
Subscription lifecycle Subscribe, Swap, PreviewSwap, UpdateQuantity, IncrementQuantity, DecrementQuantity, Cancel, CancelNow, Resume, Pause, Unpause, StartGenericTrial
Sync & reconciliation SyncSubscription, Reconcile, SyncCatalog
Metering ReportUsage, DrainUsage, UsageSummary
Invoices & payment methods Invoices, DefaultPaymentMethod
Webhooks WebhookHandler, ProcessWebhookEvent, ReplayWebhookEvent
Entitlements & banners Banner, Can, Limit, ActiveSubscriptions
Operator actions GrantComp, ExtendTrial, Refund
Credits ledger GrantCredits, DebitCredits, CreditBalance, CreditLedger

Usage metering and prepaid credits

Tally supports both post-paid provider metering and an atomic local prepaid credits ledger.

Usage metering

Attach tally.Metered(meterKey, tally.PerUnit(m), tally.Meter(name)) to a plan or add-on. Record local usage with svc.ReportUsage, flush buffered records to the provider with svc.DrainUsage, and query totals with svc.UsageSummary.

Prepaid credits ledger

Use the credits ledger for AI tokens, API call packs, or promotional balances that must never go negative.

  • Types: tally.CreditStore, tally.CreditEntry, tally.CreditGrantParams, tally.CreditDebitParams, and sentinel tally.ErrInsufficientCredits.
  • Helper: tally.AvailableCredits(entries, asOf) computes available non-expired credits at time asOf.
  • Events via WithListener: tally.CreditsGranted, tally.CreditsDebited, and tally.CreditsLowBalance (emitted when a debit crosses below WithLowBalanceThreshold).

In tally/nock, RecordCreditDebit serializes concurrent debits with BEGIN IMMEDIATE on SQLite and a transaction-scoped advisory lock on Postgres so balances cannot double-spend.

Payment providers (tally/stripe and tally/paddle)

Both provider clients depend only on the Go standard library and tally. Each client redacts its secret in String() so logs never leak credentials and refuses HTTP redirects so keys cannot be forwarded to another host.

client := stripe.New(
	os.Getenv("STRIPE_SECRET_KEY"),
	stripe.BaseURL(stripe.DefaultBaseURL),
	stripe.APIVersion(stripe.DefaultAPIVersion), // "2025-11-17.clover"
)
provider := stripe.NewProvider(client, os.Getenv("STRIPE_WEBHOOK_SECRET"),
	stripe.WithProductPrefix("app_"),
)
client := paddle.New(
	os.Getenv("PADDLE_API_KEY"),
	paddle.Sandbox(), // omit in production (DefaultBaseURL = "https://api.paddle.com")
)
provider := paddle.NewProvider(client, os.Getenv("PADDLE_WEBHOOK_SECRET"),
	paddle.WithCheckoutURL("https://app.example.com/billing/checkout"),
)

Stripe (github.com/fletchhq/tally/stripe)

  • Defaults: DefaultBaseURL ("https://api.stripe.com"), DefaultAPIVersion ("2025-11-17.clover"), DefaultTolerance (5 * time.Minute), and MaxWebhookBody (1 << 20, 1 MiB).
  • Flexible billing & meters: Targets BillingMode: "flexible". Metered swaps add the new subscription item and delete the old item without sending clear_usage, swap previews call /v1/invoices/create_preview, and metering uses /v1/billing/meters and /v1/billing/meter_events.
  • Provider options: WithPortalConfiguration, WithProductPrefix, WithVerifyOptions.
  • Request options & idempotency: WithIdempotencyKey, WithStripeAccount, NewIdempotencyKey(), IdempotencyKeyFor(parts...), and (*stripe.Error).Retryable().
  • Client methods:
    • Checkout & Portal: CreateCheckoutSession, GetCheckoutSession, CreatePortalSession
    • Customers & Tax IDs: CreateCustomer, GetCustomer, UpdateCustomer, CreateTaxID, ListTaxIDs
    • Catalog: CreateProduct, GetProduct, CreatePrice, ListPrices
    • Subscriptions, Invoices & Refunds: CreateSubscription, GetSubscription, UpdateSubscription, ListSubscriptions, CreateSubscriptionItem, UpdateSubscriptionItem, DeleteSubscriptionItem, GetInvoice, ListInvoices, CreateInvoicePreview, CreateRefund
    • Meters: CreateMeter, ListMeters, CreateMeterEvent, MeterEventSummaries
  • Webhooks & escape hatch: stripe.Webhook(secret, fn), VerifySignature, ConstructEvent, SignPayload, and client.Do(ctx, method, path, stripe.NewForm(), &out, opts...) for any Stripe endpoint outside the provider interface.

Paddle Billing v2 (github.com/fletchhq/tally/paddle)

  • Merchant-of-Record taxes: Paddle calculates and remits VAT and sales tax. Invoice.Total holds the tax-inclusive grand total; call Provider.InvoiceDetail for subtotal, discount, tax, grand total, and per-rate TaxLine / TaxRateUsed details. Do not add app-side tax on top of Invoice.Total.
  • Hosted flows: Checkout returns Paddle's hosted checkout.url, payment-method updates use GetPaymentMethodUpdateTransaction, and hosted PDFs load via GetTransactionInvoice.
  • Pause & partial refunds: PauseSubscription and UnpauseSubscription preserve scheduled cancellations, and partial refunds account for discounts on a pre-tax basis.
  • Client methods:
    • Customers: CreateCustomer, GetCustomer, UpdateCustomer, ListCustomers
    • Catalog: CreateProduct, ListProducts, CreatePrice, UpdatePrice, ListPrices
    • Subscriptions: GetSubscription, UpdateSubscription, PreviewUpdateSubscription, CancelSubscription, ResumeSubscription, ListSubscriptions
    • Transactions, Payment Methods & Adjustments: CreateTransaction, GetTransaction, GetTransactionInvoice, ListTransactions, GetPaymentMethodUpdateTransaction, ListPaymentMethods, CreateAdjustment, ListAdjustments
  • Webhooks: Verifies Paddle-Signature (ts=<unix>;h1=<hex>, HMAC-SHA256 over <ts>:<rawBody>) with a 5-minute replay window, secret rotation via WithVerifyOptions, and a 1 MiB cap (ConstructEvent).

Persistence and background jobs (tally/nock and tally/quiver)

Nock store (github.com/fletchhq/tally/nock)

tally/nock implements tally.Store and tally.CreditStore on SQLite and Postgres:

tables := tallynock.Tables()            // include in your app's Nock schema
migrations, err := tallynock.Migrations(dialect)
err = tallynock.EnsureSchema(ctx, db)   // or apply directly in standalone binaries
store := tallynock.NewStore(db)

You may also call tallynock.GenerateMigration to emit migration SQL. Store exposes transactional execution (InTx) alongside full CRUD and query methods for customers (SaveCustomer, CustomerByBillable, CustomerByProviderID, ListCustomers), subscriptions (SaveSubscription, SubscriptionByProviderID, SubscriptionsFor, ListSubscriptions), invoices (SaveInvoice, InvoiceByProviderID, ListInvoices), generic trials (SaveGenericTrial, GenericTrial), webhook events (InsertWebhookEvent, UpdateWebhookEvent, WebhookEvent, ListWebhookEvents), usage records (InsertUsage, PendingUsage, UpdateUsage), price mappings (SavePriceMapping, PriceMappings), credits (RecordCreditGrant, RecordCreditDebit, ListCreditEntries), and local dashboard aggregations (Metrics).

Quiver jobs (github.com/fletchhq/tally/quiver)

Wire tally/quiver so webhook handlers return 2xx quickly and process events asynchronously inside the storing transaction:

svc := tally.New(provider, store,
	tally.WithDispatcher(tallyquiver.Dispatcher(q, quiver.OnQueue("billing"))),
)
tallyquiver.Register(q, svc)
err := tallyquiver.Schedule(q, svc,
	tallyquiver.ReconcileOn(reconcileSpec),
	tallyquiver.DrainUsageOn(drainSpec),
	tallyquiver.ReconcileLookback(48*time.Hour),
	tallyquiver.WithEnqueueOptions(quiver.OnQueue("billing")),
)

tally/quiver defines three typed quiver.JobArgs structs:

Job args Kind Default behavior
ProcessEventArgs "tally.process_event" Enqueued via quiver.EnqueueTx + quiver.Unique per provider event (MaxAttempts: 12)
ReconcileArgs "tally.reconcile" Scheduled daily at 03:17 UTC with a 48h lookback (MaxAttempts: 3, unique)
DrainUsageArgs "tally.drain_usage" Scheduled every minute to flush up to Limit (default 100) usage rows (MaxAttempts: 5, unique)

Register discards jobs that hit tally.ErrNotFound or tally.ErrUnsupported rather than retrying them.

Customer billing portal (tally/portal)

github.com/fletchhq/tally/portal mounts a customer-facing billing UI over tally.Service. It implements http.Handler (Portal.ServeHTTP) and also exposes Portal.AssetHandler if you serve static assets separately.

p := portal.New(svc,
	portal.WithBrand(portal.Brand{Name: "Meridian", LogoURL: "/assets/logo.svg"}),
	portal.WithTheme(portal.Theme{Accent: "#0f766e"}),
	portal.WithMode(portal.Hybrid),
	portal.WithKinds("org"),
	portal.WithActorFunc(currentActor),
	portal.WithCSRF(csrfSecret),
	portal.WithPublicURL("https://app.example.com"),
	portal.WithReceiptRenderer(renderPDFReceipt),
)
mux.Handle("/billing/", http.StripPrefix("/billing", p))

Portal types and modes

  • portal.Brand{Name, LogoURL} sets the header identity.
  • portal.Theme{Accent, AccentDark, Scheme} customizes colors (monochrome #18181B by default, using light-dark()).
  • portal.Actor{ID, Name, Billables} and portal.ActorFunc func(r *http.Request) (Actor, bool) power the entity switcher and root redirects; authorization always runs through the billable kind's tally.Authorize check.
  • portal.ReceiptRenderer func(ctx context.Context, b tally.Billable, inv tally.Invoice) ([]byte, error) optionally renders branded PDF receipts alongside the provider's legal invoice PDF.
  • portal.Mode selects how much happens in-app:
    • portal.Hybrid (default): plans, seat stepper, swap proration preview, banners, cancel/resume modals, and invoices run in-app; checkout and payment-method changes hand off to the provider's hosted page.
    • portal.Hosted: shows the current plan read-only and sends changes to the provider's customer portal.
    • portal.Native: like Hybrid, without the provider portal footer, starting new subscriptions in-app when a payment method is already on file.

Every portal response sets a fresh per-request nonce CSP (zero unsafe-inline or unsafe-eval), uses @alpinejs/csp components backed by plain HTML <form> fallbacks, and fails closed on missing authorization or invalid CSRF tokens.

Sight admin plugin (tally/sight)

Register tallysight.Plugin(svc, opts...) (PluginID() == "tally") on any Sight panel to give operators a billing dashboard and management screens:

panel := sight.New("admin",
	sight.WithPolicy(policy),
	sight.WithSubject(subjectForUser),
	sight.WithPlugins(
		tallysight.Plugin(svc,
			tallysight.WithCurrency("USD"),
			tallysight.WithRefundLimit(50000, "tally:refund-large"),
			tallysight.WithAuditRecorder(auditRecorder),
			tallysight.WithPanelPath("/admin"),
		),
	),
)

Options are WithCurrency, WithRefundLimit(cents, largePerm), WithAuditRecorder, WithStylesheet, and WithPanelPath. If your audit store implements tallysight.AuditReader, subscription detail pages include the operator audit trail.

The dashboard queries only your local Nock store and makes zero provider API calls on page load. It adds six KPI cards (MRR, ARR, Active, Trialing, Past due, Churn 30d), MRR trend, Plan mix, a Needs Attention table, a failed webhooks NavBadge, and four resources (Subscriptions with Trialing/Past due/On grace/Comped lenses, Customers, read-only Invoices, and Webhook Events with Failed/Unprocessed lenses and payload inspection).

Every operator mutation requires an explicit RBAC permission (tally:dashboard, tally:refund, tally:comp, tally:extend-trial, tally:cancel, tally:seats, tally:replay, tally:sync, tally:pause, tally:grant-credits). Refund, Pause, and Grant credits actions are registered only when the active provider or store implements that capability.

Testing (tally/tallytest)

github.com/fletchhq/tally/tallytest is stdlib-only and ships deterministic doubles and contract suites:

Export Purpose
FakeProvider In-memory tally.Provider double for unit tests
Clock Controllable clock passed to tally.WithClock
MemoryStore In-memory tally.Store and tally.CreditStore
SignedRequest Builds signed webhook *http.Request fixtures
RunProviderContract Verifies any tally.Provider against Tally invariants
RunStoreContract Verifies any tally.Store against Tally invariants