billing

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package billing is the Vortex webhook receiver — the only inbound edge of the billing plane. It verifies Vortex-Signature (HMAC-SHA256 over "{t}.{body}", ±5min tolerance, constant-time compare — the scheme in @vortex/billing/webhooks/signatures.ts) and maps subscription/entitlement lifecycle events onto the org's local plan state. The Use gate reads that state; nothing in the request path talks to Vortex directly.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingHeader  = errors.New("missing Vortex-Signature header")
	ErrInvalidHeader  = errors.New("malformed Vortex-Signature header")
	ErrStaleTimestamp = errors.New("signature timestamp outside tolerance")
	ErrBadSignature   = errors.New("signature mismatch")
)

Functions

func Apply

func Apply(s Store, ev Event) error

Apply maps a verified event to org billing state. Unknown types, missing customers, and malformed payloads are durable no-ops — the endpoint must survive events from Vortex versions newer than this build. Ordering is guarded by the event's createdAt: an event older than the applied state never overwrites it. Events emitted in the same transaction share createdAt (e.g. subscription.created + entitlement.granted from one checkout) — they all apply; re-applying the same plan is an idempotent write with no audit.

func VerifySignature

func VerifySignature(secret, header string, payload []byte, now time.Time) error

VerifySignature checks the Vortex-Signature header against the raw payload. Header form: "t=<ms-epoch>,v1=<hex>" — multiple v1 entries allowed so the platform can rotate secrets without breaking in-flight deliveries.

Types

type AccessAnswer

type AccessAnswer struct {
	Allowed     bool
	State       string
	ReasonCodes []string
}

AccessAnswer is Vortex's verdict on one customer's entitlement key — GET /v1/customers/{customerId}/access?key=<capability>. Allowed is the only field Veil acts on; State/ReasonCodes stay for debugging.

type AccessChecker

type AccessChecker struct {
	Lookuper AccessLookuper
	Key      string        // entitlement key — "veil"
	TTL      time.Duration // cache window; default 60s
	// contains filtered or unexported fields
}

AccessChecker is the deny-path backstop (VEIL-62): when local plan state caps an org, one definitive Vortex answer per TTL decides whether a missed webhook left the plan stale. The webhook is durable truth — this only ever *upgrades* a stale free→active; it never downgrades and never hard-fails: errors and non-answers return false and the local denial stands.

Caching is mandatory, not an optimization: the check sits on a per-request path (denied Use), and a billing outage must not become an auth outage.

func (*AccessChecker) Allowed

func (c *AccessChecker) Allowed(ctx context.Context, orgID, customerID string) bool

Allowed reports whether Vortex currently grants the org's entitlement. Only a definitive allowed=true is true — errors, timeouts, 404s, and explicit denials all return false (callers keep local state). Repeated calls inside TTL serve the cached answer; concurrent misses singleflight to one upstream call per org.

type AccessLookuper

type AccessLookuper interface {
	CheckAccess(ctx context.Context, customerID, key string) (AccessAnswer, error)
}

AccessLookuper is what AccessChecker needs from the Vortex client — the seam tests fake.

type CheckoutIntent

type CheckoutIntent struct {
	OrgID            string
	CustomerID       string
	BillingAccountID string
}

CheckoutIntent is one upgrade-click against the org's billing link.

type Client

type Client struct {
	BaseURL     string
	Key         string
	MerchantID  string
	Environment string // "sandbox" | "production"
	// MeterID + UsageEvent configure usage reporting (VEIL-65); empty MeterID
	// disables the flusher — the webhook receiver works without it.
	MeterID    string
	UsageEvent string
	// PriceID is the paid plan's catalog price (VEIL-67) — the upgrade
	// checkout composes a subscription session against it. Empty disables
	// checkout. SuccessURL/CancelURL are the hosted page's return targets;
	// empty omits them from the request.
	PriceID    string
	SuccessURL string
	CancelURL  string
	HTTP       *http.Client
}

Client is the merchant-scoped Vortex Billing API surface Veil consumes. Wire contract verified against vortex packages/worker: merchant-schemas.ts createBillingCustomerCommandSchema and billingCustomerSnapshotSchema — POST /v1/customers carries environment + merchantAccountId in the body, mutations require Idempotency-Key, and the Bearer is a vp_ merchant key minted at merchant bootstrap (see docs).

func (*Client) CheckAccess

func (c *Client) CheckAccess(ctx context.Context, customerID, key string) (AccessAnswer, error)

CheckAccess asks Vortex whether the customer's key capability is usable — "key=veil" is the paid-plan entitlement. Wire contract: billing package CheckCustomerAccessResponse — {data:{access:{allowed,state,reasonCodes}}}.

func (*Client) CheckoutSession

func (c *Client) CheckoutSession(ctx context.Context, in CheckoutIntent) (string, error)

CheckoutSession mints a hosted subscription checkout and returns the URL. Contract: createCheckoutSessionCommandSchema — mode=subscription requires customerId + billingAccountId + items[priceId]. The idempotency key is fresh per call on purpose: Vortex replays an already-seen key with checkoutUrl:null, which would strand a second upgrade click.

func (*Client) EnsureBillingAccount

func (c *Client) EnsureBillingAccount(ctx context.Context, orgID, customerID string) (string, error)

EnsureBillingAccount returns the org's billing account id — the account usage events post to. Lookup-first like EnsureCustomer: list the customer's accounts, create on miss. Veil provisions api_only + manual collection + no auto-charge: the account binds usage to the customer; collection flips to automatic when a payment profile lands.

func (*Client) EnsureCustomer

func (c *Client) EnsureCustomer(ctx context.Context, orgID string) (string, error)

EnsureCustomer links the org to a billing customer and returns the Vortex customerId. Create collides 409 on an existing customerId — it does not upsert — so ensure is lookup-first: GET ?externalCustomerRef=<org>, create on miss, re-resolve on 409 (the cross-writer race). Idempotency-Key covers transport retries of the same POST, not repeated ensures.

func (*Client) RecordUsage

func (c *Client) RecordUsage(ctx context.Context, d UsageDelta) error

RecordUsage posts one usage event. Contract: createBillingUsageEventCommandSchema — environment + merchantAccountId + customerId + billingAccountId + meterId + eventName + quantity + occurredAt + idempotencyKey, all required.

type Event

type Event struct {
	ID        string          `json:"id"`
	Type      string          `json:"type"`
	CreatedAt int64           `json:"createdAt"` // ms epoch
	Data      json.RawMessage `json:"data"`
}

Event is the Vortex webhook envelope. Data stays raw — each aggregate type decodes its own shape.

type Store

type Store interface {
	Billing(orgID string) (store.OrgBilling, error)
	SetBilling(store.OrgBilling) error
	OrgByBillingCustomer(customerID string) (string, error)
	AppendAudit(protocol.AuditEvent) error
}

Store is the sliver of the vault store the receiver needs.

type UsageDelta

type UsageDelta struct {
	CustomerID       string
	BillingAccountID string
	Quantity         int64
	OccurredAt       time.Time
	IdempotencyKey   string
}

UsageDelta is one flushed usage delta for an org's billing account. IdempotencyKey is deterministic per delta (org + window + watermark) so upstream dedupes retries of the same send.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL