Documentation
¶
Overview ¶
Package tally is Fletch's unified billing toolkit: Cashier (subscriptions, invoices, meters, and entitlements), Spark (self-serve customer billing portal), and the Sight plugin (operator billing dashboard: KPIs, customers, subscriptions, audited actions). The root module is the home of those layers and, like every Fletch leaf, is pure Go and stdlib-only. Today it holds no exported API; the provider clients live in submodules and the higher layers land in later phases.
The stripe submodule, github.com/fletchhq/tally/stripe, is the Stripe client: Checkout, the Billing Portal, and signed webhooks.
Index ¶
- Constants
- Variables
- func AvailableCredits(entries []CreditEntry, asOf time.Time) int64
- func PerSeat() interface{ ... }
- func RequireFeature(svc *Service, refFromReq RefFunc, feature string, onDeny http.Handler) func(http.Handler) http.Handler
- func RequirePlan(svc *Service, refFromReq RefFunc, planKey string, onDeny http.Handler) func(http.Handler) http.Handler
- func RequireSubscription(svc *Service, refFromReq RefFunc, onDeny http.Handler) func(http.Handler) http.Handler
- func Version(v int) interface{ ... }
- type ActionRequired
- type ActionRequiredEvent
- type Address
- type Authorizer
- type Banner
- type BannerTone
- type Billable
- type BillableRef
- type BillingAddresser
- type BillingLocaler
- type CallOption
- func Billed(i Interval) CallOption
- func IdempotencyKey(k string) CallOption
- func Named(name string) CallOption
- func NoProrate() CallOption
- func ProrateNow() CallOption
- func ResetBillingCycle() CallOption
- func Seats(n int64) CallOption
- func SkipTrial() CallOption
- func TrialUntil(t time.Time) CallOption
- func WithDiscount(d Discount) CallOption
- func WithMetadata(m map[string]string) CallOption
- func WithPaymentMethod(token string) CallOption
- type Canceled
- type Catalog
- type CatalogSyncer
- type CheckoutItem
- type CheckoutMode
- type CheckoutRequest
- type CheckoutResult
- type Comped
- type CreateSubscription
- type CreditDebitParams
- type CreditEntry
- type CreditEvent
- type CreditGrantParams
- type CreditStore
- type CreditsDebited
- type CreditsGranted
- type CreditsLowBalance
- type CustomAmount
- type Customer
- type CustomerQuery
- type DecodedEvent
- type Discount
- type Dispatcher
- type DomainEvent
- type EligibilityFunc
- type Ended
- type EventRef
- type GenericTrial
- type Interval
- type Invoice
- type InvoiceEvent
- type InvoiceLine
- type InvoicePaid
- type InvoicePaymentFailed
- type InvoicePreview
- type InvoiceQuery
- type InvoiceStatus
- type Invoicer
- type KindDef
- type KindOption
- type Lens
- type Listener
- type MeterEvent
- type Meterer
- type Metrics
- type MetricsQuery
- type Money
- type ObjectType
- type Option
- func WithCatalog(c *Catalog) Option
- func WithClock(now func() time.Time) Option
- func WithDispatcher(d Dispatcher) Option
- func WithExemptCheck(fn func(ctx context.Context, ref BillableRef) bool) Option
- func WithKinds(kinds ...KindDef) Option
- func WithListener(ls ...Listener) Option
- func WithLowBalanceThreshold(n int64) Option
- func WithMaxRefundAmount(m Money) Option
- func WithPastDuePolicy(p PastDuePolicy) Option
- type Page
- type PastDuePolicy
- type Pauser
- type PaymentFailed
- type PaymentMethod
- type PaymentMethods
- type PlanCount
- type PlanDef
- type PlanOption
- type PriceDef
- type PriceMapping
- type PriceOption
- type Proration
- type Provider
- type ProviderCheckout
- type ProviderName
- type QuantityChanged
- type ReconcileReport
- type Redirect
- type RefFunc
- type Refund
- type RefundRequest
- type Refunded
- type Refunder
- type Resolver
- type Resumed
- type Service
- func (s *Service) ActiveSubscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)
- func (s *Service) Authorize(ctx context.Context, ref BillableRef) error
- func (s *Service) Banner(ctx context.Context, ref BillableRef) (*Banner, error)
- func (s *Service) Can(ctx context.Context, ref BillableRef, feature string) (bool, error)
- func (s *Service) Cancel(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
- func (s *Service) CancelNow(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
- func (s *Service) Catalog() *Catalog
- func (s *Service) CheckEligible(ctx context.Context, b Billable, plan *PlanDef) error
- func (s *Service) Checkout(ctx context.Context, ref BillableRef, req CheckoutRequest) (Redirect, error)
- func (s *Service) CreditBalance(ctx context.Context, ref BillableRef) (int64, error)
- func (s *Service) CreditLedger(ctx context.Context, ref BillableRef, p Page) ([]CreditEntry, error)
- func (s *Service) Current(ctx context.Context, ref BillableRef, name string) (Subscription, error)
- func (s *Service) DebitCredits(ctx context.Context, ref BillableRef, p CreditDebitParams) (CreditEntry, error)
- func (s *Service) DecrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)
- func (s *Service) DefaultPaymentMethod(ctx context.Context, ref BillableRef) (*PaymentMethod, error)
- func (s *Service) DrainUsage(ctx context.Context, limit int) (int, error)
- func (s *Service) ExtendTrial(ctx context.Context, ref BillableRef, until time.Time, opts ...CallOption) (Subscription, error)
- func (s *Service) GrantComp(ctx context.Context, ref BillableRef, plan string, until time.Time, ...) (Subscription, error)
- func (s *Service) GrantCredits(ctx context.Context, ref BillableRef, p CreditGrantParams) (CreditEntry, error)
- func (s *Service) IncrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)
- func (s *Service) Invoices(ctx context.Context, ref BillableRef, limit, offset int) ([]Invoice, int, error)
- func (s *Service) Kinds() []KindDef
- func (s *Service) Limit(ctx context.Context, ref BillableRef, key string) (int64, error)
- func (s *Service) Now() time.Time
- func (s *Service) OnPlan(ctx context.Context, ref BillableRef, plan string) (bool, error)
- func (s *Service) PastDuePolicy() PastDuePolicy
- func (s *Service) Pause(ctx context.Context, ref BillableRef, resumesAt time.Time, opts ...CallOption) (Subscription, error)
- func (s *Service) Portal(ctx context.Context, ref BillableRef, returnURL string) (Redirect, error)
- func (s *Service) PreviewSwap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (InvoicePreview, error)
- func (s *Service) ProcessWebhookEvent(ctx context.Context, id string) error
- func (s *Service) Provider() Provider
- func (s *Service) Reconcile(ctx context.Context, since time.Time) (ReconcileReport, error)
- func (s *Service) Refund(ctx context.Context, invoiceID string, amount Money, reason, actor string, ...) (Refund, error)
- func (s *Service) ReplayWebhookEvent(ctx context.Context, id, actor string) error
- func (s *Service) ReportUsage(ctx context.Context, ref BillableRef, meter string, quantity int64, ...) error
- func (s *Service) Resolve(ctx context.Context, ref BillableRef) (Billable, error)
- func (s *Service) Resume(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
- func (s *Service) StartGenericTrial(ctx context.Context, ref BillableRef, plan string, days int) (GenericTrial, error)
- func (s *Service) Store() Store
- func (s *Service) Subscribe(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)
- func (s *Service) Subscribed(ctx context.Context, ref BillableRef) (bool, error)
- func (s *Service) Subscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)
- func (s *Service) Swap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)
- func (s *Service) SyncCatalog(ctx context.Context, dryRun bool) (SyncPlan, error)
- func (s *Service) SyncCheckout(ctx context.Context, sessionID string) (Subscription, error)
- func (s *Service) SyncSubscription(ctx context.Context, id string) (Subscription, error)
- func (s *Service) Unpause(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
- func (s *Service) UpdateQuantity(ctx context.Context, ref BillableRef, qty int64, opts ...CallOption) (Subscription, error)
- func (s *Service) UsageSummary(ctx context.Context, ref BillableRef, meter string, start, end time.Time) (UsageSummary, error)
- func (s *Service) WebhookHandler() http.Handler
- type Status
- type Store
- type Subscription
- func (s Subscription) Clone() Subscription
- func (s *Subscription) Comped(now time.Time) bool
- func (s *Subscription) Ended(now time.Time) bool
- func (s *Subscription) Incomplete() bool
- func (s *Subscription) OnGracePeriod(now time.Time) bool
- func (s *Subscription) OnTrial(now time.Time) bool
- func (s *Subscription) PastDue() bool
- func (s *Subscription) Recurring(now time.Time) bool
- func (s *Subscription) Valid(now time.Time, policy PastDuePolicy) bool
- type SubscriptionEvent
- type SubscriptionItem
- type SubscriptionLister
- type SubscriptionManager
- type SubscriptionPrice
- type SubscriptionQuery
- type SubscriptionStarted
- type SwapRequest
- type Swapped
- type SyncAction
- type SyncActionKind
- type SyncOptions
- type SyncPlan
- type TrialWillEnd
- type UsageQuery
- type UsageRecord
- type UsageSummary
- type WebhookDecoder
- type WebhookEvent
- type WebhookEventQuery
Constants ¶
const ( MetaBillable = "tally_billable" MetaPlan = "tally_plan" MetaName = "tally_name" )
Metadata keys tally sets on provider subscriptions, so a subscription can be tied to its billable even before the customer is known locally.
const ( EventTrialWillEnd = "customer.subscription.trial_will_end" EventInvoicePaymentFailed = "invoice.payment_failed" EventInvoiceActionRequired = "invoice.payment_action_required" )
Well-known event types the pipeline turns into domain events. Providers map theirs to these in DecodedEvent.Type when they differ.
const DefaultSubscriptionName = "default"
DefaultSubscriptionName is the name of a billable's main subscription.
const MaxWebhookBody = 1 << 20
MaxWebhookBody caps the webhook body WebhookHandler reads.
const Unlimited int64 = math.MaxInt64
Unlimited is the Limit of exempt billables, and a value plans can set.
Variables ¶
var ( // ErrInsufficientCredits means a debit is larger than the available // credit balance. Nothing is recorded. ErrInsufficientCredits = errors.New("tally: insufficient credits") // ErrCreditAmount means a grant or debit amount is not positive. ErrCreditAmount = errors.New("tally: credit amount must be positive") )
var ( // ErrNotFound means the record does not exist. ErrNotFound = errors.New("tally: not found") // ErrUnsupported means the provider lacks the capability. ErrUnsupported = errors.New("tally: not supported by the provider") // ErrNoSubscription means the billable has no live subscription. ErrNoSubscription = errors.New("tally: no subscription") // ErrUnknownPlan means the plan or price is not in the catalog. ErrUnknownPlan = errors.New("tally: unknown plan") // ErrPriceNotSynced means a catalog price has no provider price yet; // run SyncCatalog. ErrPriceNotSynced = errors.New("tally: price not synced to the provider") // ErrUnknownKind means the billable type was not registered. ErrUnknownKind = errors.New("tally: unknown billable kind") // ErrForbidden means the caller may not manage the billable. ErrForbidden = errors.New("tally: forbidden") // ErrIneligible wraps an EligibilityFunc refusal. ErrIneligible = errors.New("tally: not eligible for plan") // ErrQuantity means a quantity is outside the plan's seat bounds. ErrQuantity = errors.New("tally: quantity outside plan bounds") // ErrNotOnGracePeriod means only a subscription on grace can resume. ErrNotOnGracePeriod = errors.New("tally: subscription is not on its grace period") // ErrTrialUsed means the billable already had a trial. ErrTrialUsed = errors.New("tally: trial already used") // ErrRefundTooLarge means the refund exceeds what was paid or the // configured limit. ErrRefundTooLarge = errors.New("tally: refund exceeds the allowed amount") // ErrBadSignature means a webhook failed verification. ErrBadSignature = errors.New("tally: webhook signature invalid") // ErrCardDeclined means the provider declined the payment. ErrCardDeclined = errors.New("tally: payment declined") )
Errors returned by the Service, stores, and providers.
var ( PastDueAllow = PastDuePolicy{/* contains filtered or unexported fields */} PastDueBlock = PastDuePolicy{} )
The past-due policies. PastDueAllow is the default: the provider's retries decide when the subscription ends.
var ErrAlreadySubscribed = errors.New("tally: already subscribed")
ErrAlreadySubscribed means the billable already has a live subscription with that name.
Functions ¶
func AvailableCredits ¶
func AvailableCredits(entries []CreditEntry, asOf time.Time) int64
AvailableCredits replays a billable's ledger, oldest entry first, and returns the balance available at asOf. Each debit draws on the grants still unexpired at its time, the soonest to expire first and grants that never expire last; what is left of a grant stops counting when it expires. Entries created after asOf are ignored. Stores share it so they agree on expiry.
func PerSeat ¶
func PerSeat() interface {
PlanOption
PriceOption
}
PerSeat bills a licensed price per seat. On a plan it applies to all of the plan's licensed prices.
func RequireFeature ¶
func RequireFeature(svc *Service, refFromReq RefFunc, feature string, onDeny http.Handler) func(http.Handler) http.Handler
RequireFeature lets a request through when a plan its billable holds grants feature.
func RequirePlan ¶
func RequirePlan(svc *Service, refFromReq RefFunc, planKey string, onDeny http.Handler) func(http.Handler) http.Handler
RequirePlan lets a request through when its billable holds planKey.
func RequireSubscription ¶
func RequireSubscription(svc *Service, refFromReq RefFunc, onDeny http.Handler) func(http.Handler) http.Handler
RequireSubscription lets a request through when its billable is subscribed (see Service.Subscribed). Otherwise onDeny serves it; nil answers 402 Payment Required.
func Version ¶
func Version(v int) interface { PlanOption PriceOption }
Version sets the version of a price, or on a plan the default version of its prices. Raising it mints new lookup keys; list the old prices with their old version to keep them for grandfathered subscribers:
Plan("seller", "Seller", Version(2),
Monthly(USD(5900)),
Monthly(USD(4900), Version(1)))
Types ¶
type ActionRequired ¶
ActionRequired is returned, as an error, when a payment needs customer authentication (SCA/3-D Secure). Send the customer to URL; ClientSecret is for apps that confirm with the provider's own script.
func (*ActionRequired) Error ¶
func (a *ActionRequired) Error() string
type ActionRequiredEvent ¶
type ActionRequiredEvent struct {
InvoiceEvent
URL string
}
ActionRequiredEvent is sent when a payment waits for customer authentication (SCA). URL is where the customer confirms it.
func (ActionRequiredEvent) EventName ¶
func (ActionRequiredEvent) EventName() string
EventName implements DomainEvent.
type Address ¶
type Address struct {
Line1 string
Line2 string
City string
State string
PostalCode string
// Country is an ISO 3166-1 alpha-2 code.
Country string
}
Address is a postal address for tax.
type Authorizer ¶
type Authorizer func(ctx context.Context, ref BillableRef) error
Authorizer decides whether the caller in ctx (the signed-in user, put there by the app's auth) may manage ref's billing. A nil error allows.
type Banner ¶
type Banner struct {
Tone BannerTone
Title string
Message string
ActionLabel string
ActionURL string
EndsAt time.Time
}
Banner is the one billing notice to show a billable. ActionURL is a provider page when there is one (an invoice to pay or confirm); otherwise it is empty and the app links its own billing page.
type BannerTone ¶
type BannerTone string
BannerTone is the kind of billing banner to show.
const ( BannerActionRequired BannerTone = "action_required" BannerPastDue BannerTone = "past_due" BannerGracePeriod BannerTone = "grace_period" BannerTrialing BannerTone = "trialing" )
The banner tones, in priority order.
type Billable ¶
type Billable interface {
BillableRef() BillableRef
BillingEmail() string
BillingName() string
}
Billable is an entity that pays: a user, a team, an organization.
type BillableRef ¶
BillableRef names the paying entity. (Type, ID) is its storage key: {"user", "u_1"}, {"team", "t_9"}, {"bakery", "b_3"}.
func ParseBillableRef ¶
func ParseBillableRef(s string) (BillableRef, error)
ParseBillableRef reads "type:id".
func (BillableRef) String ¶
func (r BillableRef) String() string
String renders the ref as "type:id".
type BillingAddresser ¶
type BillingAddresser interface {
BillingAddress() Address
}
BillingAddresser is an optional Billable capability for tax.
type BillingLocaler ¶
BillingLocaler is an optional Billable capability. Its time zone sets where a trial ends: at the end of the last trial day, local time.
type CallOption ¶
type CallOption func(*callConfig)
CallOption adjusts one Service operation.
func Billed ¶
func Billed(i Interval) CallOption
Billed picks the billing interval; the default is monthly.
func IdempotencyKey ¶
func IdempotencyKey(k string) CallOption
IdempotencyKey makes a retried call safe at the provider, and dedupes usage reports.
func Named ¶
func Named(name string) CallOption
Named picks the subscription by name; the default is "default".
func ResetBillingCycle ¶
func ResetBillingCycle() CallOption
ResetBillingCycle starts a new billing period with a swap.
func SkipTrial ¶
func SkipTrial() CallOption
SkipTrial starts the subscription without the plan's trial.
func TrialUntil ¶
func TrialUntil(t time.Time) CallOption
TrialUntil sets the trial end in place of the plan's trial length.
func WithDiscount ¶
func WithDiscount(d Discount) CallOption
WithDiscount applies a coupon or promotion code.
func WithMetadata ¶
func WithMetadata(m map[string]string) CallOption
WithMetadata adds provider metadata.
func WithPaymentMethod ¶
func WithPaymentMethod(token string) CallOption
WithPaymentMethod charges a stored provider payment method token.
type Canceled ¶
type Canceled struct {
SubscriptionEvent
AtPeriodEnd bool
EndsAt time.Time
}
Canceled is sent when a subscription is canceled, at period end or now.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog is the set of plans, defined in code. Provider price IDs are not part of it: SyncCatalog maps lookup keys to them in the Store.
func BuildCatalog ¶
BuildCatalog builds a catalog and reports an invalid definition.
func NewCatalog ¶
NewCatalog builds a catalog. It panics on an invalid definition, since a catalog is a package-level value fixed at compile time; use BuildCatalog for one built at run time.
type CatalogSyncer ¶
type CatalogSyncer interface {
SyncCatalog(ctx context.Context, c *Catalog, opts SyncOptions) (SyncPlan, error)
}
CatalogSyncer creates and archives provider products and prices so the provider matches the catalog.
type CheckoutItem ¶
type CheckoutItem struct {
PriceID string
Quantity int64
// Name and Amount describe an ad-hoc price when PriceID is empty.
Name string
Amount Money
// Interval makes an ad-hoc price recurring.
Interval Interval
CustomAmount *CustomAmount
}
CheckoutItem is one line of a provider checkout: a provider price, or an ad-hoc price.
type CheckoutMode ¶
type CheckoutMode string
CheckoutMode is what a checkout collects.
const ( CheckoutSubscription CheckoutMode = "subscription" CheckoutPayment CheckoutMode = "payment" CheckoutSetup CheckoutMode = "setup" )
The checkout modes.
type CheckoutRequest ¶
type CheckoutRequest struct {
Plan string
Interval Interval
Quantity int64
// Name is the subscription's name; empty means "default".
Name string
Mode CheckoutMode
Items []CheckoutItem
SuccessURL string
CancelURL string
SkipTrial bool
AllowPromotionCodes bool
Discounts []Discount
AutomaticTax bool
TaxIDCollection bool
Locale string
Metadata map[string]string
IdempotencyKey string
}
CheckoutRequest starts a hosted checkout. Set Plan for a subscription; set Mode CheckoutPayment and Items for a one-off payment, such as pay what you want with CheckoutItem.CustomAmount.
type CheckoutResult ¶
type CheckoutResult struct {
ID string
Status string
PaymentStatus string
Customer string
SubscriptionID string
ClientReferenceID string
Metadata map[string]string
}
CheckoutResult is a provider checkout session's outcome.
type Comped ¶
type Comped struct {
SubscriptionEvent
Until time.Time
}
Comped is sent when an operator grants a comp.
type CreateSubscription ¶
type CreateSubscription struct {
Customer string
Prices []SubscriptionPrice
TrialEnd time.Time
// PaymentMethod is a provider payment method token; empty uses the
// customer's default.
PaymentMethod string
Discounts []Discount
AutomaticTax bool
Metadata map[string]string
IdempotencyKey string
}
CreateSubscription creates a subscription directly, with a stored payment method, without a checkout page.
type CreditDebitParams ¶
CreditDebitParams spends a billable's credits.
type CreditEntry ¶
type CreditEntry struct {
ID string
Billable BillableRef
Delta int64
// BalanceAfter is the available balance right after the entry, at
// CreatedAt.
BalanceAfter int64
Reason string
// Ref ties the entry to something in the app, such as an order or a
// request ID.
Ref string
// IdempotencyKey, when set, is unique across the ledger: recording it
// again returns the first entry.
IdempotencyKey string
// ExpiresAt ends a grant: from then on what is left of it is not
// available. Debits never expire.
ExpiresAt *time.Time
CreatedAt time.Time
}
CreditEntry is one line of a billable's prepaid credit ledger: a grant (positive Delta) or a debit (negative Delta). Entries are never changed or deleted; an expired grant simply stops counting.
type CreditEvent ¶
type CreditEvent struct {
Entry CreditEntry
At time.Time
}
CreditEvent is the common part of credit events.
func (CreditEvent) BillableRef ¶
func (e CreditEvent) BillableRef() BillableRef
BillableRef implements DomainEvent.
type CreditGrantParams ¶
type CreditGrantParams struct {
Amount int64
Reason string
Ref string
IdempotencyKey string
ExpiresAt *time.Time
}
CreditGrantParams adds credits to a billable.
type CreditStore ¶
type CreditStore interface {
// RecordCreditGrant appends a grant and fills in ID and BalanceAfter.
// When e.IdempotencyKey is already recorded it sets *e to the stored
// entry and reports false.
RecordCreditGrant(ctx context.Context, e *CreditEntry) (bool, error)
// RecordCreditDebit appends a debit (e.Delta < 0) when the balance
// available at e.CreatedAt covers it, and ErrInsufficientCredits
// otherwise. A repeated IdempotencyKey behaves as in
// RecordCreditGrant, whatever the balance is now.
RecordCreditDebit(ctx context.Context, e *CreditEntry) (bool, error)
// CreditBalance is the balance available at asOf.
CreditBalance(ctx context.Context, ref BillableRef, asOf time.Time) (int64, error)
// ListCreditEntries returns the billable's entries, newest first.
// Page.After is the ID of the last entry of the previous page; Limit
// 0 means 50.
ListCreditEntries(ctx context.Context, ref BillableRef, p Page) ([]CreditEntry, error)
}
CreditStore is the optional Store capability that keeps the prepaid credit ledger. Recording methods lock the billable's ledger (or join the InTx transaction holding it), so concurrent debits can never overdraw. They raise an entry's CreatedAt to the billable's newest entry's when it is earlier, so ledger order is time order.
type CreditsDebited ¶
type CreditsDebited struct{ CreditEvent }
CreditsDebited is sent when credits are spent.
func (CreditsDebited) EventName ¶
func (CreditsDebited) EventName() string
EventName implements DomainEvent.
type CreditsGranted ¶
type CreditsGranted struct{ CreditEvent }
CreditsGranted is sent when credits are granted.
func (CreditsGranted) EventName ¶
func (CreditsGranted) EventName() string
EventName implements DomainEvent.
type CreditsLowBalance ¶
type CreditsLowBalance struct {
CreditEvent
Threshold int64
Balance int64
}
CreditsLowBalance is sent with the debit that takes the balance from at least Threshold to below it (see WithLowBalanceThreshold).
func (CreditsLowBalance) EventName ¶
func (CreditsLowBalance) EventName() string
EventName implements DomainEvent.
type CustomAmount ¶
CustomAmount lets the customer choose the amount (pay what you want).
type Customer ¶
type Customer struct {
ID string
Billable BillableRef
Provider ProviderName
ProviderID string
Email string
Name string
TaxExempt bool
Metadata map[string]string
CreatedAt time.Time
UpdatedAt time.Time
}
Customer links a billable to a provider customer.
type CustomerQuery ¶
type CustomerQuery struct {
Search string
Provider ProviderName
Limit int
Offset int
}
CustomerQuery filters ListCustomers. Search matches email, name, and billable ID, case-insensitively. Limit 0 means 50.
type DecodedEvent ¶
type DecodedEvent struct {
ID string
Type string
ObjectType ObjectType
ObjectID string
Created time.Time
}
DecodedEvent is a verified webhook event. The pipeline re-fetches the object from the provider before applying it, so the payload itself is kept only for the log.
type Discount ¶
Discount applies a coupon or a promotion code.
func CouponCode ¶
CouponCode returns a Discount for a provider coupon ID.
func PromotionCode ¶
PromotionCode returns a Discount for a provider promotion code ID.
type Dispatcher ¶
Dispatcher hands a stored webhook event to background processing, inside the transaction that stored it, so the job exists exactly when the event does. tally/quiver provides one. With no Dispatcher events are processed inline in the webhook request.
type DomainEvent ¶
type DomainEvent interface {
// EventName is a stable name, such as "subscription.started".
EventName() string
// BillableRef is the billable the event is about.
BillableRef() BillableRef
}
DomainEvent is a billing change an app reacts to: mail, entitlement caches, analytics. Listeners get them inside the transaction that records the change.
func Apply ¶
func Apply(prev *Subscription, next Subscription) []DomainEvent
Apply returns the domain events of moving a subscription from prev (nil when new) to next. It compares states only, so applying the same state twice yields nothing: duplicate and out-of-order provider events are harmless once next is re-fetched from the provider.
func ApplyInvoice ¶
func ApplyInvoice(prev *Invoice, next Invoice, at time.Time) []DomainEvent
ApplyInvoice returns the domain events of moving an invoice from prev (nil when new) to next.
type EligibilityFunc ¶
EligibilityFunc decides whether b may move to plan, such as "you have 45 listings; Seller allows 40". A non-nil error refuses, and is returned to the caller wrapped in ErrIneligible.
type Ended ¶
type Ended struct{ SubscriptionEvent }
Ended is sent when a subscription stops granting its plan for good.
type EventRef ¶
type EventRef struct {
// ID is the local webhook event ID to pass to ProcessWebhookEvent.
ID string
Provider ProviderName
EventID string
Type string
}
EventRef identifies a stored webhook event for a Dispatcher.
type GenericTrial ¶
type GenericTrial struct {
Billable BillableRef
Plan string
TrialEndsAt time.Time
CreatedAt time.Time
}
GenericTrial is a cardless trial, on the billable rather than on a subscription.
type Invoice ¶
type Invoice struct {
ID string
CustomerID string
Billable BillableRef
SubscriptionID string
Provider ProviderName
ProviderID string
ProviderCustomerID string
ProviderSubscriptionID string
Number string
Status InvoiceStatus
Total Money
AmountPaid Money
AmountDue Money
AmountRefunded Money
HostedURL string
PDFURL string
PeriodStart time.Time
PeriodEnd time.Time
PaidAt time.Time
// ActionRequired is set while the payment waits for customer
// authentication.
ActionRequired bool
CreatedAt time.Time
}
Invoice is the local mirror of a provider invoice.
type InvoiceEvent ¶
InvoiceEvent is the common part of invoice events.
func (InvoiceEvent) BillableRef ¶
func (e InvoiceEvent) BillableRef() BillableRef
BillableRef implements DomainEvent.
type InvoiceLine ¶
type InvoiceLine struct {
Description string
Amount Money
Quantity int64
PriceLookupKey string
Proration bool
}
InvoiceLine is one line of an invoice or a preview.
type InvoicePaid ¶
type InvoicePaid struct{ InvoiceEvent }
InvoicePaid is sent when an invoice is paid.
func (InvoicePaid) EventName ¶
func (InvoicePaid) EventName() string
EventName implements DomainEvent.
type InvoicePaymentFailed ¶
type InvoicePaymentFailed struct{ InvoiceEvent }
InvoicePaymentFailed is sent when an invoice payment attempt fails.
func (InvoicePaymentFailed) EventName ¶
func (InvoicePaymentFailed) EventName() string
EventName implements DomainEvent.
type InvoicePreview ¶
type InvoicePreview struct {
Subtotal Money
Total Money
AmountDue Money
Lines []InvoiceLine
PeriodEnd time.Time
}
InvoicePreview is a computed invoice, such as the proration of a swap.
type InvoiceQuery ¶
type InvoiceQuery struct {
CustomerID string
Billable BillableRef
SubscriptionID string
Status InvoiceStatus
Limit int
Offset int
}
InvoiceQuery filters ListInvoices. Results are newest first.
type InvoiceStatus ¶
type InvoiceStatus string
InvoiceStatus is an invoice's provider status.
const ( InvoiceDraft InvoiceStatus = "draft" InvoiceOpen InvoiceStatus = "open" InvoicePaidStatus InvoiceStatus = "paid" InvoiceVoid InvoiceStatus = "void" InvoiceUncollectible InvoiceStatus = "uncollectible" )
The invoice statuses.
type Invoicer ¶
type Invoicer interface {
Invoices(ctx context.Context, customer string, p Page) ([]Invoice, error)
Invoice(ctx context.Context, id string) (Invoice, error)
UpcomingInvoice(ctx context.Context, customer, subscriptionID string) (InvoicePreview, error)
}
Invoicer lists and fetches invoices.
type KindOption ¶
type KindOption func(*KindDef)
KindOption configures a KindDef.
func Authorize ¶
func Authorize(fn Authorizer) KindOption
Authorize sets who may manage billables of the kind.
func Eligible ¶
func Eligible(fn EligibilityFunc) KindOption
Eligible sets the plan eligibility check of the kind.
type Listener ¶
type Listener func(ctx context.Context, tx any, e DomainEvent) error
Listener receives domain events inside the store transaction tx. An error rolls the transaction back; a webhook event is then retried.
type MeterEvent ¶
type MeterEvent struct {
Customer string
// EventName is the provider meter's event name.
EventName string
Quantity int64
// Identifier deduplicates the report at the provider.
Identifier string
Timestamp time.Time
}
MeterEvent is one usage report.
type Meterer ¶
type Meterer interface {
ReportUsage(ctx context.Context, e MeterEvent) error
UsageSummary(ctx context.Context, q UsageQuery) (UsageSummary, error)
}
Meterer reports metered usage.
type Metrics ¶
type Metrics struct {
MRR Money
ARR Money
Active int
Trialing int
PastDue int
OnGrace int
Comped int
// Churned counts subscriptions that ended within the churn window.
Churned int
// PlanMix counts live subscriptions per plan, largest first.
PlanMix []PlanCount
}
Metrics are the billing KPIs, computed locally. MRR counts active and past-due subscriptions' licensed items (yearly divided by 12); trials, comps, and metered usage are left out.
func (Metrics) ChurnRateBP ¶
ChurnRateBP is churn over the window in basis points: churned divided by churned plus those still paying.
type MetricsQuery ¶
type MetricsQuery struct {
Now time.Time
// Currency is the currency of MRR; other currencies are left out.
// Empty means USD.
Currency string
// ChurnWindow is how far back churn counts. Zero means 30 days.
ChurnWindow time.Duration
// CreatedBy, when set, leaves out subscriptions created after it, for
// figures as of a past time.
CreatedBy time.Time
}
MetricsQuery anchors Metrics.
type Money ¶
Money is an amount in a currency's minor unit (cents for USD) with an ISO 4217 code in upper case. There are no floats anywhere in tally.
type ObjectType ¶
type ObjectType string
ObjectType is the kind of provider object a webhook event is about.
const ( ObjectSubscription ObjectType = "subscription" ObjectInvoice ObjectType = "invoice" ObjectCheckoutSession ObjectType = "checkout_session" ObjectCustomer ObjectType = "customer" ObjectOther ObjectType = "other" )
The object types the webhook pipeline acts on.
type Option ¶
type Option func(*Service)
Option configures a Service.
func WithDispatcher ¶
func WithDispatcher(d Dispatcher) Option
WithDispatcher processes webhook events in the background.
func WithExemptCheck ¶
func WithExemptCheck(fn func(ctx context.Context, ref BillableRef) bool) Option
WithExemptCheck marks billables (staff, demo accounts) that pass every entitlement check without a subscription.
func WithListener ¶
WithListener adds domain event listeners.
func WithLowBalanceThreshold ¶
WithLowBalanceThreshold sends CreditsLowBalance when a debit takes a billable's credit balance below n. Zero, the default, never sends it.
func WithMaxRefundAmount ¶
WithMaxRefundAmount caps a single refund. Larger refunds return ErrRefundTooLarge. The zero Money means no cap beyond the amount paid.
func WithPastDuePolicy ¶
func WithPastDuePolicy(p PastDuePolicy) Option
WithPastDuePolicy sets whether past-due subscriptions stay valid. The default is PastDueAllow.
type Page ¶
type Page struct {
Limit int
// After is the cursor: the last ID of the previous page.
After string
}
Page asks for one page of a list.
type PastDuePolicy ¶
type PastDuePolicy struct {
// contains filtered or unexported fields
}
PastDuePolicy decides whether a past-due subscription stays valid.
func PastDueAllowFor ¶
func PastDueAllowFor(d time.Duration) PastDuePolicy
PastDueAllowFor keeps a past-due subscription valid for d after it became past due.
func (PastDuePolicy) Grace ¶
func (p PastDuePolicy) Grace() time.Duration
Grace returns the policy's grace period; zero means unbounded when the policy allows.
type Pauser ¶
type Pauser interface {
PauseSubscription(ctx context.Context, subscriptionID string, resumesAt time.Time) (Subscription, error)
UnpauseSubscription(ctx context.Context, subscriptionID string) (Subscription, error)
}
Pauser pauses and resumes collection.
type PaymentFailed ¶
type PaymentFailed struct{ SubscriptionEvent }
PaymentFailed is sent when a subscription becomes past due or unpaid.
func (PaymentFailed) EventName ¶
func (PaymentFailed) EventName() string
EventName implements DomainEvent.
type PaymentMethod ¶
PaymentMethod is a customer's default payment method, for display.
type PaymentMethods ¶
type PaymentMethods interface {
// DefaultPaymentMethod returns nil when the customer has none.
DefaultPaymentMethod(ctx context.Context, customer string) (*PaymentMethod, error)
}
PaymentMethods reads payment methods.
type PlanDef ¶
type PlanDef struct {
Key string
Name string
Description string
Addon bool
Prices []*PriceDef
TrialDays int
Features []string
Limits map[string]int64
MinSeats int64
MaxSeats int64
Popular bool
Hidden bool
// Version is the default version of the plan's prices.
Version int
// contains filtered or unexported fields
}
PlanDef is a plan or an add-on in the catalog.
func Addon ¶
func Addon(key, name string, opts ...PlanOption) *PlanDef
Addon declares an add-on: a plan sold on top of another.
func (*PlanDef) HasFeature ¶
HasFeature reports whether the plan grants feature.
func (*PlanDef) LimitValue ¶
LimitValue returns the plan's limit for key.
func (*PlanDef) MeteredPrices ¶
MeteredPrices returns the current metered prices.
func (*PlanDef) Price ¶
Price returns the current (newest, non-legacy) licensed price for an interval.
func (*PlanDef) SubscribePrices ¶
SubscribePrices returns what a new subscription to the plan gets: the current licensed price for interval, if any, and every current metered price.
type PlanOption ¶
type PlanOption interface {
// contains filtered or unexported methods
}
PlanOption configures a plan.
func Hidden ¶
func Hidden() PlanOption
Hidden keeps the plan out of plan pickers; existing subscribers keep it.
func Limit ¶
func Limit(key string, v int64) PlanOption
Limit sets a numeric entitlement, such as Limit("active_listings", 40).
type PriceDef ¶
type PriceDef struct {
Plan string
Interval Interval
// Amount is the price per period, per seat when PerSeat. Zero for
// metered prices.
Amount Money
PerSeat bool
Metered bool
// MeterKey names a metered price's usage, as passed to ReportUsage.
MeterKey string
// MeterEvent is the provider's meter event name; it defaults to MeterKey.
MeterEvent string
// UnitAmount is the price of one unit of metered usage.
UnitAmount Money
Version int
// Legacy is true when a newer version of the same price exists: the
// price stays active for existing subscribers and is not offered.
Legacy bool
}
PriceDef is one price of a plan in the catalog. Prices are immutable: a new amount is a new Version with a new lookup key, and subscribers on the old version keep it.
func Metered ¶
func Metered(meterKey string, opts ...PriceOption) *PriceDef
Metered adds a monthly usage price for meterKey. Give it PerUnit.
type PriceMapping ¶
type PriceMapping struct {
LookupKey string
Provider ProviderName
ProviderPriceID string
ProviderProductID string
Active bool
}
PriceMapping maps a catalog lookup key to a provider price.
type PriceOption ¶
type PriceOption interface {
// contains filtered or unexported methods
}
PriceOption configures a price.
func PerUnit ¶
func PerUnit(m Money) PriceOption
PerUnit sets a metered price's amount per unit of usage.
type Provider ¶
type Provider interface {
Name() ProviderName
// EnsureCustomer returns the provider customer for b: existing when it
// is set (updating email and name), otherwise a new one.
EnsureCustomer(ctx context.Context, b Billable, existing string) (string, error)
// Checkout starts a hosted checkout. A provider without hosted
// checkout returns ErrUnsupported.
Checkout(ctx context.Context, req ProviderCheckout) (Redirect, error)
// Portal returns the provider's customer portal, or ErrUnsupported.
Portal(ctx context.Context, customer, returnURL string) (Redirect, error)
// Subscription fetches the current state of a subscription.
Subscription(ctx context.Context, id string) (Subscription, error)
// CheckoutSession fetches a checkout's outcome.
CheckoutSession(ctx context.Context, id string) (CheckoutResult, error)
Webhook() WebhookDecoder
}
Provider is the contract every billing provider driver implements. Optional capabilities are separate interfaces, detected with type assertions.
type ProviderCheckout ¶
type ProviderCheckout struct {
Mode CheckoutMode
Customer string
Email string
Items []CheckoutItem
SuccessURL string
CancelURL string
TrialEnd time.Time
AllowPromotionCodes bool
Discounts []Discount
AutomaticTax bool
TaxIDCollection bool
Locale string
ClientReferenceID string
Metadata map[string]string
SubscriptionMetadata map[string]string
IdempotencyKey string
}
ProviderCheckout is what a provider needs to start a checkout.
type ProviderName ¶
type ProviderName string
ProviderName names a billing provider.
const ( ProviderStripe ProviderName = "stripe" ProviderPaddle ProviderName = "paddle" ProviderPolar ProviderName = "polar" ProviderFake ProviderName = "fake" )
The known providers. ProviderFake is tallytest's in-memory provider.
type QuantityChanged ¶
type QuantityChanged struct {
SubscriptionEvent
From, To int64
}
QuantityChanged is sent when the seat count changes.
func (QuantityChanged) EventName ¶
func (QuantityChanged) EventName() string
EventName implements DomainEvent.
type ReconcileReport ¶
type ReconcileReport struct {
// Checked counts local subscriptions re-fetched from the provider.
Checked int
// Created counts provider subscriptions that were missing locally.
Created int
// Events counts the domain events the repairs fired.
Events int
}
ReconcileReport is what Reconcile did.
type RefFunc ¶
type RefFunc func(r *http.Request) (ref BillableRef, ok bool)
RefFunc finds the billable of a request, such as the signed-in user's team. ok is false when there is none.
type RefundRequest ¶
RefundRequest refunds part or all of a paid invoice.
type Refunded ¶
type Refunded struct {
InvoiceEvent
Amount Money
Reason string
// Actor names who issued it.
Actor string
}
Refunded is sent when a refund is issued.
type Refunder ¶
type Refunder interface {
Refund(ctx context.Context, req RefundRequest) (Refund, error)
}
Refunder issues refunds.
type Resolver ¶
type Resolver func(ctx context.Context, ref BillableRef) (Billable, error)
Resolver loads the Billable for a ref. It returns ErrNotFound when there is none.
type Resumed ¶
type Resumed struct{ SubscriptionEvent }
Resumed is sent when a cancellation at period end is undone, or a paused subscription resumes.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the billing API an app calls.
func (*Service) ActiveSubscriptions ¶
func (s *Service) ActiveSubscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)
ActiveSubscriptions returns the billable's valid subscriptions.
func (*Service) Authorize ¶
func (s *Service) Authorize(ctx context.Context, ref BillableRef) error
Authorize checks that the caller in ctx may manage ref's billing. A kind without an Authorizer refuses.
func (*Service) Banner ¶
Banner returns the billing notice for the billable's default subscription, or nil when there is nothing to say.
func (*Service) Can ¶
Can reports whether any plan the billable holds grants feature. Exempt billables can do everything.
func (*Service) Cancel ¶
func (s *Service) Cancel(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
Cancel cancels the subscription at the end of its period; it stays valid on its grace period until then.
func (*Service) CancelNow ¶
func (s *Service) CancelNow(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
CancelNow cancels the subscription at once.
func (*Service) CheckEligible ¶
CheckEligible runs the kind's eligibility check for plan.
func (*Service) Checkout ¶
func (s *Service) Checkout(ctx context.Context, ref BillableRef, req CheckoutRequest) (Redirect, error)
Checkout starts a provider-hosted checkout for the billable and returns where to send the customer.
func (*Service) CreditBalance ¶
CreditBalance is the billable's available credit balance now.
func (*Service) CreditLedger ¶
func (s *Service) CreditLedger(ctx context.Context, ref BillableRef, p Page) ([]CreditEntry, error)
CreditLedger returns a page of the billable's credit entries, newest first.
func (*Service) Current ¶
func (s *Service) Current(ctx context.Context, ref BillableRef, name string) (Subscription, error)
Current returns the billable's newest subscription called name that has not ended, or ErrNoSubscription.
func (*Service) DebitCredits ¶
func (s *Service) DebitCredits(ctx context.Context, ref BillableRef, p CreditDebitParams) (CreditEntry, error)
DebitCredits spends the billable's credits. It fails with ErrInsufficientCredits, recording nothing, when the available balance (unexpired grants less earlier debits) is smaller than Amount. A repeated IdempotencyKey returns the first entry and sends no event.
func (*Service) DecrementQuantity ¶
func (s *Service) DecrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)
DecrementQuantity removes n seats.
func (*Service) DefaultPaymentMethod ¶
func (s *Service) DefaultPaymentMethod(ctx context.Context, ref BillableRef) (*PaymentMethod, error)
DefaultPaymentMethod returns the billable's default payment method, or nil.
func (*Service) DrainUsage ¶
DrainUsage sends up to limit pending usage records to the provider and returns how many it sent. Failed records stay pending with their error.
func (*Service) ExtendTrial ¶
func (s *Service) ExtendTrial(ctx context.Context, ref BillableRef, until time.Time, opts ...CallOption) (Subscription, error)
ExtendTrial moves the trial end of the billable's trialing subscription, or of its generic trial.
func (*Service) GrantComp ¶
func (s *Service) GrantComp(ctx context.Context, ref BillableRef, plan string, until time.Time, actor string) (Subscription, error)
GrantComp gives the billable plan for free until a time: on its current subscription when it has one, otherwise as a local subscription with no provider side. actor is recorded in the metadata.
func (*Service) GrantCredits ¶
func (s *Service) GrantCredits(ctx context.Context, ref BillableRef, p CreditGrantParams) (CreditEntry, error)
GrantCredits adds prepaid credits to the billable. A repeated IdempotencyKey returns the first grant and sends no event.
func (*Service) IncrementQuantity ¶
func (s *Service) IncrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)
IncrementQuantity adds n seats.
func (*Service) Invoices ¶
func (s *Service) Invoices(ctx context.Context, ref BillableRef, limit, offset int) ([]Invoice, int, error)
Invoices returns the billable's invoices from the local mirror, newest first.
func (*Service) Limit ¶
Limit returns the largest value of a limit across the plans the billable holds: 0 when none sets it, Unlimited for exempt billables.
func (*Service) PastDuePolicy ¶
func (s *Service) PastDuePolicy() PastDuePolicy
PastDuePolicy returns the past-due policy.
func (*Service) Pause ¶
func (s *Service) Pause(ctx context.Context, ref BillableRef, resumesAt time.Time, opts ...CallOption) (Subscription, error)
Pause stops collection on the billable's subscription until resumesAt, or until Unpause when resumesAt is zero.
func (*Service) PreviewSwap ¶
func (s *Service) PreviewSwap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (InvoicePreview, error)
PreviewSwap returns the invoice a Swap with the same arguments would produce, such as its proration.
func (*Service) ProcessWebhookEvent ¶
ProcessWebhookEvent applies a stored event: it re-fetches the event's object from the provider, so stale and out-of-order payloads are harmless, mirrors it, fires the domain events, and marks the event processed, all in one transaction. A failure increments Attempts and records LastError. An event already processed is a no-op.
func (*Service) Reconcile ¶
Reconcile repairs drift between the local mirror and the provider: it re-fetches every local subscription that has not ended and, when the provider can list, mirrors provider subscriptions created since that are missing locally. Errors on single subscriptions are joined and the walk goes on.
func (*Service) Refund ¶
func (s *Service) Refund(ctx context.Context, invoiceID string, amount Money, reason, actor string, opts ...CallOption) (Refund, error)
Refund refunds amount of a paid invoice (by local ID), up to what was paid and not yet refunded, and up to WithMaxRefundAmount. actor is recorded on the Refunded event.
func (*Service) ReplayWebhookEvent ¶
ReplayWebhookEvent marks a stored event unprocessed, records who replayed it, and processes it again: through the Dispatcher when there is one, otherwise at once.
func (*Service) ReportUsage ¶
func (s *Service) ReportUsage(ctx context.Context, ref BillableRef, meter string, quantity int64, opts ...CallOption) error
ReportUsage records quantity units of meter in the usage outbox. DrainUsage sends them to the provider. A repeated IdempotencyKey is recorded once.
func (*Service) Resume ¶
func (s *Service) Resume(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
Resume undoes a cancellation at period end while on the grace period.
func (*Service) StartGenericTrial ¶
func (s *Service) StartGenericTrial(ctx context.Context, ref BillableRef, plan string, days int) (GenericTrial, error)
StartGenericTrial starts a cardless trial of plan for days. A billable gets one trial.
func (*Service) Subscribe ¶
func (s *Service) Subscribe(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)
Subscribe creates a subscription with a stored payment method. When the payment needs authentication it returns the incomplete subscription and an *ActionRequired error.
func (*Service) Subscribed ¶
Subscribed reports whether the billable is exempt, has a valid subscription, or is on an active generic trial.
func (*Service) Subscriptions ¶
func (s *Service) Subscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)
Subscriptions returns the billable's subscriptions, newest first.
func (*Service) Swap ¶
func (s *Service) Swap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)
Swap moves the billable's subscription to another plan, keeping the interval unless Billed says otherwise.
func (*Service) SyncCatalog ¶
SyncCatalog makes the provider's products and prices match the catalog and stores the price mappings. With dryRun it only plans.
func (*Service) SyncCheckout ¶
SyncCheckout mirrors the outcome of a finished checkout at once, for the success URL, so the app is correct before the webhook arrives. It returns the zero Subscription for a checkout that made none.
func (*Service) SyncSubscription ¶
SyncSubscription re-fetches one subscription, by local ID, from the provider and mirrors it: Reconcile for a single record.
func (*Service) Unpause ¶
func (s *Service) Unpause(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)
Unpause resumes collection on a paused subscription.
func (*Service) UpdateQuantity ¶
func (s *Service) UpdateQuantity(ctx context.Context, ref BillableRef, qty int64, opts ...CallOption) (Subscription, error)
UpdateQuantity sets the seat count within the plan's bounds.
func (*Service) UsageSummary ¶
func (s *Service) UsageSummary(ctx context.Context, ref BillableRef, meter string, start, end time.Time) (UsageSummary, error)
UsageSummary returns the provider's aggregated usage of meter in [start, end).
func (*Service) WebhookHandler ¶
WebhookHandler returns the provider webhook endpoint. It reads the raw body (413 over MaxWebhookBody), verifies it (400 on failure), stores the event once per (provider, event ID) and hands it to the Dispatcher in the same transaction, then answers 200. A duplicate delivery is a no-op 200. With no Dispatcher the event is processed before answering, and a failure is a 500 so the provider retries.
type Status ¶
type Status string
Status is a subscription's provider status.
const ( StatusIncomplete Status = "incomplete" StatusIncompleteExpired Status = "incomplete_expired" StatusTrialing Status = "trialing" StatusActive Status = "active" StatusPastDue Status = "past_due" StatusUnpaid Status = "unpaid" StatusCanceled Status = "canceled" StatusPaused Status = "paused" )
The subscription statuses.
type Store ¶
type Store interface {
// InTx runs fn in one transaction. tx is the store's transaction value
// (a *nock.Transaction for tally/nock), handed to Dispatcher and
// Listener so they can enqueue jobs atomically. A nested call joins the
// outer transaction.
InTx(ctx context.Context, fn func(ctx context.Context, tx any) error) error
SaveCustomer(ctx context.Context, c *Customer) error
Customer(ctx context.Context, id string) (Customer, error)
CustomerByBillable(ctx context.Context, ref BillableRef, provider ProviderName) (Customer, error)
CustomerByProviderID(ctx context.Context, provider ProviderName, providerID string) (Customer, error)
ListCustomers(ctx context.Context, q CustomerQuery) ([]Customer, int, error)
// SaveSubscription stores the subscription and replaces its items.
SaveSubscription(ctx context.Context, s *Subscription) error
Subscription(ctx context.Context, id string) (Subscription, error)
// SubscriptionByProviderID locks the row for update inside a
// transaction where the database supports it.
SubscriptionByProviderID(ctx context.Context, provider ProviderName, providerID string) (Subscription, error)
// SubscriptionsFor returns the billable's subscriptions, newest first.
SubscriptionsFor(ctx context.Context, ref BillableRef) ([]Subscription, error)
ListSubscriptions(ctx context.Context, q SubscriptionQuery) ([]Subscription, int, error)
SaveInvoice(ctx context.Context, inv *Invoice) error
Invoice(ctx context.Context, id string) (Invoice, error)
InvoiceByProviderID(ctx context.Context, provider ProviderName, providerID string) (Invoice, error)
ListInvoices(ctx context.Context, q InvoiceQuery) ([]Invoice, int, error)
SavePriceMapping(ctx context.Context, m PriceMapping) error
PriceMappings(ctx context.Context, provider ProviderName) ([]PriceMapping, error)
// InsertWebhookEvent stores e unless (Provider, EventID) exists, and
// reports whether it did. Either way e.ID is the stored event's ID.
InsertWebhookEvent(ctx context.Context, e *WebhookEvent) (bool, error)
WebhookEvent(ctx context.Context, id string) (WebhookEvent, error)
// UpdateWebhookEvent stores ProcessedAt, Attempts, LastError and
// ReplayedBy.
UpdateWebhookEvent(ctx context.Context, e WebhookEvent) error
ListWebhookEvents(ctx context.Context, q WebhookEventQuery) ([]WebhookEvent, int, error)
// InsertUsage stores u unless its IdempotencyKey exists, and reports
// whether it did.
InsertUsage(ctx context.Context, u *UsageRecord) (bool, error)
// PendingUsage returns unreported usage, oldest first.
PendingUsage(ctx context.Context, limit int) ([]UsageRecord, error)
// UpdateUsage stores ReportedAt, Attempts and LastError.
UpdateUsage(ctx context.Context, u UsageRecord) error
SaveGenericTrial(ctx context.Context, g GenericTrial) error
GenericTrial(ctx context.Context, ref BillableRef) (GenericTrial, error)
// Metrics computes the dashboard KPIs from local tables only.
Metrics(ctx context.Context, q MetricsQuery) (Metrics, error)
}
Store persists the local billing mirror. Methods called with the ctx that InTx passes to its function run inside that transaction. Lookups return ErrNotFound when there is no record. Save methods insert or update and fill in an empty ID.
type Subscription ¶
type Subscription struct {
ID string
Billable BillableRef
// CustomerID is the local Customer ID.
CustomerID string
// Name tells apart several subscriptions of one billable; usually
// DefaultSubscriptionName.
Name string
Plan string
Provider ProviderName
ProviderID string
ProviderCustomerID string
Status Status
Quantity int64
Items []SubscriptionItem
TrialEndsAt time.Time
// EndsAt is when a subscription canceled at period end stops, or when
// a canceled subscription stopped.
EndsAt time.Time
CurrentPeriodStart time.Time
CurrentPeriodEnd time.Time
CancelAtPeriodEnd bool
CanceledAt time.Time
// PastDueSince is when the subscription last became past due.
PastDueSince time.Time
// CompedUntil grants the plan for free until then.
CompedUntil time.Time
// BillingMode is the provider's billing mode, such as Stripe's
// "flexible".
BillingMode string
Metadata map[string]string
CreatedAt time.Time
UpdatedAt time.Time
}
Subscription is the local mirror of a provider subscription. It changes only from provider state (webhooks, SyncCheckout, Reconcile) and from local comps.
func (*Subscription) Comped ¶
func (s *Subscription) Comped(now time.Time) bool
Comped reports whether a comp covers now.
func (*Subscription) Ended ¶
func (s *Subscription) Ended(now time.Time) bool
Ended reports whether the subscription no longer grants anything at now.
func (*Subscription) Incomplete ¶
func (s *Subscription) Incomplete() bool
Incomplete reports whether the first payment has not succeeded.
func (*Subscription) OnGracePeriod ¶
func (s *Subscription) OnGracePeriod(now time.Time) bool
OnGracePeriod reports whether the subscription was canceled at period end and the period has not ended at now.
func (*Subscription) OnTrial ¶
func (s *Subscription) OnTrial(now time.Time) bool
OnTrial reports whether the trial is running at now.
func (*Subscription) PastDue ¶
func (s *Subscription) PastDue() bool
PastDue reports whether a renewal payment failed: past due, or unpaid after the provider stopped retrying.
func (*Subscription) Recurring ¶
func (s *Subscription) Recurring(now time.Time) bool
Recurring reports whether the subscription will renew: active or on trial, and not canceled at period end.
func (*Subscription) Valid ¶
func (s *Subscription) Valid(now time.Time, policy PastDuePolicy) bool
Valid reports whether the subscription grants its plan at now: comped, on trial, active, on grace, or past due within policy.
type SubscriptionEvent ¶
type SubscriptionEvent struct {
Subscription Subscription
At time.Time
}
SubscriptionEvent is the common part of subscription events.
func (SubscriptionEvent) BillableRef ¶
func (e SubscriptionEvent) BillableRef() BillableRef
BillableRef implements DomainEvent.
type SubscriptionItem ¶
type SubscriptionItem struct {
ID string
ProviderItemID string
PriceLookupKey string
ProviderPriceID string
Quantity int64
Metered bool
// UnitAmount and Interval are the price's, for local revenue metrics.
UnitAmount Money
Interval Interval
}
SubscriptionItem is one price on a subscription.
type SubscriptionLister ¶
type SubscriptionLister interface {
// ListSubscriptionsSince calls fn for every subscription created at or
// after since (all when since is zero), in no particular order.
ListSubscriptionsSince(ctx context.Context, since time.Time, fn func(Subscription) error) error
}
SubscriptionLister walks the provider's subscriptions, for Reconcile.
type SubscriptionManager ¶
type SubscriptionManager interface {
// CreateSubscription returns the created subscription. When the first
// payment needs authentication it returns the incomplete subscription
// and an *ActionRequired error.
CreateSubscription(ctx context.Context, req CreateSubscription) (Subscription, error)
SwapSubscription(ctx context.Context, req SwapRequest) (Subscription, error)
PreviewSwap(ctx context.Context, req SwapRequest) (InvoicePreview, error)
UpdateQuantity(ctx context.Context, subscriptionID string, quantity int64, p Proration, idempotencyKey string) (Subscription, error)
CancelSubscription(ctx context.Context, subscriptionID string, atPeriodEnd bool) (Subscription, error)
ResumeSubscription(ctx context.Context, subscriptionID string) (Subscription, error)
ExtendTrial(ctx context.Context, subscriptionID string, until time.Time) (Subscription, error)
}
SubscriptionManager changes subscriptions without a hosted page.
type SubscriptionPrice ¶
SubscriptionPrice is one price a subscription should carry.
type SubscriptionQuery ¶
type SubscriptionQuery struct {
Status []Status
Lens Lens
Plan string
Billable BillableRef
Search string
Now time.Time
Limit int
Offset int
}
SubscriptionQuery filters ListSubscriptions. Now anchors the time-based lenses. Search matches the customer's email, name, and billable ID, and the plan. Results are newest first.
type SubscriptionStarted ¶
type SubscriptionStarted struct{ SubscriptionEvent }
SubscriptionStarted is sent when a subscription first becomes trialing, active, or past due.
func (SubscriptionStarted) EventName ¶
func (SubscriptionStarted) EventName() string
EventName implements DomainEvent.
type SwapRequest ¶
type SwapRequest struct {
SubscriptionID string
Prices []SubscriptionPrice
Proration Proration
// ResetBillingCycle starts a new period now.
ResetBillingCycle bool
Metadata map[string]string
IdempotencyKey string
}
SwapRequest sets a subscription's prices. Providers keep items whose price is unchanged, update licensed items in place, and replace metered items by adding the new one and removing the old one.
type Swapped ¶
type Swapped struct {
SubscriptionEvent
From, To string
}
Swapped is sent when the plan changes.
type SyncAction ¶
type SyncAction struct {
Kind SyncActionKind
LookupKey string
ProviderPriceID string
}
SyncAction is one step of a catalog sync.
type SyncActionKind ¶
type SyncActionKind string
SyncActionKind is what SyncCatalog does to one price.
const ( SyncCreate SyncActionKind = "create" SyncKeep SyncActionKind = "keep" SyncArchive SyncActionKind = "archive" )
The sync actions.
type SyncOptions ¶
type SyncOptions struct {
// DryRun plans without changing the provider.
DryRun bool
// Existing are the stored mappings; prices mapped there but missing
// from the catalog are archived.
Existing []PriceMapping
}
SyncOptions configure SyncCatalog.
type SyncPlan ¶
type SyncPlan struct {
Actions []SyncAction
Mappings []PriceMapping
}
SyncPlan is a catalog sync's steps and the resulting price mappings.
type TrialWillEnd ¶
type TrialWillEnd struct {
SubscriptionEvent
TrialEndsAt time.Time
}
TrialWillEnd is sent ahead of a trial's end (Stripe: three days before).
func (TrialWillEnd) EventName ¶
func (TrialWillEnd) EventName() string
EventName implements DomainEvent.
type UsageQuery ¶
UsageQuery asks for a customer's usage of a meter in [Start, End).
type UsageRecord ¶
type UsageRecord struct {
ID string
CustomerID string
Billable BillableRef
// Meter is the catalog meter key.
Meter string
Quantity int64
IdempotencyKey string
OccurredAt time.Time
// ReportedAt is zero until the provider accepted the record.
ReportedAt time.Time
Attempts int
LastError string
}
UsageRecord is one metered usage report in the outbox.
type UsageSummary ¶
UsageSummary is aggregated usage.
type WebhookDecoder ¶
type WebhookDecoder interface {
// Decode verifies the signature over the raw body and decodes the
// event. A verification failure wraps ErrBadSignature.
Decode(header http.Header, body []byte) (DecodedEvent, error)
}
WebhookDecoder verifies and decodes a provider webhook request.
type WebhookEvent ¶
type WebhookEvent struct {
ID string
Provider ProviderName
EventID string
Type string
ObjectType ObjectType
ObjectID string
Payload []byte
ReceivedAt time.Time
// ProcessedAt is zero until the event is applied.
ProcessedAt time.Time
Attempts int
LastError string
// ReplayedBy names who last replayed the event by hand.
ReplayedBy string
}
WebhookEvent is one received provider event in the webhook log.
type WebhookEventQuery ¶
type WebhookEventQuery struct {
Provider ProviderName
Type string
// Unprocessed keeps events with no ProcessedAt.
Unprocessed bool
// Failed keeps unprocessed events with a LastError.
Failed bool
Limit int
Offset int
}
WebhookEventQuery filters ListWebhookEvents. Results are newest first.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
nock
module
|
|
|
paddle
module
|
|
|
portal
module
|
|
|
quiver
module
|
|
|
sight
module
|
|
|
stripe
module
|
|
|
Package tallytest is tally's test kit: a settable clock, an in-memory Store, a FakeProvider that implements every capability, signed webhook requests, and the contract suites every provider and store runs.
|
Package tallytest is tally's test kit: a settable clock, an in-memory Store, a FakeProvider that implements every capability, signed webhook requests, and the contract suites every provider and store runs. |