openmeter

package module
v1.0.0-beta.230 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

OpenMeter Go SDK

Go client for the OpenMeter API — usage metering and billing for AI and DevTool companies. This package is generated from the OpenMeter TypeSpec definitions and ships typed request and response models.

[!IMPORTANT] This SDK is a work in progress.

This SDK targets the OpenMeter API v3, a rewrite of the OpenMeter API following AIP (API Improvement Proposal) standardization.

Table of Contents

Installation

go get github.com/openmeterio/openmeter/api/v3/client

Initialization

Create a client with a base URL and an API key. The API key is sent as a Bearer token on every request.

package main

import (
	"log"
	"os"

	"github.com/openmeterio/openmeter/api/v3/client"
)

func main() {
	om, err := openmeter.New(
		"https://openmeter.cloud/api/v3",
		openmeter.WithToken(os.Getenv("OPENMETER_API_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}

	_ = om
}

For region-specific deployments, pass the concrete API base URL for that region to New.

Usage

Every operation is reachable through a namespaced service on the client and returns a typed response plus an error.

package main

import (
	"context"
	"log"
	"os"

	"github.com/openmeterio/openmeter/api/v3/client"
)

func main() {
	om, err := openmeter.New(
		"https://openmeter.cloud/api/v3",
		openmeter.WithToken(os.Getenv("OPENMETER_API_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	meter, err := om.Meters.Create(ctx, openmeter.CreateMeterRequest{
		Name:          "Tokens",
		Key:           "tokens",
		Aggregation:   openmeter.MeterAggregationSum,
		EventType:     "request",
		ValueProperty: openmeter.String("$.tokens"),
	})
	if err != nil {
		log.Fatal(err)
	}

	meters, err := om.Meters.List(ctx, openmeter.MeterListParams{})
	if err != nil {
		log.Fatal(err)
	}

	_, _ = meter, meters
}

Operation arguments follow the generated method signature: path parameters come first, then a typed request body when present, then typed query params when present.

Available Resources and Operations

Operations are grouped by resource and exposed as services on the client. The full call path, HTTP route, and a short description are listed below.

Events
Method HTTP Description
om.Events.List GET /openmeter/events List ingested events.
om.Events.IngestEvent POST /openmeter/events Ingests an event or batch of events following the CloudEvents specification.
om.Events.IngestEvents POST /openmeter/events
om.Events.IngestEventsJSON POST /openmeter/events
Meters
Method HTTP Description
om.Meters.Create POST /openmeter/meters Create a meter.
om.Meters.Get GET /openmeter/meters/{meterId} Get a meter by ID.
om.Meters.List GET /openmeter/meters List meters.
om.Meters.Update PUT /openmeter/meters/{meterId} Update a meter.
om.Meters.Delete DELETE /openmeter/meters/{meterId} Delete a meter.
om.Meters.Query POST /openmeter/meters/{meterId}/query Query a meter for usage. Set Accept: application/json (the default) to get a structured JSON response. Set Accept: text/csv to download the same data as a CSV file suitable for spreadsheets. The CSV columns, in order, are: from, to, [subject,] [customer_id, customer_key, customer_name,] <dimensions...>, value The subject column is emitted only when subject is in the query's group_by_dimensions. The three customer_* columns are emitted together only when customer_id is in the query's group_by_dimensions.
om.Meters.QueryCSV POST /openmeter/meters/{meterId}/query
om.Meters.QueryCSVStream POST /openmeter/meters/{meterId}/query Streaming variant of QueryCSV returning an io.ReadCloser.
Customers
Method HTTP Description
om.Customers.Create POST /openmeter/customers
om.Customers.Get GET /openmeter/customers/{customerId}
om.Customers.List GET /openmeter/customers
om.Customers.Upsert PUT /openmeter/customers/{customerId}
om.Customers.Delete DELETE /openmeter/customers/{customerId}
om.Customers.Billing.Get GET /openmeter/customers/{customerId}/billing
om.Customers.Billing.Update PUT /openmeter/customers/{customerId}/billing
om.Customers.Billing.UpdateAppData PUT /openmeter/customers/{customerId}/billing/app-data
om.Customers.Billing.CreateStripeCheckoutSession POST /openmeter/customers/{customerId}/billing/stripe/checkout-sessions Create a Stripe Checkout Session for the customer. Creates a Checkout Session for collecting payment method information from customers. The session operates in "setup" mode, which collects payment details without charging the customer immediately. The collected payment method can be used for future subscription billing. For hosted checkout sessions, redirect customers to the returned URL. For embedded sessions, use the client_secret to initialize Stripe.js in your application.
om.Customers.Billing.CreateStripePortalSession POST /openmeter/customers/{customerId}/billing/stripe/portal-sessions Create Stripe Customer Portal Session. Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer.
om.Customers.Credits.Grants.Create POST /openmeter/customers/{customerId}/credits/grants Create a new credit grant. A credit grant represents an allocation of prepaid credits to a customer.
om.Customers.Credits.Grants.Get GET /openmeter/customers/{customerId}/credits/grants/{creditGrantId} Get a credit grant.
om.Customers.Credits.Grants.List GET /openmeter/customers/{customerId}/credits/grants List credit grants.
om.Customers.Credits.Grants.UpdateExternalSettlement POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/settlement/external Update the payment settlement status of an externally funded credit grant. Use this endpoint to synchronize the payment state of an external payment with the system so that revenue recognition and credit availability work as expected.
om.Customers.Credits.Balance.Get GET /openmeter/customers/{customerId}/credits/balance Get a credit balance.
om.Customers.Credits.Adjustments.Create POST /openmeter/customers/{customerId}/credits/adjustments A credit adjustment can be used to make manual adjustments to a customer's credit balance. Supported use-cases: - Usage correction
om.Customers.Credits.Transactions.List GET /openmeter/customers/{customerId}/credits/transactions List credit transactions for a customer. Returns an immutable, chronological record of credit movements: funded credits and consumed credits. Transactions are returned in reverse chronological order by default.
om.Customers.Charges.List GET /openmeter/customers/{customerId}/charges List customer charges. Returns the customer's charges that are represented as either flat fee or usage-based charges.
om.Customers.Charges.Create POST /openmeter/customers/{customerId}/charges Create customer charge.
Entitlements
Method HTTP Description
om.Entitlements.ListCustomerAccess GET /openmeter/customers/{customerId}/entitlement-access
Subscriptions
Method HTTP Description
om.Subscriptions.Create POST /openmeter/subscriptions
om.Subscriptions.List GET /openmeter/subscriptions
om.Subscriptions.Get GET /openmeter/subscriptions/{subscriptionId}
om.Subscriptions.Cancel POST /openmeter/subscriptions/{subscriptionId}/cancel Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancelation time.
om.Subscriptions.UnscheduleCancelation POST /openmeter/subscriptions/{subscriptionId}/unschedule-cancelation Unschedules the subscription cancelation.
om.Subscriptions.Change POST /openmeter/subscriptions/{subscriptionId}/change Closes a running subscription and starts a new one according to the specification. Can be used for upgrades, downgrades, and plan changes.
om.Subscriptions.CreateAddon POST /openmeter/subscriptions/{subscriptionId}/addons Add add-on to a subscription.
om.Subscriptions.ListAddons GET /openmeter/subscriptions/{subscriptionId}/addons List the add-ons of a subscription.
om.Subscriptions.GetAddon GET /openmeter/subscriptions/{subscriptionId}/addons/{subscriptionAddonId} Get an add-on association for a subscription.
Apps
Method HTTP Description
om.Apps.List GET /openmeter/apps List installed apps.
om.Apps.Get GET /openmeter/apps/{appId} Get an installed app.
Billing
Method HTTP Description
om.Billing.ListProfiles GET /openmeter/profiles List billing profiles.
om.Billing.CreateProfile POST /openmeter/profiles Create a new billing profile. Billing profiles contain the settings for billing and controls invoice generation. An organization can have multiple billing profiles defined. A billing profile is linked to a specific app. This association is established during the billing profile's creation and remains immutable.
om.Billing.GetProfile GET /openmeter/profiles/{id} Get a billing profile.
om.Billing.UpdateProfile PUT /openmeter/profiles/{id} Update a billing profile.
om.Billing.DeleteProfile DELETE /openmeter/profiles/{id} Delete a billing profile. Only such billing profiles can be deleted that are: - not the default profile - not pinned to any customer using customer overrides - only have finalized invoices
Invoices
Method HTTP Description
om.Invoices.List GET /openmeter/billing/invoices List billing invoices. Returns a page of invoices. Gathering invoices are never included. Use filter to narrow by status, customer, dates, or service period start. Use sort to control ordering.
om.Invoices.Get GET /openmeter/billing/invoices/{invoiceId} Get a billing invoice by ID. Returns the full invoice resource including line items, status details, totals, and workflow configuration snapshot.
om.Invoices.Update PUT /openmeter/billing/invoices/{invoiceId} Update a billing invoice. Only the mutable fields of the invoice can be edited: description, labels, supplier, customer, workflow settings, and top-level lines. Top-level lines are matched by id; lines without an id are created, and existing lines omitted from lines are deleted. Detailed (child) lines are always computed and cannot be edited directly. Only invoices in draft status can be updated.
om.Invoices.Delete DELETE /openmeter/billing/invoices/{invoiceId} Delete a billing invoice. Only standard invoices in draft status can be deleted. Deleting an invoice will also delete all associated line items and workflow configuration.
Tax
Method HTTP Description
om.Tax.CreateCode POST /openmeter/tax-codes
om.Tax.GetCode GET /openmeter/tax-codes/{taxCodeId}
om.Tax.ListCodes GET /openmeter/tax-codes
om.Tax.UpsertCode PUT /openmeter/tax-codes/{taxCodeId}
om.Tax.DeleteCode DELETE /openmeter/tax-codes/{taxCodeId}
Currencies
Method HTTP Description
om.Currencies.List GET /openmeter/currencies List currencies supported by the billing system.
om.Currencies.CreateCustomCurrency POST /openmeter/currencies/custom Create a custom currency. This operation allows defining your own custom currency for billing purposes.
om.Currencies.ListCostBases GET /openmeter/currencies/custom/{currencyId}/cost-bases List cost bases for a currency. For custom currencies, there can be multiple cost bases with different effective_from dates.
om.Currencies.CreateCostBasis POST /openmeter/currencies/custom/{currencyId}/cost-bases Create a cost basis for a currency.
Features
Method HTTP Description
om.Features.List GET /openmeter/features List all features.
om.Features.Create POST /openmeter/features Create a feature.
om.Features.Get GET /openmeter/features/{featureId} Get a feature by id.
om.Features.Update PATCH /openmeter/features/{featureId} Update a feature by id. Currently only the unit_cost field can be updated.
om.Features.Delete DELETE /openmeter/features/{featureId} Delete a feature by id.
om.Features.QueryCost POST /openmeter/features/{featureId}/cost/query Query the cost of a feature.
LLMCost
Method HTTP Description
om.LLMCost.ListPrices GET /openmeter/llm-cost/prices List global LLM cost prices. Returns prices with overrides applied if any.
om.LLMCost.GetPrice GET /openmeter/llm-cost/prices/{priceId} Get a specific LLM cost price by ID. Returns the price with overrides applied if any.
om.LLMCost.ListOverrides GET /openmeter/llm-cost/overrides List per-namespace price overrides.
om.LLMCost.CreateOverride POST /openmeter/llm-cost/overrides Create a per-namespace price override.
om.LLMCost.DeleteOverride DELETE /openmeter/llm-cost/overrides/{priceId} Delete a per-namespace price override.
Plans
Method HTTP Description
om.Plans.List GET /openmeter/plans List all plans.
om.Plans.Create POST /openmeter/plans Create a new plan.
om.Plans.Update PUT /openmeter/plans/{planId} Update a plan by id.
om.Plans.Get GET /openmeter/plans/{planId} Get a plan by id.
om.Plans.Delete DELETE /openmeter/plans/{planId} Delete a plan by id.
om.Plans.Archive POST /openmeter/plans/{planId}/archive Archive a plan version.
om.Plans.Publish POST /openmeter/plans/{planId}/publish Publish a plan version.
Addons
Method HTTP Description
om.Addons.List GET /openmeter/addons List all add-ons.
om.Addons.Create POST /openmeter/addons Create a new add-on.
om.Addons.Update PUT /openmeter/addons/{addonId} Update an add-on by id.
om.Addons.Get GET /openmeter/addons/{addonId} Get add-on by id.
om.Addons.Delete DELETE /openmeter/addons/{addonId} Soft delete add-on by id.
om.Addons.Archive POST /openmeter/addons/{addonId}/archive Archive an add-on version.
om.Addons.Publish POST /openmeter/addons/{addonId}/publish Publish an add-on version.
PlanAddons
Method HTTP Description
om.PlanAddons.List GET /openmeter/plans/{planId}/addons List add-ons associated with a plan.
om.PlanAddons.Create POST /openmeter/plans/{planId}/addons Add an add-on to a plan.
om.PlanAddons.Get GET /openmeter/plans/{planId}/addons/{planAddonId} Get an add-on association for a plan.
om.PlanAddons.Update PUT /openmeter/plans/{planId}/addons/{planAddonId} Update an add-on association for a plan.
om.PlanAddons.Delete DELETE /openmeter/plans/{planId}/addons/{planAddonId} Remove an add-on from a plan.
Defaults
Method HTTP Description
om.Defaults.GetOrganizationTaxCodes GET /openmeter/defaults/tax-codes
om.Defaults.UpdateOrganizationTaxCodes PUT /openmeter/defaults/tax-codes
Governance
Method HTTP Description
om.Governance.QueryAccess POST /openmeter/governance/query Query feature access for a list of customers. The endpoint resolves each provided identifier to a customer and returns the access status for the requested features, plus optional credit balance availability. Designed to be called on a fixed refresh interval and the query response is intended to be cached.

Error Handling

A non-2xx response returns an *APIError carrying the problem-details fields (StatusCode, Status, Type, Title, Detail, Instance) from the response where available. Client-side validation errors such as an empty path ID are returned before any HTTP request is made.

package main

import (
	"context"
	"errors"
	"log"

	"github.com/openmeterio/openmeter/api/v3/client"
)

func main() {
	om, err := openmeter.New("https://openmeter.cloud/api/v3", openmeter.WithToken("om_..."))
	if err != nil {
		log.Fatal(err)
	}

	_, err = om.Meters.Get(context.Background(), "unknown")
	if err != nil {
		var apiErr *openmeter.APIError
		if errors.As(err, &apiErr) {
			log.Printf("%d %s %s", apiErr.StatusCode, apiErr.Title, apiErr.Type)
			return
		}
		log.Fatal(err)
	}
}

Pagination and Streaming

Paginated list operations also emit ListAll helpers that return iter.Seq2[T, error]. Text responses such as meter CSV export emit a byte returning method and a Stream variant for callers that want an io.ReadCloser.

Cursor-paginated responses report their position as Next and Previous on CursorMetaPage. Both are opaque cursor tokens: pass them back verbatim as the page[after] / page[before] query parameters (CursorPageParams.After / CursorPageParams.Before); do not parse or construct them.

Iterating with Before set walks pages backward while the items within each page stay in forward order, so the resulting stream is not globally sorted.

for meter, err := range om.Meters.ListAll(ctx, openmeter.MeterListParams{}) {
	if err != nil {
		log.Fatal(err)
	}
	log.Println(meter.Key)
}

stream, err := om.Meters.QueryCSVStream(ctx, "meter-id", openmeter.MeterQueryRequest{})
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

Documentation

Overview

Package openmeter provides a Go client SDK for the OpenMeter API — usage metering and billing for AI and DevTool companies. It is generated from the OpenMeter TypeSpec definitions and exposes every operation as a method on a typed service hanging off Client (for example Client.Meters), with typed request and response models.

Construct a Client with New, passing the API base URL and a bearer token via WithToken:

om, err := openmeter.New(
	"https://openmeter.cloud/api/v3",
	openmeter.WithToken(os.Getenv("OPENMETER_API_KEY")),
)

Any non-2xx response is returned as an APIError carrying the HTTP status code and the RFC 7807 problem fields; unwrap it with errors.As or AsAPIError. Client-side validation failures such as an empty resource ID are reported before any request is sent and match ErrEmptyID via errors.Is.

Paginated list operations additionally provide ...All variants returning iter.Seq2 sequences that fetch pages lazily and yield each item together with an error.

Index

Constants

This section is empty.

Variables

View Source
var ErrEmptyID = errors.New("openmeter: resource ID must not be empty")

ErrEmptyID is returned by operations that target a single resource when the resource ID is empty. It is caught before any request is made so an omitted ID surfaces as a clear client-side error rather than an ambiguous server response. Match it with errors.Is.

View Source
var Version = resolveVersion()

Version is the SDK version reported in the default User-Agent. When the SDK is consumed as a module dependency it is resolved from the consumer's build info (the module version selected by their go.mod), so tagged releases need no stamping commit. Builds where that is unavailable — the module itself, replace directives, vendored trees without version data — fall back to the sdk-version emitter option ("0.0.0-dev").

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b.

func DecodeAPIError

func DecodeAPIError[T any](err error) (T, bool, error)

DecodeAPIError decodes an API error body into T. The returned boolean is false when err is not an APIError.

func Int

func Int(i int) *int

Int returns a pointer to i.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. It is the generic form covering any type; the typed String/Int/Bool/Time below remain because they let the compiler infer the element type at call sites where a bare literal would not (e.g. String("x") vs Ptr("x"), which are equivalent, but Int(1) avoids Ptr[int](1)).

func String

func String(s string) *string

String returns a pointer to s.

func Time

func Time(t time.Time) *time.Time

Time returns a pointer to t.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status code of the response.
	StatusCode int `json:"-"`

	// Status is the status code echoed in the problem body (usually equal to
	// StatusCode).
	Status int `json:"status"`
	// Title is a short, stable, human-readable summary of the problem.
	Title string `json:"title"`
	// Type is an optional machine-readable error type.
	Type string `json:"type,omitempty"`
	// Detail is a human-readable explanation specific to this occurrence.
	Detail string `json:"detail"`
	// Instance carries the correlation ID, formatted as kong:trace:<id>.
	Instance string `json:"instance"`

	// RawBody is the undecoded response body, always populated.
	RawBody []byte `json:"-"`
}

APIError is returned for any non-2xx API response. It mirrors the API's RFC 7807-style problem body. When the body cannot be parsed as such, Title is left empty and RawBody carries the undecoded payload.

func AsAPIError

func AsAPIError(err error) (*APIError, bool)

AsAPIError returns the APIError inside err, when err came from an API response.

func (*APIError) Decode

func (e *APIError) Decode(out any) error

Decode decodes the original error response body into out.

func (*APIError) Error

func (e *APIError) Error() string

type Addon

type Addon struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// A key is a semi-unique string that is used to identify the add-on. It is used to
	// reference the latest `active` version of the add-on and is unique with the
	// version number.
	Key string `json:"key"`
	// Version of the add-on. Incremented when the add-on is updated.
	Version int64 `json:"version"`
	// The InstanceType of the add-ons. Can be "single" or "multiple".
	InstanceType AddonInstanceType `json:"instance_type"`
	// The currency code of the add-on.
	Currency BillingCurrencyCode `json:"currency"`
	// The date and time when the add-on becomes effective. When not specified, the
	// add-on is a draft.
	EffectiveFrom *time.Time `json:"effective_from,omitempty"`
	// The date and time when the add-on is no longer effective. When not specified,
	// the add-on is effective indefinitely.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
	// The status of the add-on. Computed based on the effective start and end dates:
	//
	// - `draft`: `effective_from` is not set.
	// - `active`: `effective_from <= now` and (`effective_to` is not set or
	// `now < effective_to`).
	// - `archived`: `effective_to <= now`.
	Status AddonStatus `json:"status"`
	// The rate cards of the add-on.
	RateCards []RateCard `json:"rate_cards"`
	// List of validation errors.
	ValidationErrors []ProductCatalogValidationError `json:"validation_errors,omitempty"`
}

Add-on allows extending subscriptions with compatible plans with additional ratecards.

type AddonFilter

type AddonFilter struct {
	ID       *StringExactFilter
	Key      *StringFilter
	Name     *StringFilter
	Status   *StringExactFilter
	Currency *StringExactFilter
}

type AddonInstanceType

type AddonInstanceType string

The instanceType of the add-on.

- `single`: Can be added to a subscription only once. - `multiple`: Can be added to a subscription more than once.

const (
	AddonInstanceTypeSingle   AddonInstanceType = "single"
	AddonInstanceTypeMultiple AddonInstanceType = "multiple"
)

func (AddonInstanceType) Valid

func (value AddonInstanceType) Valid() bool

type AddonListParams

type AddonListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *AddonFilter
}

type AddonPagePaginatedResponse

type AddonPagePaginatedResponse struct {
	Data []Addon       `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type AddonReference

type AddonReference struct {
	ID string `json:"id"`
}

Addon reference.

type AddonStatus

type AddonStatus string

The status of the add-on defined by the `effective_from` and `effective_to` properties.

- `draft`: The add-on has not yet been published and can be edited. - `active`: The add-on is published and available for use. - `archived`: The add-on is no longer available for use.

const (
	AddonStatusDraft    AddonStatus = "draft"
	AddonStatusActive   AddonStatus = "active"
	AddonStatusArchived AddonStatus = "archived"
)

func (AddonStatus) Valid

func (value AddonStatus) Valid() bool

type AddonsService

type AddonsService struct {
	// contains filtered or unexported fields
}

func (*AddonsService) Archive

func (s *AddonsService) Archive(ctx context.Context, addonID string) (*Addon, error)

Archive an add-on version.

func (*AddonsService) Create

func (s *AddonsService) Create(ctx context.Context, request CreateAddonRequest) (*Addon, error)

Create a new add-on.

func (*AddonsService) Delete

func (s *AddonsService) Delete(ctx context.Context, addonID string) error

Soft delete add-on by id.

func (*AddonsService) Get

func (s *AddonsService) Get(ctx context.Context, addonID string) (*Addon, error)

Get add-on by id.

func (*AddonsService) List

List all add-ons.

func (*AddonsService) ListAll

func (s *AddonsService) ListAll(ctx context.Context, params AddonListParams) iter.Seq2[Addon, error]

ListAll returns an iterator over all Addon results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*AddonsService) Publish

func (s *AddonsService) Publish(ctx context.Context, addonID string) (*Addon, error)

Publish an add-on version.

func (*AddonsService) Update

func (s *AddonsService) Update(ctx context.Context, addonID string, request UpsertAddonRequest) (*Addon, error)

Update an add-on by id.

type Address

type Address struct {
	// Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html)
	// alpha-2 format.
	Country *string `json:"country,omitempty"`
	// Postal code.
	PostalCode *string `json:"postal_code,omitempty"`
	// State or province.
	State *string `json:"state,omitempty"`
	// City.
	City *string `json:"city,omitempty"`
	// First line of the address.
	Line1 *string `json:"line1,omitempty"`
	// Second line of the address.
	Line2 *string `json:"line2,omitempty"`
	// Phone number.
	PhoneNumber *string `json:"phone_number,omitempty"`
}

Address

type App

type App struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Installed application.

App is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the AppFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func AppFromAppExternalInvoicing

func AppFromAppExternalInvoicing(value AppExternalInvoicing) (App, error)

func AppFromAppSandbox

func AppFromAppSandbox(value AppSandbox) (App, error)

func AppFromAppStripe

func AppFromAppStripe(value AppStripe) (App, error)

func (App) AsAppExternalInvoicing

func (u App) AsAppExternalInvoicing() (*AppExternalInvoicing, error)

func (App) AsAppSandbox

func (u App) AsAppSandbox() (*AppSandbox, error)

func (App) AsAppStripe

func (u App) AsAppStripe() (*AppStripe, error)

func (App) MarshalJSON

func (u App) MarshalJSON() ([]byte, error)

func (*App) UnmarshalJSON

func (u *App) UnmarshalJSON(data []byte) error

type AppCatalogItem

type AppCatalogItem struct {
	// Type of the app.
	Type AppType `json:"type"`
	// Name of the app.
	Name string `json:"name"`
	// Description of the app.
	Description string `json:"description"`
}

Available apps for billing integrations to connect with third-party services. Apps can have various capabilities like syncing data from or to external systems, integrating with third-party services for tax calculation, delivery of invoices, collection of payments, etc.

type AppCustomerData

type AppCustomerData struct {
	// Used if the customer has a linked Stripe app.
	Stripe *AppCustomerDataStripe `json:"stripe,omitempty"`
	// Used if the customer has a linked external invoicing app.
	ExternalInvoicing *AppCustomerDataExternalInvoicing `json:"external_invoicing,omitempty"`
}

App customer data.

type AppCustomerDataExternalInvoicing

type AppCustomerDataExternalInvoicing struct {
	// Labels for this external invoicing integration on the customer.
	Labels map[string]string `json:"labels,omitempty"`
}

External invoicing customer data.

type AppCustomerDataExternalInvoicingInput

type AppCustomerDataExternalInvoicingInput struct {
	// Labels for this external invoicing integration on the customer.
	Labels *map[string]string `json:"labels,omitempty"`
}

External invoicing customer data.

type AppCustomerDataInput

type AppCustomerDataInput struct {
	// Used if the customer has a linked Stripe app.
	Stripe *AppCustomerDataStripeInput `json:"stripe,omitempty"`
	// Used if the customer has a linked external invoicing app.
	ExternalInvoicing *AppCustomerDataExternalInvoicingInput `json:"external_invoicing,omitempty"`
}

App customer data.

type AppCustomerDataStripe

type AppCustomerDataStripe struct {
	// The Stripe customer ID used.
	CustomerID *string `json:"customer_id,omitempty"`
	// The Stripe default payment method ID.
	DefaultPaymentMethodID *string `json:"default_payment_method_id,omitempty"`
	// Labels for this Stripe integration on the customer.
	Labels map[string]string `json:"labels,omitempty"`
}

Stripe customer data.

type AppCustomerDataStripeInput

type AppCustomerDataStripeInput struct {
	// The Stripe customer ID used.
	CustomerID *string `json:"customer_id,omitempty"`
	// The Stripe default payment method ID.
	DefaultPaymentMethodID *string `json:"default_payment_method_id,omitempty"`
	// Labels for this Stripe integration on the customer.
	Labels *map[string]string `json:"labels,omitempty"`
}

Stripe customer data.

type AppExternalInvoicing

type AppExternalInvoicing struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The app type.
	Type AppType `json:"type"`
	// The app catalog definition that this installed app is based on.
	Definition AppCatalogItem `json:"definition"`
	// Status of the app connection.
	Status AppStatus `json:"status"`
	// Enable draft synchronization hook.
	//
	// When enabled, invoices will pause at the draft state and wait for the
	// integration to call the draft synchronized endpoint before progressing to the
	// issuing state. This allows the external system to validate and prepare the
	// invoice data.
	//
	// When disabled, invoices automatically progress through the draft state based on
	// the configured workflow timing.
	EnableDraftSyncHook bool `json:"enable_draft_sync_hook"`
	// Enable issuing synchronization hook.
	//
	// When enabled, invoices will pause at the issuing state and wait for the
	// integration to call the issuing synchronized endpoint before progressing to the
	// issued state. This ensures the external invoicing system has successfully
	// created and finalized the invoice before it is marked as issued.
	//
	// When disabled, invoices automatically progress through the issuing state and are
	// immediately marked as issued.
	EnableIssuingSyncHook bool `json:"enable_issuing_sync_hook"`
}

External Invoicing app enables integration with third-party invoicing or payment system.

The app supports a bi-directional synchronization pattern where OpenMeter Billing manages the invoice lifecycle while the external system handles invoice presentation and payment collection.

Integration workflow:

1. The billing system creates invoices and transitions them through lifecycle states (draft → issuing → issued) 2. The integration receives webhook notifications about invoice state changes 3. The integration calls back to provide external system IDs and metadata 4. The integration reports payment events back via the payment status API

State synchronization is controlled by hooks that pause invoice progression until the external system confirms synchronization via API callbacks.

type AppListParams

type AppListParams struct {
	Page *PageParams
}

type AppPagePaginatedResponse

type AppPagePaginatedResponse struct {
	Data []App         `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type AppReference

type AppReference struct {
	// The ID of the app.
	ID string `json:"id"`
}

App reference.

type AppSandbox

type AppSandbox struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The app type.
	Type AppType `json:"type"`
	// The app catalog definition that this installed app is based on.
	Definition AppCatalogItem `json:"definition"`
	// Status of the app connection.
	Status AppStatus `json:"status"`
}

Sandbox app can be used for testing billing features.

type AppStatus

type AppStatus string

Connection status of an installed app.

const (
	AppStatusReady        AppStatus = "ready"
	AppStatusUnauthorized AppStatus = "unauthorized"
)

func (AppStatus) Valid

func (value AppStatus) Valid() bool

type AppStripe

type AppStripe struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The app type.
	Type AppType `json:"type"`
	// The app catalog definition that this installed app is based on.
	Definition AppCatalogItem `json:"definition"`
	// Status of the app connection.
	Status AppStatus `json:"status"`
	// The Stripe account ID associated with the connected Stripe account.
	AccountID string `json:"account_id"`
	// Indicates whether the app is connected to a live Stripe account.
	Livemode bool `json:"livemode"`
	// The masked Stripe API key that only exposes the first and last few characters.
	MaskedAPIKey string `json:"masked_api_key"`
}

Stripe app.

type AppStripeCheckoutSessionCustomTextParams

type AppStripeCheckoutSessionCustomTextParams struct {
	// Text displayed after the payment confirmation button.
	AfterSubmit *AppStripeCheckoutSessionCustomTextParamsAfterSubmit `json:"after_submit,omitempty"`
	// Text displayed alongside shipping address collection.
	ShippingAddress *AppStripeCheckoutSessionCustomTextParamsShippingAddress `json:"shipping_address,omitempty"`
	// Text displayed alongside the payment confirmation button.
	Submit *AppStripeCheckoutSessionCustomTextParamsSubmit `json:"submit,omitempty"`
	// Text replacing the default terms of service agreement text.
	TermsOfServiceAcceptance *AppStripeCheckoutSessionCustomTextParamsTermsOfServiceAcceptance `json:"terms_of_service_acceptance,omitempty"`
}

Custom text displayed at various stages of the checkout flow.

type AppStripeCheckoutSessionCustomTextParamsAfterSubmit

type AppStripeCheckoutSessionCustomTextParamsAfterSubmit struct {
	// The custom message text (max 1200 characters).
	Message *string `json:"message,omitempty"`
}

type AppStripeCheckoutSessionCustomTextParamsShippingAddress

type AppStripeCheckoutSessionCustomTextParamsShippingAddress struct {
	// The custom message text (max 1200 characters).
	Message *string `json:"message,omitempty"`
}

type AppStripeCheckoutSessionCustomTextParamsSubmit

type AppStripeCheckoutSessionCustomTextParamsSubmit struct {
	// The custom message text (max 1200 characters).
	Message *string `json:"message,omitempty"`
}

type AppStripeCheckoutSessionCustomTextParamsTermsOfServiceAcceptance

type AppStripeCheckoutSessionCustomTextParamsTermsOfServiceAcceptance struct {
	// The custom message text (max 1200 characters).
	Message *string `json:"message,omitempty"`
}

type AppStripeCheckoutSessionMode

type AppStripeCheckoutSessionMode string

Stripe Checkout Session mode.

Determines the primary purpose of the checkout session.

const (
	AppStripeCheckoutSessionModeSetup AppStripeCheckoutSessionMode = "setup"
)

func (AppStripeCheckoutSessionMode) Valid

func (value AppStripeCheckoutSessionMode) Valid() bool

type AppStripeCheckoutSessionUiMode

type AppStripeCheckoutSessionUiMode string

Checkout Session UI mode.

const (
	AppStripeCheckoutSessionUiModeEmbedded AppStripeCheckoutSessionUiMode = "embedded"
	AppStripeCheckoutSessionUiModeHosted   AppStripeCheckoutSessionUiMode = "hosted"
)

func (AppStripeCheckoutSessionUiMode) Valid

func (value AppStripeCheckoutSessionUiMode) Valid() bool

type AppStripeCreateCheckoutSessionBillingAddressCollection

type AppStripeCreateCheckoutSessionBillingAddressCollection string

Controls whether Checkout collects the customer's billing address.

const (
	AppStripeCreateCheckoutSessionBillingAddressCollectionAuto     AppStripeCreateCheckoutSessionBillingAddressCollection = "auto"
	AppStripeCreateCheckoutSessionBillingAddressCollectionRequired AppStripeCreateCheckoutSessionBillingAddressCollection = "required"
)

func (AppStripeCreateCheckoutSessionBillingAddressCollection) Valid

type AppStripeCreateCheckoutSessionConsentCollection

type AppStripeCreateCheckoutSessionConsentCollection struct {
	// Controls the visibility of payment method reuse agreement.
	PaymentMethodReuseAgreement *AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement `json:"payment_method_reuse_agreement,omitempty"`
	// Enables collection of promotional communication consent.
	//
	// Only available to US merchants. When set to "auto", Checkout determines whether
	// to show the option based on the customer's locale.
	Promotions *AppStripeCreateCheckoutSessionConsentCollectionPromotions `json:"promotions,omitempty"`
	// Requires customers to accept terms of service before payment.
	//
	// Requires a valid terms of service URL in your Stripe Dashboard settings.
	TermsOfService *AppStripeCreateCheckoutSessionConsentCollectionTermsOfService `json:"terms_of_service,omitempty"`
}

Checkout Session consent collection configuration.

type AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement

type AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement struct {
	// Position and visibility of the payment method reuse agreement.
	Position *AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition `json:"position,omitempty"`
}

Payment method reuse agreement configuration.

type AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition

type AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition string

Position of payment method reuse agreement in the UI.

const (
	AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto   AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "auto"
	AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "hidden"
)

func (AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition) Valid

type AppStripeCreateCheckoutSessionConsentCollectionPromotions

type AppStripeCreateCheckoutSessionConsentCollectionPromotions string

Promotional communication consent collection setting.

const (
	AppStripeCreateCheckoutSessionConsentCollectionPromotionsAuto AppStripeCreateCheckoutSessionConsentCollectionPromotions = "auto"
	AppStripeCreateCheckoutSessionConsentCollectionPromotionsNone AppStripeCreateCheckoutSessionConsentCollectionPromotions = "none"
)

func (AppStripeCreateCheckoutSessionConsentCollectionPromotions) Valid

type AppStripeCreateCheckoutSessionConsentCollectionTermsOfService

type AppStripeCreateCheckoutSessionConsentCollectionTermsOfService string

Terms of service acceptance requirement.

const (
	AppStripeCreateCheckoutSessionConsentCollectionTermsOfServiceNone     AppStripeCreateCheckoutSessionConsentCollectionTermsOfService = "none"
	AppStripeCreateCheckoutSessionConsentCollectionTermsOfServiceRequired AppStripeCreateCheckoutSessionConsentCollectionTermsOfService = "required"
)

func (AppStripeCreateCheckoutSessionConsentCollectionTermsOfService) Valid

type AppStripeCreateCheckoutSessionCustomerUpdate

type AppStripeCreateCheckoutSessionCustomerUpdate struct {
	// Whether to save the billing address to customer.address.
	//
	// Defaults to "never".
	Address *AppStripeCreateCheckoutSessionCustomerUpdateBehavior `json:"address,omitempty"`
	// Whether to save the customer name to customer.name.
	//
	// Defaults to "never".
	Name *AppStripeCreateCheckoutSessionCustomerUpdateBehavior `json:"name,omitempty"`
	// Whether to save shipping information to customer.shipping.
	//
	// Defaults to "never".
	Shipping *AppStripeCreateCheckoutSessionCustomerUpdateBehavior `json:"shipping,omitempty"`
}

Controls which customer fields can be updated by the checkout session.

type AppStripeCreateCheckoutSessionCustomerUpdateBehavior

type AppStripeCreateCheckoutSessionCustomerUpdateBehavior string

Behavior for updating customer fields from checkout session.

const (
	AppStripeCreateCheckoutSessionCustomerUpdateBehaviorAuto  AppStripeCreateCheckoutSessionCustomerUpdateBehavior = "auto"
	AppStripeCreateCheckoutSessionCustomerUpdateBehaviorNever AppStripeCreateCheckoutSessionCustomerUpdateBehavior = "never"
)

func (AppStripeCreateCheckoutSessionCustomerUpdateBehavior) Valid

type AppStripeCreateCheckoutSessionRedirectOnCompletion

type AppStripeCreateCheckoutSessionRedirectOnCompletion string

Redirect behavior for embedded checkout sessions.

const (
	AppStripeCreateCheckoutSessionRedirectOnCompletionAlways     AppStripeCreateCheckoutSessionRedirectOnCompletion = "always"
	AppStripeCreateCheckoutSessionRedirectOnCompletionIfRequired AppStripeCreateCheckoutSessionRedirectOnCompletion = "if_required"
	AppStripeCreateCheckoutSessionRedirectOnCompletionNever      AppStripeCreateCheckoutSessionRedirectOnCompletion = "never"
)

func (AppStripeCreateCheckoutSessionRedirectOnCompletion) Valid

type AppStripeCreateCheckoutSessionRequestOptions

type AppStripeCreateCheckoutSessionRequestOptions struct {
	// Whether to collect the customer's billing address.
	//
	// Defaults to auto, which only collects the address when necessary for tax
	// calculation.
	BillingAddressCollection *AppStripeCreateCheckoutSessionBillingAddressCollection `json:"billing_address_collection,omitempty"`
	// URL to redirect customers who cancel the checkout session.
	//
	// Not allowed when ui_mode is "embedded".
	CancelURL *string `json:"cancel_url,omitempty"`
	// Unique reference string for reconciling sessions with internal systems.
	//
	// Can be a customer ID, cart ID, or any other identifier.
	ClientReferenceID *string `json:"client_reference_id,omitempty"`
	// Controls which customer fields can be updated by the checkout session.
	CustomerUpdate *AppStripeCreateCheckoutSessionCustomerUpdate `json:"customer_update,omitempty"`
	// Configuration for collecting customer consent during checkout.
	ConsentCollection *AppStripeCreateCheckoutSessionConsentCollection `json:"consent_collection,omitempty"`
	// Three-letter ISO 4217 currency code in uppercase.
	//
	// Required for payment mode sessions. Optional for setup mode sessions.
	Currency *string `json:"currency,omitempty"`
	// Custom text to display during checkout at various stages.
	CustomText *AppStripeCheckoutSessionCustomTextParams `json:"custom_text,omitempty"`
	// Unix timestamp when the checkout session expires.
	//
	// Can be 30 minutes to 24 hours from creation. Defaults to 24 hours.
	ExpiresAt *int64 `json:"expires_at,omitempty"`
	// IETF language tag for the checkout UI locale.
	//
	// If blank or "auto", uses the browser's locale. Example: "en", "fr", "de".
	Locale *string `json:"locale,omitempty"`
	// Set of key-value pairs to attach to the checkout session.
	//
	// Useful for storing additional structured information.
	Metadata *map[string]string `json:"metadata,omitempty"`
	// Return URL for embedded checkout sessions after payment authentication.
	//
	// Required if ui_mode is "embedded" and redirect-based payment methods are
	// enabled.
	ReturnURL *string `json:"return_url,omitempty"`
	// Success URL to redirect customers after completing payment or setup.
	//
	// Not allowed when ui_mode is "embedded". See:
	// https://docs.stripe.com/payments/checkout/custom-success-page
	SuccessURL *string `json:"success_url,omitempty"`
	// The UI mode for the checkout session.
	//
	// "hosted" displays a Stripe-hosted page. "embedded" integrates directly into your
	// app. Defaults to "hosted".
	UiMode *AppStripeCheckoutSessionUiMode `json:"ui_mode,omitempty"`
	// List of payment method types to enable (e.g., "card", "us_bank_account").
	//
	// If not specified, Stripe enables all relevant payment methods.
	PaymentMethodTypes *[]string `json:"payment_method_types,omitempty"`
	// Redirect behavior for embedded checkout sessions.
	//
	// Controls when to redirect users after completion. See:
	// https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form
	RedirectOnCompletion *AppStripeCreateCheckoutSessionRedirectOnCompletion `json:"redirect_on_completion,omitempty"`
	// Configuration for collecting tax IDs during checkout.
	TaxIDCollection *AppStripeCreateCheckoutSessionTaxIDCollection `json:"tax_id_collection,omitempty"`
}

Configuration options for creating a Stripe Checkout Session.

Based on Stripe's [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create).

type AppStripeCreateCheckoutSessionResult

type AppStripeCreateCheckoutSessionResult struct {
	// The customer ID in the billing system.
	CustomerID string `json:"customer_id"`
	// The Stripe customer ID.
	StripeCustomerID string `json:"stripe_customer_id"`
	// The Stripe checkout session ID.
	SessionID string `json:"session_id"`
	// The setup intent ID created for collecting the payment method.
	SetupIntentID string `json:"setup_intent_id"`
	// Client secret for initializing Stripe.js on the client side.
	//
	// Required for embedded checkout sessions. See:
	// https://docs.stripe.com/payments/checkout/custom-success-page
	ClientSecret *string `json:"client_secret,omitempty"`
	// The client reference ID provided in the request.
	//
	// Useful for reconciling the session with your internal systems.
	ClientReferenceID *string `json:"client_reference_id,omitempty"`
	// Customer's email address if provided to Stripe.
	CustomerEmail *string `json:"customer_email,omitempty"`
	// Currency code for the checkout session.
	Currency *string `json:"currency,omitempty"`
	// Timestamp when the checkout session was created.
	CreatedAt time.Time `json:"created_at"`
	// Timestamp when the checkout session will expire.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// Metadata attached to the checkout session.
	Metadata map[string]string `json:"metadata,omitempty"`
	// The status of the checkout session.
	//
	// See:
	// https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status
	Status *string `json:"status,omitempty"`
	// URL to redirect customers to the checkout page (for hosted mode).
	URL *string `json:"url,omitempty"`
	// Mode of the checkout session.
	//
	// Currently only "setup" mode is supported for collecting payment methods.
	Mode AppStripeCheckoutSessionMode `json:"mode"`
	// The cancel URL where customers are redirected if they cancel.
	CancelURL *string `json:"cancel_url,omitempty"`
	// The success URL where customers are redirected after completion.
	SuccessURL *string `json:"success_url,omitempty"`
	// The return URL for embedded sessions after authentication.
	ReturnURL *string `json:"return_url,omitempty"`
}

Result of creating a Stripe Checkout Session.

Contains all the information needed to redirect customers to the checkout or initialize an embedded checkout flow.

type AppStripeCreateCheckoutSessionTaxIDCollection

type AppStripeCreateCheckoutSessionTaxIDCollection struct {
	// Enable tax ID collection during checkout.
	//
	// Defaults to false.
	Enabled *bool `json:"enabled,omitempty"`
	// Whether tax ID collection is required.
	//
	// Defaults to "never".
	Required *AppStripeCreateCheckoutSessionTaxIDCollectionRequired `json:"required,omitempty"`
}

Tax ID collection configuration for checkout sessions.

type AppStripeCreateCheckoutSessionTaxIDCollectionRequired

type AppStripeCreateCheckoutSessionTaxIDCollectionRequired string

Tax ID collection requirement level.

const (
	AppStripeCreateCheckoutSessionTaxIDCollectionRequiredIfSupported AppStripeCreateCheckoutSessionTaxIDCollectionRequired = "if_supported"
	AppStripeCreateCheckoutSessionTaxIDCollectionRequiredNever       AppStripeCreateCheckoutSessionTaxIDCollectionRequired = "never"
)

func (AppStripeCreateCheckoutSessionTaxIDCollectionRequired) Valid

type AppStripeCreateCustomerPortalSessionOptions

type AppStripeCreateCustomerPortalSessionOptions struct {
	// The ID of an existing
	// [Stripe configuration](https://docs.stripe.com/api/customer_portal/configurations)
	// to use for this session, describing its functionality and features. If not
	// specified, the session uses the default configuration.
	ConfigurationID *string `json:"configuration_id,omitempty"`
	// The IETF
	// [language tag](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale)
	// of the locale customer portal is displayed in. If blank or `auto`, the
	// customer's preferred_locales or browser's locale is used.
	Locale *string `json:"locale,omitempty"`
	// The
	// [URL to redirect](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url)
	// the customer to after they have completed their requested actions.
	ReturnURL *string `json:"return_url,omitempty"`
}

Request to create a Stripe Customer Portal Session.

type AppStripeCreateCustomerPortalSessionResult

type AppStripeCreateCustomerPortalSessionResult struct {
	// The ID of the customer portal session.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id
	ID string `json:"id"`
	// The ID of the stripe customer.
	StripeCustomerID string `json:"stripe_customer_id"`
	// Configuration used to customize the customer portal.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration
	ConfigurationID string `json:"configuration_id"`
	// Livemode.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode
	Livemode bool `json:"livemode"`
	// Created at.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created
	CreatedAt time.Time `json:"created_at"`
	// Return URL.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url
	ReturnURL string `json:"return_url"`
	// The IETF language tag of the locale customer portal is displayed in.
	//
	// See:
	// https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale
	Locale string `json:"locale"`
	// The URL to redirect the customer to after they have completed their requested
	// actions.
	URL string `json:"url"`
}

Result of creating a [Stripe Customer Portal Session](https://docs.stripe.com/api/customer_portal/sessions/object).

Contains all the information needed to redirect the customer to the Stripe Customer Portal.

type AppType

type AppType string

The type of the app.

const (
	AppTypeSandbox           AppType = "sandbox"
	AppTypeStripe            AppType = "stripe"
	AppTypeExternalInvoicing AppType = "external_invoicing"
)

func (AppType) Valid

func (value AppType) Valid() bool

type AppsService

type AppsService struct {
	// contains filtered or unexported fields
}

func (*AppsService) Get

func (s *AppsService) Get(ctx context.Context, appID string) (*App, error)

Get an installed app.

func (*AppsService) List

List installed apps.

func (*AppsService) ListAll

func (s *AppsService) ListAll(ctx context.Context, params AppListParams) iter.Seq2[App, error]

ListAll returns an iterator over all App results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

type BillingCurrencyCode

type BillingCurrencyCode string

Fiat or custom currency code.

type BillingCustomerReference

type BillingCustomerReference struct {
	// The ID of the customer.
	ID string `json:"id"`
}

Customer reference.

type BillingService

type BillingService struct {
	// contains filtered or unexported fields
}

func (*BillingService) CreateProfile

func (s *BillingService) CreateProfile(ctx context.Context, request CreateBillingProfileRequest) (*Profile, error)

Create a new billing profile.

Billing profiles contain the settings for billing and controls invoice generation. An organization can have multiple billing profiles defined. A billing profile is linked to a specific app. This association is established during the billing profile's creation and remains immutable.

func (*BillingService) DeleteProfile

func (s *BillingService) DeleteProfile(ctx context.Context, id string) error

Delete a billing profile.

Only such billing profiles can be deleted that are:

- not the default profile - not pinned to any customer using customer overrides - only have finalized invoices

func (*BillingService) GetProfile

func (s *BillingService) GetProfile(ctx context.Context, id string) (*Profile, error)

Get a billing profile.

func (*BillingService) ListProfiles

List billing profiles.

func (*BillingService) ListProfilesAll

func (s *BillingService) ListProfilesAll(ctx context.Context, params ProfileListParams) iter.Seq2[Profile, error]

ListProfilesAll returns an iterator over all Profile results, fetching pages of ListProfiles transparently. Iteration stops at the first error, which is yielded as the second value.

func (*BillingService) UpdateProfile

func (s *BillingService) UpdateProfile(ctx context.Context, id string, request UpsertBillingProfileRequest) (*Profile, error)

Update a billing profile.

type BillingSubscription

type BillingSubscription struct {
	ID     string            `json:"id"`
	Labels map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The customer ID of the subscription.
	CustomerID string `json:"customer_id"`
	// The plan ID of the subscription. Set if subscription is created from a plan.
	PlanID *string `json:"plan_id,omitempty"`
	// A billing anchor is the fixed point in time that determines the subscription's
	// recurring billing cycle. It affects when charges occur and how prorations are
	// calculated. Common anchors:
	//
	// - Calendar month (1st of each month): `2025-01-01T00:00:00Z`
	// - Subscription anniversary (day customer signed up)
	// - Custom date (customer-specified day)
	BillingAnchor time.Time `json:"billing_anchor"`
	// The status of the subscription.
	Status SubscriptionStatus `json:"status"`
	// Settlement mode for billing.
	//
	// Values:
	//
	// - `credit_then_invoice`: Credits are applied first, then any remainder is
	// invoiced.
	// - `credit_only`: Usage is settled exclusively against credits.
	SettlementMode *SettlementMode `json:"settlement_mode,omitempty"`
}

Subscription.

type BillingSubscriptionFilter

type BillingSubscriptionFilter struct {
	ID         *StringExactFilter
	CustomerID *StringExactFilter
	Status     *StringExactFilter
	PlanID     *StringExactFilter
	PlanKey    *StringExactFilter
}

type BillingSubscriptionListParams

type BillingSubscriptionListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *BillingSubscriptionFilter
}

type BooleanFilter

type BooleanFilter struct {
	Eq *bool
}

BooleanFilter expresses equality for a boolean field.

type Charge

type Charge struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Customer charge.

Charge is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the ChargeFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func ChargeFromChargeFlatFee

func ChargeFromChargeFlatFee(value ChargeFlatFee) (Charge, error)

func ChargeFromChargeUsageBased

func ChargeFromChargeUsageBased(value ChargeUsageBased) (Charge, error)

func (Charge) AsChargeFlatFee

func (u Charge) AsChargeFlatFee() (*ChargeFlatFee, error)

func (Charge) AsChargeUsageBased

func (u Charge) AsChargeUsageBased() (*ChargeUsageBased, error)

func (Charge) MarshalJSON

func (u Charge) MarshalJSON() ([]byte, error)

func (*Charge) UnmarshalJSON

func (u *Charge) UnmarshalJSON(data []byte) error

type ChargeFilter

type ChargeFilter struct {
	// Filter charges by status.
	//
	// Supported statuses are:
	//
	// - `created`
	// - `active`
	// - `final`
	// - `deleted`
	//
	// If omitted, all statuses are returned except for `deleted`.
	Status *StringExactFilter
}

type ChargeFlatFee

type ChargeFlatFee struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The type of the charge.
	Type ChargeType `json:"type"`
	// The customer owning the charge.
	Customer BillingCustomerReference `json:"customer"`
	// Indicates whether the charge lifecycle is controlled by OpenMeter or manually
	// overridden by the API user.
	LifecycleController LifecycleController `json:"lifecycle_controller"`
	// The subscription that originated the charge, when the charge was created from a
	// subscription item.
	Subscription *SubscriptionReference `json:"subscription,omitempty"`
	// The currency of the charge.
	Currency string `json:"currency"`
	// The lifecycle status of the charge.
	Status ChargeStatus `json:"status"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// The full, unprorated service period of the charge.
	FullServicePeriod ClosedPeriod `json:"full_service_period"`
	// The billing period the charge belongs to.
	BillingPeriod ClosedPeriod `json:"billing_period"`
	// The earliest time when the charge should be advanced again by background
	// processing.
	AdvanceAfter *time.Time `json:"advance_after,omitempty"`
	// Unique reference ID of the charge.
	UniqueReferenceID *string `json:"unique_reference_id,omitempty"`
	// Settlement mode of the charge.
	SettlementMode SettlementMode `json:"settlement_mode"`
	// Tax configuration of the charge.
	TaxConfig *TaxConfig `json:"tax_config,omitempty"`
	// Payment term of the flat fee charge.
	PaymentTerm PricePaymentTerm `json:"payment_term"`
	// The discounts applied to the charge.
	Discounts *ChargeFlatFeeDiscounts `json:"discounts,omitempty"`
	// The feature associated with the charge, when applicable.
	FeatureKey *string `json:"feature_key,omitempty"`
	// The proration configuration of the charge.
	ProrationConfiguration RateCardProrationConfiguration `json:"proration_configuration"`
	// The amount after proration of the charge.
	AmountAfterProration CurrencyAmount `json:"amount_after_proration"`
	// The price of the charge.
	Price Price `json:"price"`
	// Current intent from the system lifecycle controller for a charge that has an
	// active manual override. The top-level charge fields remain the effective
	// customer-facing intent.
	SystemIntent *ChargeFlatFeeSystemIntent `json:"system_intent,omitempty"`
}

A flat fee charge for a customer.

type ChargeFlatFeeDiscounts

type ChargeFlatFeeDiscounts struct {
	// Percentage discount applied to the price (0–100).
	Percentage *float64 `json:"percentage,omitempty"`
}

Discounts applicable to flat fee charges.

This is the same as `ProductCatalog.Discounts` but without the `usage` field, which is not applicable to flat fee charges.

type ChargeFlatFeeSystemIntent

type ChargeFlatFeeSystemIntent struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// The full, unprorated service period of the charge.
	FullServicePeriod ClosedPeriod `json:"full_service_period"`
	// The billing period the charge belongs to.
	BillingPeriod ClosedPeriod `json:"billing_period"`
	// Payment term of the flat fee charge.
	PaymentTerm PricePaymentTerm `json:"payment_term"`
	// The discounts applied to the charge.
	Discounts *ChargeFlatFeeDiscounts `json:"discounts,omitempty"`
	// The proration configuration of the charge.
	ProrationConfiguration RateCardProrationConfiguration `json:"proration_configuration"`
	// The amount before proration of the system lifecycle controller flat fee intent.
	AmountBeforeProration CurrencyAmount `json:"amount_before_proration"`
	// The timestamp when the system lifecycle controller intent was deleted. The
	// effective charge can remain visible while a manual override is active.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

Flat fee intent fields from the system lifecycle controller shadowed by a manual override.

type ChargeListParams

type ChargeListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *ChargeFilter
	Expand []ChargesExpand
}

type ChargePagePaginatedResponse

type ChargePagePaginatedResponse struct {
	Data []Charge      `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type ChargeReference

type ChargeReference struct {
	// Unique identifier for the charge.
	ID string `json:"id"`
}

Reference to a charge associated with an invoice line.

type ChargeStatus

type ChargeStatus string

Lifecycle status of a charge.

Values:

- `created`: The charge has been created but is not active yet. - `active`: The charge is active. - `final`: The charge is fully finalized and no further changes are expected. - `deleted`: The charge has been deleted.

const (
	ChargeStatusCreated ChargeStatus = "created"
	ChargeStatusActive  ChargeStatus = "active"
	ChargeStatusFinal   ChargeStatus = "final"
	ChargeStatusDeleted ChargeStatus = "deleted"
)

func (ChargeStatus) Valid

func (value ChargeStatus) Valid() bool

type ChargeTotals

type ChargeTotals struct {
	// The amount of the charge already booked to the internal accounting system.
	Booked Totals `json:"booked"`
	// The realtime amount of the charge.
	//
	// Requires the `realtime_usage` expand.
	Realtime *Totals `json:"realtime,omitempty"`
}

The totals of a change.

RealTime is only expanded when the `real_time_usage` expand is used.

type ChargeType

type ChargeType string

Type of a charge.

Values:

- `flat_fee`: A fixed-amount charge. - `usage_based`: A usage-priced charge.

const (
	ChargeTypeFlatFee    ChargeType = "flat_fee"
	ChargeTypeUsageBased ChargeType = "usage_based"
)

func (ChargeType) Valid

func (value ChargeType) Valid() bool

type ChargeUsageBased

type ChargeUsageBased struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The type of the charge.
	Type ChargeType `json:"type"`
	// The customer owning the charge.
	Customer BillingCustomerReference `json:"customer"`
	// Indicates whether the charge lifecycle is controlled by OpenMeter or manually
	// overridden by the API user.
	LifecycleController LifecycleController `json:"lifecycle_controller"`
	// The subscription that originated the charge, when the charge was created from a
	// subscription item.
	Subscription *SubscriptionReference `json:"subscription,omitempty"`
	// The currency of the charge.
	Currency string `json:"currency"`
	// The lifecycle status of the charge.
	Status ChargeStatus `json:"status"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// The full, unprorated service period of the charge.
	FullServicePeriod ClosedPeriod `json:"full_service_period"`
	// The billing period the charge belongs to.
	BillingPeriod ClosedPeriod `json:"billing_period"`
	// The earliest time when the charge should be advanced again by background
	// processing.
	AdvanceAfter *time.Time `json:"advance_after,omitempty"`
	// Unique reference ID of the charge.
	UniqueReferenceID *string `json:"unique_reference_id,omitempty"`
	// Settlement mode of the charge.
	SettlementMode SettlementMode `json:"settlement_mode"`
	// Tax configuration of the charge.
	TaxConfig *TaxConfig `json:"tax_config,omitempty"`
	// Discounts applied to the usage-based charge.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
	// The feature associated with the charge.
	FeatureKey string `json:"feature_key"`
	// Aggregated booked and realtime totals for the charge.
	Totals ChargeTotals `json:"totals"`
	// The price of the charge.
	Price Price `json:"price"`
	// Current intent from the system lifecycle controller for a charge that has an
	// active manual override. The top-level charge fields remain the effective
	// customer-facing intent.
	SystemIntent *ChargeUsageBasedSystemIntent `json:"system_intent,omitempty"`
}

A usage-based charge for a customer.

type ChargeUsageBasedSystemIntent

type ChargeUsageBasedSystemIntent struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// The full, unprorated service period of the charge.
	FullServicePeriod ClosedPeriod `json:"full_service_period"`
	// The billing period the charge belongs to.
	BillingPeriod ClosedPeriod `json:"billing_period"`
	// Discounts applied to the usage-based charge.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
	// The price of the charge.
	Price Price `json:"price"`
	// The timestamp when the system lifecycle controller intent was deleted. The
	// effective charge can remain visible while a manual override is active.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

Usage-based intent fields from the system lifecycle controller shadowed by a manual override.

type ChargesExpand

type ChargesExpand string

Expands for customer charges.

Values:

- `real_time_usage`: The charge's real-time usage.

const (
	ChargesExpandRealTimeUsage ChargesExpand = "real_time_usage"
)

func (ChargesExpand) Valid

func (value ChargesExpand) Valid() bool

type Client

type Client struct {
	Events        *EventsService
	Meters        *MetersService
	Customers     *CustomersService
	Entitlements  *EntitlementsService
	Subscriptions *SubscriptionsService
	Apps          *AppsService
	Billing       *BillingService
	Invoices      *InvoicesService
	Tax           *TaxService
	Currencies    *CurrenciesService
	Features      *FeaturesService
	LLMCost       *LLMCostService
	Plans         *PlansService
	Addons        *AddonsService
	PlanAddons    *PlanAddonsService
	Defaults      *DefaultsService
	Governance    *GovernanceService
	// contains filtered or unexported fields
}

func New

func New(baseURL string, opts ...Option) (*Client, error)

type ClosedPeriod

type ClosedPeriod struct {
	// The start of the period.
	//
	// The period is inclusive at the start.
	From time.Time `json:"from"`
	// The end of the period.
	//
	// The period is exclusive at the end.
	To time.Time `json:"to"`
}

A period with defined start and end dates.

The period is always inclusive at the start and exclusive at the end.

type CollectionAlignment

type CollectionAlignment string

BillingCollectionAlignment specifies when the pending line items should be collected into an invoice.

const (
	CollectionAlignmentSubscription CollectionAlignment = "subscription"
	CollectionAlignmentAnchored     CollectionAlignment = "anchored"
)

func (CollectionAlignment) Valid

func (value CollectionAlignment) Valid() bool

type CollectionMethod

type CollectionMethod string

Collection method specifies how the invoice should be collected (automatic or manual).

const (
	CollectionMethodChargeAutomatically CollectionMethod = "charge_automatically"
	CollectionMethodSendInvoice         CollectionMethod = "send_invoice"
)

func (CollectionMethod) Valid

func (value CollectionMethod) Valid() bool

type CostBasis

type CostBasis struct {
	ID string `json:"id"`
	// The fiat currency code for the cost basis.
	FiatCode string `json:"fiat_code"`
	// The cost rate for the currency.
	Rate Numeric `json:"rate"`
	// An ISO-8601 timestamp representation of the date from which the cost basis is
	// effective. If not provided, it will be effective immediately and will be set to
	// `now` by the system.
	EffectiveFrom *time.Time `json:"effective_from,omitempty"`
	// An ISO-8601 timestamp representation of the date until which the cost basis is
	// effective. If provided, it must be later than `effective_from`. If not provided,
	// it remains effective until superseded.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
}

Describes currency basis supported by billing system.

type CostBasisFilter

type CostBasisFilter struct {
	// Filter cost bases by fiat currency code.
	FiatCode *string
}

type CostBasisListParams

type CostBasisListParams struct {
	Filter *CostBasisFilter
	Page   *PageParams
}

type CostBasisPagePaginatedResponse

type CostBasisPagePaginatedResponse struct {
	Data []CostBasis   `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type CreateAddonRequest

type CreateAddonRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// A key is a semi-unique string that is used to identify the add-on. It is used to
	// reference the latest `active` version of the add-on and is unique with the
	// version number.
	Key string `json:"key"`
	// The InstanceType of the add-ons. Can be "single" or "multiple".
	InstanceType AddonInstanceType `json:"instance_type"`
	// The currency code of the add-on.
	Currency BillingCurrencyCode `json:"currency"`
	// The rate cards of the add-on.
	RateCards []RateCardInput `json:"rate_cards"`
}

Addon create request.

type CreateBillingProfileRequest

type CreateBillingProfileRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The name and contact information for the supplier this billing profile
	// represents
	Supplier Party `json:"supplier"`
	// The billing workflow settings for this profile
	Workflow Workflow `json:"workflow"`
	// The applications used by this billing profile.
	Apps ProfileAppReferences `json:"apps"`
	// Whether this is the default profile.
	Default bool `json:"default"`
}

BillingProfile create request.

type CreateChargeFlatFeeRequest

type CreateChargeFlatFeeRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The type of the charge.
	Type ChargeType `json:"type"`
	// The currency of the charge.
	Currency string `json:"currency"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// Unique reference ID of the charge.
	UniqueReferenceID *string `json:"unique_reference_id,omitempty"`
	// Settlement mode of the charge.
	SettlementMode SettlementMode `json:"settlement_mode"`
	// Tax configuration of the charge.
	TaxConfig *TaxConfig `json:"tax_config,omitempty"`
	// Payment term of the flat fee charge.
	PaymentTerm PricePaymentTerm `json:"payment_term"`
	// The discounts applied to the charge.
	Discounts *ChargeFlatFeeDiscounts `json:"discounts,omitempty"`
	// The feature associated with the charge, when applicable.
	FeatureKey *string `json:"feature_key,omitempty"`
	// The proration configuration of the charge.
	ProrationConfiguration RateCardProrationConfiguration `json:"proration_configuration"`
	// The amount before proration of the charge.
	AmountBeforeProration CurrencyAmount `json:"amount_before_proration"`
	// The full, unprorated service period of the charge.
	FullServicePeriod *ClosedPeriod `json:"full_service_period,omitempty"`
	// The billing period the charge belongs to.
	BillingPeriod *ClosedPeriod `json:"billing_period,omitempty"`
}

Flat fee charge create request.

type CreateChargeRequest

type CreateChargeRequest struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Customer charge.

CreateChargeRequest is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the CreateChargeRequestFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func CreateChargeRequestFromCreateChargeFlatFeeRequest

func CreateChargeRequestFromCreateChargeFlatFeeRequest(value CreateChargeFlatFeeRequest) (CreateChargeRequest, error)

func CreateChargeRequestFromCreateChargeUsageBasedRequest

func CreateChargeRequestFromCreateChargeUsageBasedRequest(value CreateChargeUsageBasedRequest) (CreateChargeRequest, error)

func (CreateChargeRequest) AsCreateChargeFlatFeeRequest

func (u CreateChargeRequest) AsCreateChargeFlatFeeRequest() (*CreateChargeFlatFeeRequest, error)

func (CreateChargeRequest) AsCreateChargeUsageBasedRequest

func (u CreateChargeRequest) AsCreateChargeUsageBasedRequest() (*CreateChargeUsageBasedRequest, error)

func (CreateChargeRequest) MarshalJSON

func (u CreateChargeRequest) MarshalJSON() ([]byte, error)

func (*CreateChargeRequest) UnmarshalJSON

func (u *CreateChargeRequest) UnmarshalJSON(data []byte) error

type CreateChargeUsageBasedRequest

type CreateChargeUsageBasedRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The type of the charge.
	Type ChargeType `json:"type"`
	// The currency of the charge.
	Currency string `json:"currency"`
	// The timestamp when the charge is intended to be invoiced.
	InvoiceAt time.Time `json:"invoice_at"`
	// The effective service period covered by the charge.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// Unique reference ID of the charge.
	UniqueReferenceID *string `json:"unique_reference_id,omitempty"`
	// Settlement mode of the charge.
	SettlementMode SettlementMode `json:"settlement_mode"`
	// Tax configuration of the charge.
	TaxConfig *TaxConfig `json:"tax_config,omitempty"`
	// Discounts applied to the usage-based charge.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
	// The feature associated with the charge.
	FeatureKey string `json:"feature_key"`
	// The price of the charge.
	Price Price `json:"price"`
	// The full, unprorated service period of the charge.
	FullServicePeriod *ClosedPeriod `json:"full_service_period,omitempty"`
	// The billing period the charge belongs to.
	BillingPeriod *ClosedPeriod `json:"billing_period,omitempty"`
}

Usage-based charge create request.

type CreateCostBasisRequest

type CreateCostBasisRequest struct {
	// The fiat currency code for the cost basis.
	FiatCode string `json:"fiat_code"`
	// The cost rate for the currency.
	Rate Numeric `json:"rate"`
	// An ISO-8601 timestamp representation of the date from which the cost basis is
	// effective. If not provided, it will be effective immediately and will be set to
	// `now` by the system.
	EffectiveFrom *time.Time `json:"effective_from,omitempty"`
	// An ISO-8601 timestamp representation of the date until which the cost basis is
	// effective. If provided, it must be later than `effective_from`. If not provided,
	// it remains effective until superseded.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
}

CostBasis create request.

type CreateCreditAdjustmentRequest

type CreateCreditAdjustmentRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The currency of the granted credits.
	Currency BillingCurrencyCode `json:"currency"`
	// Granted credit amount.
	Amount Numeric `json:"amount"`
}

CreditAdjustment create request.

type CreateCreditGrantFilters

type CreateCreditGrantFilters struct {
	// Limit the credit grant to specific features. If no features are specified, the
	// credit grant can be used for any feature.
	Features *[]string `json:"features,omitempty"`
}

Filters for the credit grant.

type CreateCreditGrantPurchase

type CreateCreditGrantPurchase struct {
	// Currency of the purchase amount.
	Currency string `json:"currency"`
	// Cost basis per credit unit used to calculate the purchase amount.
	//
	// If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge
	// is $50.00. The value must be greater than 0. If the cost basis is 0, use
	// `funding_method=none` instead.
	//
	// Defaults to 1.0.
	PerUnitCostBasis *Numeric `json:"per_unit_cost_basis,omitempty"`
	// Controls when credits become available for consumption.
	//
	// Defaults to `on_creation`.
	AvailabilityPolicy *CreditAvailabilityPolicy `json:"availability_policy,omitempty"`
}

Purchase and payment terms of the grant.

type CreateCreditGrantRequest

type CreateCreditGrantRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Funding method of the grant.
	FundingMethod CreditFundingMethod `json:"funding_method"`
	// The currency of the granted credits.
	Currency BillingCurrencyCode `json:"currency"`
	// Granted credit amount.
	Amount Numeric `json:"amount"`
	// Present when a funding workflow applies (funding_method is not `none`).
	Purchase *CreateCreditGrantPurchase `json:"purchase,omitempty"`
	// Tax configuration for the grant.
	//
	// For `invoice` and `external` funding methods, tax configuration should be
	// provided to ensure correct revenue recognition. When not provided, the default
	// credit grant tax code is applied, if that's not set the global default taxcode
	// is used.
	TaxConfig *CreditGrantTaxConfig     `json:"tax_config,omitempty"`
	Filters   *CreateCreditGrantFilters `json:"filters,omitempty"`
	// Draw-down priority of the grant. Lower values have higher priority.
	Priority *int16 `json:"priority,omitempty"`
	// The timestamp when the credit grant becomes effective.
	//
	// Defaults to the current date and time.
	EffectiveAt *time.Time `json:"effective_at,omitempty"`
	// The duration after which the credit grant expires.
	//
	// Defaults to never expiring.
	ExpiresAfter *string `json:"expires_after,omitempty"`
	// Idempotency key for the credit grant creation request.
	//
	// When provided, reusing the same key returns an HTTP 409 Conflict instead of
	// creating a duplicate grant, which makes create requests safe to retry.
	Key *string `json:"key,omitempty"`
}

CreditGrant create request.

type CreateCurrencyCustomRequest

type CreateCurrencyCustomRequest struct {
	// The name of the currency. It should be a human-readable string that represents
	// the name of the currency, such as "US Dollar" or "Euro".
	Name string `json:"name"`
	// The symbol of the currency. It should be a string that represents the symbol of
	// the currency, such as "$" for US Dollar or "€" for Euro.
	Symbol *string `json:"symbol,omitempty"`
	Code   string  `json:"code"`
}

CurrencyCustom create request.

type CreateCustomerRequest

type CreateCustomerRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// Mapping to attribute metered usage to the customer by the event subject.
	UsageAttribution *CustomerUsageAttribution `json:"usage_attribution,omitempty"`
	// The primary email address of the customer.
	PrimaryEmail *string `json:"primary_email,omitempty"`
	// Currency of the customer. Used for billing, tax and invoicing.
	Currency *string `json:"currency,omitempty"`
	// The billing address of the customer. Used for tax and invoicing.
	BillingAddress *Address `json:"billing_address,omitempty"`
}

Customer create request.

type CreateFeatureRequest

type CreateFeatureRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// The meter that the feature is associated with and based on which usage is
	// calculated. If not specified, the feature is static.
	Meter *FeatureMeterReferenceInput `json:"meter,omitempty"`
	// Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or
	// "llm" to look up cost from the LLM cost database based on meter group-by
	// properties.
	UnitCost *FeatureUnitCost `json:"unit_cost,omitempty"`
}

Feature create request.

type CreateMeterRequest

type CreateMeterRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// The aggregation type to use for the meter.
	Aggregation MeterAggregation `json:"aggregation"`
	// The event type to include in the aggregation.
	EventType string `json:"event_type"`
	// The date since the meter should include events. Useful to skip old events. If
	// not specified, all historical events are included.
	EventsFrom *time.Time `json:"events_from,omitempty"`
	// JSONPath expression to extract the value from the ingested event's data
	// property.
	//
	// The ingested value for sum, avg, min, and max aggregations is a number or a
	// string that can be parsed to a number.
	//
	// For unique_count aggregation, the ingested value must be a string. For count
	// aggregation the value_property is ignored.
	ValueProperty *string `json:"value_property,omitempty"`
	// Named JSONPath expressions to extract the group by values from the event data.
	//
	// Keys must be unique and consist only alphanumeric and underscore characters.
	Dimensions *map[string]string `json:"dimensions,omitempty"`
}

Meter create request.

type CreatePlanAddonRequest

type CreatePlanAddonRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The add-on associated with the plan.
	Addon AddonReference `json:"addon"`
	// The key of the plan phase from which the add-on becomes available for purchase.
	FromPlanPhase string `json:"from_plan_phase"`
	// The maximum number of times the add-on can be purchased for the plan. For
	// single-instance add-ons this field must be omitted. For multi-instance add-ons
	// when omitted, unlimited quantity can be purchased.
	MaxQuantity *int64 `json:"max_quantity,omitempty"`
}

PlanAddon create request.

type CreatePlanRequest

type CreatePlanRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// A key is a semi-unique string that is used to identify the plan. It is used to
	// reference the latest `active` version of the plan and is unique with the version
	// number.
	Key string `json:"key"`
	// The currency code of the plan.
	Currency string `json:"currency"`
	// The billing cadence for subscriptions using this plan.
	BillingCadence string `json:"billing_cadence"`
	// Whether pro-rating is enabled for this plan.
	ProRatingEnabled *bool `json:"pro_rating_enabled,omitempty"`
	// The plan phases define the pricing ramp for a subscription. A phase switch
	// occurs only at the end of a billing period. At least one phase is required.
	Phases []PlanPhaseInput `json:"phases"`
}

Plan create request.

type CreateSubscriptionAddonRequest

type CreateSubscriptionAddonRequest struct {
	Labels *map[string]string `json:"labels,omitempty"`
	// The add-on associated with the subscription.
	Addon AddonReference `json:"addon"`
	// The quantity of the add-on. Always 1 for single instance add-ons.
	Quantity int64 `json:"quantity"`
	// The timing of the operation. After the create or update, a new entry will be
	// created in the timeline.
	Timing SubscriptionEditTiming `json:"timing"`
}

SubscriptionAddon create request.

type CreateTaxCodeRequest

type CreateTaxCodeRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// Mapping of app types to tax codes.
	AppMappings []TaxCodeAppMapping `json:"app_mappings"`
}

TaxCode create request.

type CreditAdjustment

type CreditAdjustment struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
}

A credit adjustment can be used to make manual adjustments to a customer's credit balance.

Supported use-cases:

- Usage correction

type CreditAvailabilityPolicy

type CreditAvailabilityPolicy string

When credits become available for consumption.

- `on_creation`: Credits are available as soon as the grant is created. - `on_authorization`: Credits are available once the payment is authorized. - `on_settlement`: Credits are available once the payment is settled.

const (
	CreditAvailabilityPolicyOnCreation CreditAvailabilityPolicy = "on_creation"
)

func (CreditAvailabilityPolicy) Valid

func (value CreditAvailabilityPolicy) Valid() bool

type CreditBalance

type CreditBalance struct {
	Currency BillingCurrencyCode `json:"currency"`
	// Credits available after applying currently live charge impacts.
	Live Numeric `json:"live"`
	// Credits that have been booked on the ledger as of the balance timestamp.
	Settled Numeric `json:"settled"`
	// Credits that have been granted but are not yet written to the ledger, or are
	// written to the ledger with a future booked time.
	Pending Numeric `json:"pending"`
}

The credit balance by currency.

type CreditBalances

type CreditBalances struct {
	// The timestamp of the balance retrieval.
	RetrievedAt time.Time `json:"retrieved_at"`
	// The balances by currencies.
	Balances []CreditBalance `json:"balances"`
}

The balances of the credits of a customer.

type CreditFundingMethod

type CreditFundingMethod string

The funding method describes how the grant is funded.

- `none`: No funding workflow applies, for example promotional grants - `invoice`: The grant is funded by an in-system invoice flow - `external`: The grant is funded outside the system (e.g., wire transfer, external invoice, or manual reconciliation)

const (
	CreditFundingMethodNone     CreditFundingMethod = "none"
	CreditFundingMethodInvoice  CreditFundingMethod = "invoice"
	CreditFundingMethodExternal CreditFundingMethod = "external"
)

func (CreditFundingMethod) Valid

func (value CreditFundingMethod) Valid() bool

type CreditGrant

type CreditGrant struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// Funding method of the grant.
	FundingMethod CreditFundingMethod `json:"funding_method"`
	// The currency of the granted credits.
	Currency BillingCurrencyCode `json:"currency"`
	// Granted credit amount.
	Amount Numeric `json:"amount"`
	// Present when a funding workflow applies (funding_method is not `none`).
	Purchase *CreditGrantPurchase `json:"purchase,omitempty"`
	// Tax configuration for the grant.
	//
	// For `invoice` and `external` funding methods, tax configuration should be
	// provided to ensure correct revenue recognition. When not provided, the default
	// credit grant tax code is applied, if that's not set the global default taxcode
	// is used.
	TaxConfig *CreditGrantTaxConfig `json:"tax_config,omitempty"`
	// Available when `funding_method` is `invoice`.
	Invoice *CreditGrantInvoiceReference `json:"invoice,omitempty"`
	Filters *CreditGrantFilters          `json:"filters,omitempty"`
	// Draw-down priority of the grant. Lower values have higher priority.
	Priority *int16 `json:"priority,omitempty"`
	// The timestamp when the credit grant becomes effective.
	//
	// Defaults to the current date and time.
	EffectiveAt *time.Time `json:"effective_at,omitempty"`
	// Idempotency key for the credit grant creation request.
	//
	// When provided, reusing the same key returns an HTTP 409 Conflict instead of
	// creating a duplicate grant, which makes create requests safe to retry.
	Key *string `json:"key,omitempty"`
	// The timestamp when the credit grant expires.
	//
	// Calculated from the grant effective time and `expires_after` if provided.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// Timestamp when the grant was voided.
	VoidedAt *time.Time `json:"voided_at,omitempty"`
	// Current lifecycle status of the grant.
	Status CreditGrantStatus `json:"status"`
}

A credit grant allocates credits to a customer.

Credits are drawn down against charges according to the settlement mode configured on the rate card.

type CreditGrantFilter

type CreditGrantFilter struct {
	// Filter credit grants by status.
	Status *CreditGrantStatus
	// Filter credit grants by currency.
	Currency *string
	// Filter credit grants by key.
	Key *StringFilter
}

type CreditGrantFilters

type CreditGrantFilters struct {
	// Limit the credit grant to specific features. If no features are specified, the
	// credit grant can be used for any feature.
	Features []string `json:"features,omitempty"`
}

Filters for the credit grant.

type CreditGrantInvoiceReference

type CreditGrantInvoiceReference struct {
	// Identifier of the invoice associated with the grant.
	ID *string `json:"id,omitempty"`
	// Identifier of the invoice line associated with the grant.
	Line *CreditGrantInvoiceReferenceLine `json:"line,omitempty"`
}

Invoice references for the grant.

type CreditGrantInvoiceReferenceLine

type CreditGrantInvoiceReferenceLine struct {
	ID string `json:"id"`
}

type CreditGrantListParams

type CreditGrantListParams struct {
	Page   *PageParams
	Filter *CreditGrantFilter
}

type CreditGrantPagePaginatedResponse

type CreditGrantPagePaginatedResponse struct {
	Data []CreditGrant `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type CreditGrantPurchase

type CreditGrantPurchase struct {
	// Currency of the purchase amount.
	Currency string `json:"currency"`
	// Cost basis per credit unit used to calculate the purchase amount.
	//
	// If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge
	// is $50.00. The value must be greater than 0. If the cost basis is 0, use
	// `funding_method=none` instead.
	//
	// Defaults to 1.0.
	PerUnitCostBasis *Numeric `json:"per_unit_cost_basis,omitempty"`
	// The purchase amount. Calculated from `per_unit_cost_basis` and credit `amount`.
	Amount Numeric `json:"amount"`
	// Controls when credits become available for consumption.
	//
	// Defaults to `on_creation`.
	AvailabilityPolicy *CreditAvailabilityPolicy `json:"availability_policy,omitempty"`
	// Current payment settlement status.
	SettlementStatus *CreditPurchasePaymentSettlementStatus `json:"settlement_status,omitempty"`
}

Purchase and payment terms of the grant.

type CreditGrantStatus

type CreditGrantStatus string

Credit grant lifecycle status.

- `pending`: The credit block has been created but is not yet valid. (`effective_at` is in the future or availability_policy is not met) - `active`: The credit block is currently valid and eligible for consumption. (`effective_at` is in the past, `expires_at` is in the future and availability_policy is met) - `expired`: The credit block expired with remaining unused balance, `expires_at` time has passed. - `voided`: The credit block was voided. Remaining balance is forfeited.

const (
	CreditGrantStatusPending CreditGrantStatus = "pending"
	CreditGrantStatusActive  CreditGrantStatus = "active"
	CreditGrantStatusExpired CreditGrantStatus = "expired"
	CreditGrantStatusVoided  CreditGrantStatus = "voided"
)

func (CreditGrantStatus) Valid

func (value CreditGrantStatus) Valid() bool

type CreditGrantTaxConfig

type CreditGrantTaxConfig struct {
	// Tax behavior applied to the invoice line item.
	Behavior *TaxBehavior `json:"behavior,omitempty"`
	// Tax code applied to the invoice line item.
	TaxCode *TaxCodeReference `json:"tax_code,omitempty"`
}

Tax configuration for a credit grant.

Tax configuration should be provided to ensure correct revenue recognition, including for externally funded grants.

type CreditPurchasePaymentSettlementStatus

type CreditPurchasePaymentSettlementStatus string

Credit purchase payment settlement status.

- `pending`: Payment has been initiated and is not yet authorized. - `authorized`: Payment has been authorized. - `settled`: Payment has been settled.

const (
	CreditPurchasePaymentSettlementStatusPending    CreditPurchasePaymentSettlementStatus = "pending"
	CreditPurchasePaymentSettlementStatusAuthorized CreditPurchasePaymentSettlementStatus = "authorized"
	CreditPurchasePaymentSettlementStatusSettled    CreditPurchasePaymentSettlementStatus = "settled"
)

func (CreditPurchasePaymentSettlementStatus) Valid

type CreditTransaction

type CreditTransaction struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// The date and time the transaction was booked.
	BookedAt time.Time `json:"booked_at"`
	// The type of credit transaction.
	Type CreditTransactionType `json:"type"`
	// Currency of the balance affected by the transaction.
	Currency BillingCurrencyCode `json:"currency"`
	// Signed amount of the credit movement. Positive values add balance, negative
	// values reduce balance.
	Amount Numeric `json:"amount"`
	// The available balance before and after the transaction.
	AvailableBalance CreditTransactionAvailableBalance `json:"available_balance"`
}

A credit transaction represents a single credit movement on the customer's balance.

Credit transactions are immutable.

type CreditTransactionAvailableBalance

type CreditTransactionAvailableBalance struct {
	Before Numeric `json:"before"`
	After  Numeric `json:"after"`
}

type CreditTransactionFilter

type CreditTransactionFilter struct {
	// Filter credit transactions by type.
	Type *CreditTransactionType
	// Filter credit transactions by currency.
	Currency *BillingCurrencyCode
	// Filter credit transactions by feature key. Omit to return all credit
	// transactions. Use `exists=false` to return only unrestricted credit
	// transactions.
	FeatureKey *StringFilter
}

type CreditTransactionListParams

type CreditTransactionListParams struct {
	Page   *CursorPageParams
	Filter *CreditTransactionFilter
}

type CreditTransactionPaginatedResponse

type CreditTransactionPaginatedResponse struct {
	Data []CreditTransaction `json:"data"`
	Meta CursorMeta          `json:"meta"`
}

Cursor paginated response.

type CreditTransactionType

type CreditTransactionType string

The type of the credit transaction.

- `funded`: Credit granted and available for consumption. - `consumed`: Credit consumed by usage or fees. - `expired`: Credit removed because it expired before being used.

const (
	CreditTransactionTypeFunded   CreditTransactionType = "funded"
	CreditTransactionTypeConsumed CreditTransactionType = "consumed"
	CreditTransactionTypeExpired  CreditTransactionType = "expired"
)

func (CreditTransactionType) Valid

func (value CreditTransactionType) Valid() bool

type CurrenciesService

type CurrenciesService struct {
	// contains filtered or unexported fields
}

func (*CurrenciesService) CreateCostBasis

func (s *CurrenciesService) CreateCostBasis(ctx context.Context, currencyID string, request CreateCostBasisRequest) (*CostBasis, error)

Create a cost basis for a currency.

func (*CurrenciesService) CreateCustomCurrency

func (s *CurrenciesService) CreateCustomCurrency(ctx context.Context, request CreateCurrencyCustomRequest) (*CurrencyCustom, error)

Create a custom currency. This operation allows defining your own custom currency for billing purposes.

func (*CurrenciesService) List

List currencies supported by the billing system.

func (*CurrenciesService) ListAll

ListAll returns an iterator over all Currency results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*CurrenciesService) ListCostBases

func (s *CurrenciesService) ListCostBases(ctx context.Context, currencyID string, params CostBasisListParams) (*CostBasisPagePaginatedResponse, error)

List cost bases for a currency. For custom currencies, there can be multiple cost bases with different `effective_from` dates.

func (*CurrenciesService) ListCostBasesAll

func (s *CurrenciesService) ListCostBasesAll(ctx context.Context, currencyID string, params CostBasisListParams) iter.Seq2[CostBasis, error]

ListCostBasesAll returns an iterator over all CostBasis results, fetching pages of ListCostBases transparently. Iteration stops at the first error, which is yielded as the second value.

type Currency

type Currency struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Fiat or custom currency.

Currency is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the CurrencyFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func CurrencyFromCurrencyCustom

func CurrencyFromCurrencyCustom(value CurrencyCustom) (Currency, error)

func CurrencyFromCurrencyFiat

func CurrencyFromCurrencyFiat(value CurrencyFiat) (Currency, error)

func (Currency) AsCurrencyCustom

func (u Currency) AsCurrencyCustom() (*CurrencyCustom, error)

func (Currency) AsCurrencyFiat

func (u Currency) AsCurrencyFiat() (*CurrencyFiat, error)

func (Currency) MarshalJSON

func (u Currency) MarshalJSON() ([]byte, error)

func (*Currency) UnmarshalJSON

func (u *Currency) UnmarshalJSON(data []byte) error

type CurrencyAmount

type CurrencyAmount struct {
	Amount   Numeric `json:"amount"`
	Currency string  `json:"currency"`
}

Monetary amount in a specific currency.

type CurrencyCustom

type CurrencyCustom struct {
	// The type of the currency.
	Type CurrencyType `json:"type"`
	// The name of the currency. It should be a human-readable string that represents
	// the name of the currency, such as "US Dollar" or "Euro".
	Name string `json:"name"`
	// The symbol of the currency. It should be a string that represents the symbol of
	// the currency, such as "$" for US Dollar or "€" for Euro.
	Symbol *string `json:"symbol,omitempty"`
	ID     string  `json:"id"`
	Code   string  `json:"code"`
	// An ISO-8601 timestamp representation of the custom currency creation date.
	CreatedAt time.Time `json:"created_at"`
}

Describes custom currency.

type CurrencyFiat

type CurrencyFiat struct {
	// The type of the currency.
	Type CurrencyType `json:"type"`
	// The name of the currency. It should be a human-readable string that represents
	// the name of the currency, such as "US Dollar" or "Euro".
	Name string `json:"name"`
	// The symbol of the currency. It should be a string that represents the symbol of
	// the currency, such as "$" for US Dollar or "€" for Euro.
	Symbol *string `json:"symbol,omitempty"`
	Code   string  `json:"code"`
}

Currency describes a currency supported by the billing system.

type CurrencyFilter

type CurrencyFilter struct {
	Type *CurrencyType
	Code *StringFilter
}

type CurrencyListParams

type CurrencyListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *CurrencyFilter
}

type CurrencyPagePaginatedResponse

type CurrencyPagePaginatedResponse struct {
	Data []Currency    `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type CurrencyType

type CurrencyType string

Currency type for custom currencies. It should be a unique code but not conflicting with any existing standard currency codes.

const (
	CurrencyTypeFiat   CurrencyType = "fiat"
	CurrencyTypeCustom CurrencyType = "custom"
)

func (CurrencyType) Valid

func (value CurrencyType) Valid() bool

type CursorMeta

type CursorMeta struct {
	// Page metadata.
	Page CursorMetaPage `json:"page"`
}

Cursor pagination metadata.

type CursorMetaPage

type CursorMetaPage struct {
	// URI to the first page.
	First *string `json:"first,omitempty"`
	// URI to the last page.
	Last *string `json:"last,omitempty"`
	// URI to the next page.
	Next *string `json:"next,omitempty"`
	// URI to the previous page.
	Previous *string `json:"previous,omitempty"`
	// Requested page size.
	Size *int64 `json:"size,omitempty"`
}

Cursor pagination metadata.

type CursorPageParams

type CursorPageParams struct {
	Size   *int
	After  *string
	Before *string
}

CursorPageParams selects a cursor page.

type CursorPaginationQueryPage

type CursorPaginationQueryPage struct {
	// The number of items to include per page.
	Size *int64 `json:"size,omitempty"`
	// Request the next page of data, starting with the item after this parameter.
	After *string `json:"after,omitempty"`
	// Request the previous page of data, starting with the item before this parameter.
	Before *string `json:"before,omitempty"`
}

Determines which page of the collection to retrieve.

type Customer

type Customer struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	Key       string     `json:"key"`
	// Mapping to attribute metered usage to the customer by the event subject.
	UsageAttribution *CustomerUsageAttribution `json:"usage_attribution,omitempty"`
	// The primary email address of the customer.
	PrimaryEmail *string `json:"primary_email,omitempty"`
	// Currency of the customer. Used for billing, tax and invoicing.
	Currency *string `json:"currency,omitempty"`
	// The billing address of the customer. Used for tax and invoicing.
	BillingAddress *Address `json:"billing_address,omitempty"`
}

Customers can be individuals or organizations that can subscribe to plans and have access to features.

type CustomerData

type CustomerData struct {
	// The billing profile for the customer.
	//
	// If not provided, the default billing profile will be used.
	BillingProfile *ProfileReference `json:"billing_profile,omitempty"`
	// App customer data.
	AppData *AppCustomerData `json:"app_data,omitempty"`
}

Billing customer data.

type CustomerFilter

type CustomerFilter struct {
	Key                        *StringFilter
	Name                       *StringFilter
	PrimaryEmail               *StringFilter
	UsageAttributionSubjectKey *StringFilter
	PlanKey                    *StringFilter
	BillingProfileID           *StringExactFilter
}

type CustomerListParams

type CustomerListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *CustomerFilter
}

type CustomerPagePaginatedResponse

type CustomerPagePaginatedResponse struct {
	Data []Customer    `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type CustomerReference

type CustomerReference struct {
	ID string `json:"id"`
}

Customer reference.

type CustomerStripeCreateCheckoutSessionRequest

type CustomerStripeCreateCheckoutSessionRequest struct {
	// Options for configuring the Stripe Checkout Session.
	//
	// These options are passed directly to Stripe's
	// [checkout session creation API](https://docs.stripe.com/api/checkout/sessions/create).
	StripeOptions AppStripeCreateCheckoutSessionRequestOptions `json:"stripe_options"`
}

Request to create a Stripe Checkout Session for the customer.

Checkout Sessions are used to collect payment method information from customers in a secure, Stripe-hosted interface. This integration uses setup mode to collect payment methods that can be charged later for subscription billing.

type CustomerStripeCreateCustomerPortalSessionRequest

type CustomerStripeCreateCustomerPortalSessionRequest struct {
	// Options for configuring the Stripe Customer Portal Session.
	StripeOptions AppStripeCreateCustomerPortalSessionOptions `json:"stripe_options"`
}

Request to create a Stripe Customer Portal Session for the customer.

Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer.

type CustomerUsageAttribution

type CustomerUsageAttribution struct {
	// The subjects that are attributed to the customer. Can be empty when no usage
	// event subjects are associated with the customer.
	SubjectKeys []string `json:"subject_keys"`
}

Mapping to attribute metered usage to the customer. One customer can have zero or more subjects, but one subject can only belong to one customer.

type CustomersBillingService

type CustomersBillingService struct {
	// contains filtered or unexported fields
}

func (*CustomersBillingService) CreateStripeCheckoutSession

Create a [Stripe Checkout Session](https://docs.stripe.com/payments/checkout) for the customer.

Creates a Checkout Session for collecting payment method information from customers. The session operates in "setup" mode, which collects payment details without charging the customer immediately. The collected payment method can be used for future subscription billing.

For hosted checkout sessions, redirect customers to the returned URL. For embedded sessions, use the client_secret to initialize Stripe.js in your application.

func (*CustomersBillingService) CreateStripePortalSession

Create Stripe Customer Portal Session.

Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer.

func (*CustomersBillingService) Get

func (s *CustomersBillingService) Get(ctx context.Context, customerID string) (*CustomerData, error)

func (*CustomersBillingService) Update

func (*CustomersBillingService) UpdateAppData

func (s *CustomersBillingService) UpdateAppData(ctx context.Context, customerID string, request UpsertAppCustomerDataRequest) (*AppCustomerData, error)

type CustomersChargesService

type CustomersChargesService struct {
	// contains filtered or unexported fields
}

func (*CustomersChargesService) Create

func (s *CustomersChargesService) Create(ctx context.Context, customerID string, request CreateChargeRequest) (*Charge, error)

Create customer charge.

func (*CustomersChargesService) List

List customer charges.

Returns the customer's charges that are represented as either flat fee or usage-based charges.

func (*CustomersChargesService) ListAll

func (s *CustomersChargesService) ListAll(ctx context.Context, customerID string, params ChargeListParams) iter.Seq2[Charge, error]

ListAll returns an iterator over all Charge results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

type CustomersCreditsAdjustmentsService

type CustomersCreditsAdjustmentsService struct {
	// contains filtered or unexported fields
}

func (*CustomersCreditsAdjustmentsService) Create

A credit adjustment can be used to make manual adjustments to a customer's credit balance.

Supported use-cases:

- Usage correction

type CustomersCreditsBalanceService

type CustomersCreditsBalanceService struct {
	// contains filtered or unexported fields
}

func (*CustomersCreditsBalanceService) Get

Get a credit balance.

type CustomersCreditsGrantsService

type CustomersCreditsGrantsService struct {
	// contains filtered or unexported fields
}

func (*CustomersCreditsGrantsService) Create

Create a new credit grant. A credit grant represents an allocation of prepaid credits to a customer.

func (*CustomersCreditsGrantsService) Get

func (s *CustomersCreditsGrantsService) Get(ctx context.Context, customerID string, creditGrantID string) (*CreditGrant, error)

Get a credit grant.

func (*CustomersCreditsGrantsService) List

List credit grants.

func (*CustomersCreditsGrantsService) ListAll

ListAll returns an iterator over all CreditGrant results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*CustomersCreditsGrantsService) UpdateExternalSettlement

func (s *CustomersCreditsGrantsService) UpdateExternalSettlement(ctx context.Context, customerID string, creditGrantID string, request UpdateCreditGrantExternalSettlementRequest) (*CreditGrant, error)

Update the payment settlement status of an externally funded credit grant.

Use this endpoint to synchronize the payment state of an external payment with the system so that revenue recognition and credit availability work as expected.

type CustomersCreditsService

type CustomersCreditsService struct {
	Grants       *CustomersCreditsGrantsService
	Balance      *CustomersCreditsBalanceService
	Adjustments  *CustomersCreditsAdjustmentsService
	Transactions *CustomersCreditsTransactionsService
	// contains filtered or unexported fields
}

type CustomersCreditsTransactionsService

type CustomersCreditsTransactionsService struct {
	// contains filtered or unexported fields
}

func (*CustomersCreditsTransactionsService) List

List credit transactions for a customer.

Returns an immutable, chronological record of credit movements: funded credits and consumed credits. Transactions are returned in reverse chronological order by default.

func (*CustomersCreditsTransactionsService) ListAll

ListAll returns an iterator over all CreditTransaction results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

type CustomersService

type CustomersService struct {
	Billing *CustomersBillingService
	Credits *CustomersCreditsService
	Charges *CustomersChargesService
	// contains filtered or unexported fields
}

func (*CustomersService) Create

func (*CustomersService) Delete

func (s *CustomersService) Delete(ctx context.Context, customerID string) error

func (*CustomersService) Get

func (s *CustomersService) Get(ctx context.Context, customerID string) (*Customer, error)

func (*CustomersService) List

func (*CustomersService) ListAll

ListAll returns an iterator over all Customer results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*CustomersService) Upsert

func (s *CustomersService) Upsert(ctx context.Context, customerID string, request UpsertCustomerRequest) (*Customer, error)

type DateTimeFilter

type DateTimeFilter struct {
	Eq  *time.Time
	Gt  *time.Time
	Gte *time.Time
	Lt  *time.Time
	Lte *time.Time
}

DateTimeFilter expresses comparisons against RFC 3339 timestamps.

type DefaultsService

type DefaultsService struct {
	// contains filtered or unexported fields
}

func (*DefaultsService) GetOrganizationTaxCodes

func (s *DefaultsService) GetOrganizationTaxCodes(ctx context.Context) (*OrganizationDefaultTaxCodes, error)

func (*DefaultsService) UpdateOrganizationTaxCodes

type EntitlementAccessResult

type EntitlementAccessResult struct {
	// The type of the entitlement.
	Type EntitlementType `json:"type"`
	// The feature key of the entitlement.
	FeatureKey string `json:"feature_key"`
	// Whether the customer has access to the feature. Always true for `boolean` and
	// `static` entitlements. Depends on balance for `metered` entitlements.
	HasAccess bool `json:"has_access"`
	// Only available for static entitlements. Config is the JSON parsable
	// configuration of the entitlement. Useful to describe per customer configuration.
	Config *string `json:"config,omitempty"`
}

Entitlement access result.

type EntitlementType

type EntitlementType string

The type of the entitlement.

const (
	EntitlementTypeMetered EntitlementType = "metered"
	EntitlementTypeStatic  EntitlementType = "static"
	EntitlementTypeBoolean EntitlementType = "boolean"
)

func (EntitlementType) Valid

func (value EntitlementType) Valid() bool

type EntitlementsService

type EntitlementsService struct {
	// contains filtered or unexported fields
}

func (*EntitlementsService) ListCustomerAccess

func (s *EntitlementsService) ListCustomerAccess(ctx context.Context, customerID string) (*ListCustomerEntitlementAccessResponseData, error)

type Event

type Event struct {
	// Identifies the event.
	ID string `json:"id"`
	// Identifies the context in which an event happened.
	Source string `json:"source"`
	// The version of the CloudEvents specification which the event uses.
	Specversion string `json:"specversion"`
	// Contains a value describing the type of event related to the originating
	// occurrence.
	Type string `json:"type"`
	// Content type of the CloudEvents data value. Only the value "application/json" is
	// allowed over HTTP.
	Datacontenttype Nullable[string] `json:"datacontenttype,omitempty"`
	// Identifies the schema that data adheres to.
	Dataschema Nullable[string] `json:"dataschema,omitempty"`
	// Describes the subject of the event in the context of the event producer
	// (identified by source).
	Subject string `json:"subject"`
	// Timestamp of when the occurrence happened. Must adhere to RFC 3339.
	Time Nullable[time.Time] `json:"time,omitempty"`
	// The event payload. Optional, if present it must be a JSON object.
	Data Nullable[map[string]any] `json:"data,omitempty"`
}

Metering event following the CloudEvents specification.

type EventInput

type EventInput struct {
	// Identifies the event.
	ID string `json:"id"`
	// Identifies the context in which an event happened.
	Source string `json:"source"`
	// The version of the CloudEvents specification which the event uses.
	Specversion *string `json:"specversion,omitempty"`
	// Contains a value describing the type of event related to the originating
	// occurrence.
	Type string `json:"type"`
	// Content type of the CloudEvents data value. Only the value "application/json" is
	// allowed over HTTP.
	Datacontenttype Nullable[string] `json:"datacontenttype,omitempty"`
	// Identifies the schema that data adheres to.
	Dataschema Nullable[string] `json:"dataschema,omitempty"`
	// Describes the subject of the event in the context of the event producer
	// (identified by source).
	Subject string `json:"subject"`
	// Timestamp of when the occurrence happened. Must adhere to RFC 3339.
	Time Nullable[time.Time] `json:"time,omitempty"`
	// The event payload. Optional, if present it must be a JSON object.
	Data Nullable[map[string]any] `json:"data,omitempty"`
}

Metering event following the CloudEvents specification.

type EventsService

type EventsService struct {
	// contains filtered or unexported fields
}

func (*EventsService) IngestEvent

func (s *EventsService) IngestEvent(ctx context.Context, request EventInput) error

Ingests an event or batch of events following the CloudEvents specification.

func (*EventsService) IngestEvents

func (s *EventsService) IngestEvents(ctx context.Context, request []EventInput) error

func (*EventsService) IngestEventsJSON

func (s *EventsService) IngestEventsJSON(ctx context.Context, request OneOrMany[EventInput]) error

func (*EventsService) List

List ingested events.

func (*EventsService) ListAll

ListAll returns an iterator over all IngestedEvent results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

type Feature

type Feature struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	Key       string     `json:"key"`
	// The meter that the feature is associated with and based on which usage is
	// calculated. If not specified, the feature is static.
	Meter *FeatureMeterReference `json:"meter,omitempty"`
	// Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or
	// "llm" to look up cost from the LLM cost database based on meter group-by
	// properties.
	UnitCost *FeatureUnitCost `json:"unit_cost,omitempty"`
}

A capability or billable dimension offered by a provider.

type FeatureCostQueryResult

type FeatureCostQueryResult struct {
	// Start of the queried period.
	From *time.Time `json:"from,omitempty"`
	// End of the queried period.
	To *time.Time `json:"to,omitempty"`
	// The cost data rows.
	Data []FeatureCostQueryRow `json:"data"`
}

Result of a feature cost query.

type FeatureCostQueryRow

type FeatureCostQueryRow struct {
	// The metered usage value for the period.
	Usage Numeric `json:"usage"`
	// The computed cost amount (usage × unit cost). Null when pricing is not available
	// for the given combination of dimensions.
	Cost Nullable[Numeric] `json:"cost"`
	// The currency code of the cost amount.
	Currency string `json:"currency"`
	// Detail message when cost amount is null, explaining why the cost could not be
	// resolved.
	Detail *string `json:"detail,omitempty"`
	// The start of the time bucket the value is aggregated over.
	From time.Time `json:"from"`
	// The end of the time bucket the value is aggregated over.
	To time.Time `json:"to"`
	// The dimensions the value is aggregated over. `subject` and `customer_id` are
	// reserved dimensions.
	Dimensions map[string]string `json:"dimensions"`
}

A row in the result of a feature cost query.

type FeatureFilter

type FeatureFilter struct {
	MeterID *StringExactFilter
	Key     *StringFilter
	Name    *StringFilter
}

type FeatureLLMTokenType

type FeatureLLMTokenType string

Token type for LLM cost lookup.

const (
	FeatureLLMTokenTypeInput      FeatureLLMTokenType = "input"
	FeatureLLMTokenTypeOutput     FeatureLLMTokenType = "output"
	FeatureLLMTokenTypeCacheRead  FeatureLLMTokenType = "cache_read"
	FeatureLLMTokenTypeCacheWrite FeatureLLMTokenType = "cache_write"
	FeatureLLMTokenTypeReasoning  FeatureLLMTokenType = "reasoning"
	FeatureLLMTokenTypeRequest    FeatureLLMTokenType = "request"
	FeatureLLMTokenTypeResponse   FeatureLLMTokenType = "response"
)

func (FeatureLLMTokenType) Valid

func (value FeatureLLMTokenType) Valid() bool

type FeatureLLMUnitCost

type FeatureLLMUnitCost struct {
	// The type discriminator for LLM unit cost.
	Type FeatureUnitCostType `json:"type"`
	// Meter group-by property that holds the LLM provider. Use this when the meter has
	// a group-by dimension for provider. Mutually exclusive with `provider`.
	ProviderProperty *string `json:"provider_property,omitempty"`
	// Static LLM provider value (e.g., "openai", "anthropic"). Use this when the
	// feature tracks a single provider. Mutually exclusive with `provider_property`.
	Provider *string `json:"provider,omitempty"`
	// Meter group-by property that holds the model ID. Use this when the meter has a
	// group-by dimension for model. Mutually exclusive with `model`.
	ModelProperty *string `json:"model_property,omitempty"`
	// Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). Use this when the
	// feature tracks a single model. Mutually exclusive with `model_property`.
	Model *string `json:"model,omitempty"`
	// Meter group-by property that holds the token type. Use this when the meter has a
	// group-by dimension for token type. Mutually exclusive with `token_type`.
	TokenTypeProperty *string `json:"token_type_property,omitempty"`
	// Static token type value. Use this when the feature tracks a single token type
	// (e.g., only input tokens). `request` is an alias for `input`, `response` is an
	// alias for `output`. Mutually exclusive with `token_type_property`.
	TokenType *FeatureLLMTokenType `json:"token_type,omitempty"`
	// Resolved per-token pricing from the LLM cost database. Populated in responses
	// when the provider and model can be determined, either from static values or from
	// meter group-by filters with exact matches.
	Pricing *FeatureLLMUnitCostPricing `json:"pricing,omitempty"`
}

LLM cost lookup configuration. Each dimension (provider, model, token type) can be specified as either a static value or a meter group-by property name (mutually exclusive).

type FeatureLLMUnitCostPricing

type FeatureLLMUnitCostPricing struct {
	// Cost per input token in USD.
	InputPerToken Numeric `json:"input_per_token"`
	// Cost per output token in USD.
	OutputPerToken Numeric `json:"output_per_token"`
	// Cost per cache read token in USD.
	CacheReadPerToken *Numeric `json:"cache_read_per_token,omitempty"`
	// Cost per reasoning token in USD.
	ReasoningPerToken *Numeric `json:"reasoning_per_token,omitempty"`
	// Cost per cache write token in USD.
	CacheWritePerToken *Numeric `json:"cache_write_per_token,omitempty"`
}

Resolved per-token pricing from the LLM cost database.

type FeatureListParams

type FeatureListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *FeatureFilter
}

type FeatureManualUnitCost

type FeatureManualUnitCost struct {
	// The type discriminator for manual unit cost.
	Type FeatureUnitCostType `json:"type"`
	// Fixed per-unit cost amount in USD.
	Amount Numeric `json:"amount"`
}

A fixed per-unit cost amount.

type FeatureMeterReference

type FeatureMeterReference struct {
	// The ID of the meter to associate with this feature.
	ID string `json:"id"`
	// Filters to apply to the dimensions of the meter.
	Filters map[string]QueryFilterStringMapItem `json:"filters,omitempty"`
}

Reference to a meter associated with a feature.

type FeatureMeterReferenceInput

type FeatureMeterReferenceInput struct {
	// The ID of the meter to associate with this feature.
	ID string `json:"id"`
	// Filters to apply to the dimensions of the meter.
	Filters *map[string]QueryFilterStringMapItemInput `json:"filters,omitempty"`
}

Reference to a meter associated with a feature.

type FeaturePagePaginatedResponse

type FeaturePagePaginatedResponse struct {
	Data []Feature     `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type FeatureReference

type FeatureReference struct {
	ID string `json:"id"`
}

Feature reference.

type FeatureUnitCost

type FeatureUnitCost struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Per-unit cost configuration for a feature. Either a fixed manual amount or a dynamic LLM cost lookup.

FeatureUnitCost is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the FeatureUnitCostFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func FeatureUnitCostFromFeatureLLMUnitCost

func FeatureUnitCostFromFeatureLLMUnitCost(value FeatureLLMUnitCost) (FeatureUnitCost, error)

func FeatureUnitCostFromFeatureManualUnitCost

func FeatureUnitCostFromFeatureManualUnitCost(value FeatureManualUnitCost) (FeatureUnitCost, error)

func (FeatureUnitCost) AsFeatureLLMUnitCost

func (u FeatureUnitCost) AsFeatureLLMUnitCost() (*FeatureLLMUnitCost, error)

func (FeatureUnitCost) AsFeatureManualUnitCost

func (u FeatureUnitCost) AsFeatureManualUnitCost() (*FeatureManualUnitCost, error)

func (FeatureUnitCost) MarshalJSON

func (u FeatureUnitCost) MarshalJSON() ([]byte, error)

func (*FeatureUnitCost) UnmarshalJSON

func (u *FeatureUnitCost) UnmarshalJSON(data []byte) error

type FeatureUnitCostType

type FeatureUnitCostType string

The type of unit cost.

const (
	FeatureUnitCostTypeLLM    FeatureUnitCostType = "llm"
	FeatureUnitCostTypeManual FeatureUnitCostType = "manual"
)

func (FeatureUnitCostType) Valid

func (value FeatureUnitCostType) Valid() bool

type FeaturesService

type FeaturesService struct {
	// contains filtered or unexported fields
}

func (*FeaturesService) Create

func (s *FeaturesService) Create(ctx context.Context, request CreateFeatureRequest) (*Feature, error)

Create a feature.

func (*FeaturesService) Delete

func (s *FeaturesService) Delete(ctx context.Context, featureID string) error

Delete a feature by id.

func (*FeaturesService) Get

func (s *FeaturesService) Get(ctx context.Context, featureID string) (*Feature, error)

Get a feature by id.

func (*FeaturesService) List

List all features.

func (*FeaturesService) ListAll

ListAll returns an iterator over all Feature results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*FeaturesService) QueryCost

func (s *FeaturesService) QueryCost(ctx context.Context, featureID string, request *MeterQueryRequest) (*FeatureCostQueryResult, error)

Query the cost of a feature.

func (*FeaturesService) Update

func (s *FeaturesService) Update(ctx context.Context, featureID string, request UpdateFeatureRequest) (*Feature, error)

Update a feature by id. Currently only the unit_cost field can be updated.

type GetCustomerCreditBalanceFilter

type GetCustomerCreditBalanceFilter struct {
	// Filter credit balance by currency.
	Currency *StringExactFilter
	// Filter credit balance by feature key. Omit to return the total portfolio value.
	// Use `exists=false` to return only unrestricted balance.
	FeatureKey *StringFilter
}

type GetCustomerCreditBalanceParams

type GetCustomerCreditBalanceParams struct {
	Timestamp *time.Time
	Filter    *GetCustomerCreditBalanceFilter
}

type GovernanceFeatureAccess

type GovernanceFeatureAccess struct {
	// Whether the customer currently has access to the feature.
	//
	// `true` for boolean and static entitlements that are available, and for metered
	// entitlements with remaining balance. `false` when the feature is unavailable,
	// the usage limit has been reached, or (when applicable) credits have been
	// exhausted.
	HasAccess bool `json:"has_access"`
	// Optional reason when the customer does not have access to the feature. Populated
	// when `has_access` is `false`.
	Reason *GovernanceFeatureAccessReason `json:"reason,omitempty"`
}

Access status for a single feature.

type GovernanceFeatureAccessReason

type GovernanceFeatureAccessReason struct {
	// Machine-readable error code.
	Code GovernanceFeatureAccessReasonCode `json:"code"`
	// Human-readable description of the error.
	Message string `json:"message"`
	// Additional structured context.
	Attributes map[string]any `json:"attributes,omitempty"`
}

Reason a feature is not accessible to a customer.

type GovernanceFeatureAccessReasonCode

type GovernanceFeatureAccessReasonCode string

Machine-readable reason code for denied feature access.

const (
	GovernanceFeatureAccessReasonCodeUnknown            GovernanceFeatureAccessReasonCode = "unknown"
	GovernanceFeatureAccessReasonCodeUsageLimitReached  GovernanceFeatureAccessReasonCode = "usage_limit_reached"
	GovernanceFeatureAccessReasonCodeFeatureUnavailable GovernanceFeatureAccessReasonCode = "feature_unavailable"
	GovernanceFeatureAccessReasonCodeFeatureNotFound    GovernanceFeatureAccessReasonCode = "feature_not_found"
	GovernanceFeatureAccessReasonCodeNoCreditAvailable  GovernanceFeatureAccessReasonCode = "no_credit_available"
)

func (GovernanceFeatureAccessReasonCode) Valid

type GovernanceQueryError

type GovernanceQueryError struct {
	// Machine-readable error code.
	Code GovernanceQueryErrorCode `json:"code"`
	// Human-readable description of the error.
	Message string `json:"message"`
	// Additional structured context.
	Attributes map[string]any `json:"attributes,omitempty"`
	// The customer identifier from the request that produced this error.
	Customer *string `json:"customer,omitempty"`
}

Query error within a partially successful governance query response.

type GovernanceQueryErrorCode

type GovernanceQueryErrorCode string

Error code for a governance query failure.

const (
	GovernanceQueryErrorCodeUnknown          GovernanceQueryErrorCode = "unknown"
	GovernanceQueryErrorCodeCustomerNotFound GovernanceQueryErrorCode = "customer_not_found"
)

func (GovernanceQueryErrorCode) Valid

func (value GovernanceQueryErrorCode) Valid() bool

type GovernanceQueryRequest

type GovernanceQueryRequest struct {
	// Whether to include credit balance availability for each resolved customer. When
	// true, each feature evaluation includes credit balance checks.
	//
	// Defaults to `false`.
	IncludeCredits *bool                           `json:"include_credits,omitempty"`
	Customer       GovernanceQueryRequestCustomers `json:"customer"`
	Feature        *GovernanceQueryRequestFeatures `json:"feature,omitempty"`
}

Query to evaluate feature access for a list of customers.

type GovernanceQueryRequestCustomers

type GovernanceQueryRequestCustomers struct {
	// Each entry can be a customer `key` or a usage-attribution subject `key`.
	// Identifiers that cannot be resolved to a customer are reported in the response
	// `errors` array.
	Keys []string `json:"keys"`
}

List of customer identifiers to evaluate access for.

type GovernanceQueryRequestFeatures

type GovernanceQueryRequestFeatures struct {
	// List of feature keys to evaluate access for.
	Keys []string `json:"keys"`
}

Optional list of feature keys to evaluate access for. If omitted, all features available in the organization are returned. Providing this list is recommended to reduce the response size and the load on the backend services.

type GovernanceQueryResponse

type GovernanceQueryResponse struct {
	// Access evaluation results, one entry per resolved customer.
	Data []GovernanceQueryResult `json:"data"`
	// Partial errors encountered while processing the request.
	Errors []GovernanceQueryError `json:"errors"`
	// Pagination metadata. The endpoint may return a partial response if the full
	// response would exceed server-side limits.
	Meta CursorMeta `json:"meta"`
}

Response of the governance query.

type GovernanceQueryResult

type GovernanceQueryResult struct {
	// The list of identifiers from the request that resolved to this customer. Each
	// entry is either the customer `key` or one of its usage-attribution subject
	// `key`s.
	//
	// Duplicate or aliased identifiers that resolve to the same customer collapse to a
	// single result entry, with every requested identifier listed here.
	Matched []string `json:"matched"`
	// The customer the matched identifiers resolved to.
	Customer Customer `json:"customer"`
	// Map of features with their access status.
	//
	// Map keys are the feature keys requested in `feature.keys`, or every feature
	// `key` available in the organization when the feature filter was omitted.
	Features map[string]GovernanceFeatureAccess `json:"features"`
	// Timestamp of the most recent change to the customer's access state reflected in
	// this result.
	UpdatedAt time.Time `json:"updated_at"`
}

Access evaluation result for a single resolved customer.

type GovernanceQueryResultListParams

type GovernanceQueryResultListParams struct {
	Page *CursorPageParams
}

type GovernanceService

type GovernanceService struct {
	// contains filtered or unexported fields
}

func (*GovernanceService) QueryAccess

Query feature access for a list of customers.

The endpoint resolves each provided identifier to a customer and returns the access status for the requested features, plus optional credit balance availability.

_Designed to be called on a fixed refresh interval and the query response is intended to be cached._

type IngestedEvent

type IngestedEvent struct {
	// The original event ingested.
	Event Event `json:"event"`
	// The customer if the event is associated with a customer.
	Customer *CustomerReference `json:"customer,omitempty"`
	// The date and time the event was ingested and its processing started.
	IngestedAt time.Time `json:"ingested_at"`
	// The date and time the event was stored in the database.
	StoredAt time.Time `json:"stored_at"`
	// The validation errors of the ingested event.
	ValidationErrors []IngestedEventValidationError `json:"validation_errors,omitempty"`
}

An ingested metering event with ingestion metadata.

type IngestedEventFilter

type IngestedEventFilter struct {
	// Filter events by ID.
	ID *StringFilter
	// Filter events by source.
	Source *StringFilter
	// Filter events by subject.
	Subject *StringFilter
	// Filter events by type.
	Type *StringFilter
	// Filter events by the associated customer ID.
	CustomerID *StringExactFilter
	// Filter events by event time.
	Time *DateTimeFilter
	// Filter events by the time the event was ingested.
	IngestedAt *DateTimeFilter
	// Filter events by the time the event was stored.
	StoredAt *DateTimeFilter
}

type IngestedEventListParams

type IngestedEventListParams struct {
	Page   *CursorPageParams
	Filter *IngestedEventFilter
	Sort   *Sort
}

type IngestedEventPaginatedResponse

type IngestedEventPaginatedResponse struct {
	Data []IngestedEvent `json:"data"`
	Meta CursorMeta      `json:"meta"`
}

Cursor paginated response.

type IngestedEventValidationError

type IngestedEventValidationError struct {
	// The machine readable code of the error.
	Code string `json:"code"`
	// The human readable description of the error.
	Message string `json:"message"`
	// Additional attributes.
	Attributes map[string]any `json:"attributes,omitempty"`
}

Event validation errors.

type Invoice

type Invoice struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

An invoice issued to a customer.

The `type` field determines the concrete variant:

- `standard`: a standard invoice for charges owed.

Invoice is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the InvoiceFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func InvoiceFromInvoiceStandard

func InvoiceFromInvoiceStandard(value InvoiceStandard) (Invoice, error)

func (Invoice) AsInvoiceStandard

func (u Invoice) AsInvoiceStandard() (*InvoiceStandard, error)

func (Invoice) MarshalJSON

func (u Invoice) MarshalJSON() ([]byte, error)

func (*Invoice) UnmarshalJSON

func (u *Invoice) UnmarshalJSON(data []byte) error

type InvoiceAvailableActionDetails

type InvoiceAvailableActionDetails struct {
	// The extended status the invoice will transition to after performing this action.
	ResultingState string `json:"resulting_state"`
}

Details about an available invoice action including the resulting state.

type InvoiceAvailableActions

type InvoiceAvailableActions struct {
	// Advance the invoice to the next workflow step.
	Advance *InvoiceAvailableActionDetails `json:"advance,omitempty"`
	// Approve the invoice for issuance.
	Approve *InvoiceAvailableActionDetails `json:"approve,omitempty"`
	// Delete the invoice.
	Delete *InvoiceAvailableActionDetails `json:"delete,omitempty"`
	// Retry a failed workflow step.
	Retry *InvoiceAvailableActionDetails `json:"retry,omitempty"`
	// Snapshot the current usage quantities.
	SnapshotQuantities *InvoiceAvailableActionDetails `json:"snapshot_quantities,omitempty"`
}

The set of state-transition actions available for an invoice in its current status.

A field is present only when that action is permitted from the current state.

type InvoiceCustomer

type InvoiceCustomer struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Mapping to attribute metered usage to the customer by the event subject.
	UsageAttribution *CustomerUsageAttribution `json:"usage_attribution,omitempty"`
	// The billing address of the customer. Used for tax and invoicing.
	BillingAddress *Address `json:"billing_address,omitempty"`
	ID             string   `json:"id"`
	// Optional external resource key for the customer.
	//
	// Omitted when the customer was created without a key. Unlike on the customer
	// resource itself, the key is optional here because the invoice snapshot may
	// predate or omit it.
	Key *string `json:"key,omitempty"`
}

Snapshot of the customer's information at the time the invoice was issued.

type InvoiceDetailedLine

type InvoiceDetailedLine struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The service period covered by this detailed line.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// Aggregated financial totals for the detailed line.
	Totals Totals `json:"totals"`
	// The cost category of this detailed line.
	Category InvoiceDetailedLineCostCategory `json:"category"`
	// Discounts applied to this detailed line.
	Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"`
	// Credit applied to this detailed line.
	CreditsApplied []InvoiceLineCreditsApplied `json:"credits_applied,omitempty"`
	// External identifiers for this detailed line.
	ExternalReferences *InvoiceLineExternalReferences `json:"external_references,omitempty"`
	// The quantity of the detailed line.
	Quantity Numeric `json:"quantity"`
	// The unit price of the detailed line.
	UnitPrice Numeric `json:"unit_price"`
}

A detailed (child) sub-line belonging to a parent invoice line.

Detailed lines represent the individual flat-fee components that make up a usage-based parent line after quantity snapshotting.

type InvoiceDetailedLineCostCategory

type InvoiceDetailedLineCostCategory string

Cost category of a detailed invoice line item.

const (
	InvoiceDetailedLineCostCategoryRegular    InvoiceDetailedLineCostCategory = "regular"
	InvoiceDetailedLineCostCategoryCommitment InvoiceDetailedLineCostCategory = "commitment"
)

func (InvoiceDetailedLineCostCategory) Valid

func (value InvoiceDetailedLineCostCategory) Valid() bool

type InvoiceDiscountReason

type InvoiceDiscountReason string

The reason a discount was applied to an invoice line.

const (
	InvoiceDiscountReasonMaximumSpend       InvoiceDiscountReason = "maximum_spend"
	InvoiceDiscountReasonRatecardPercentage InvoiceDiscountReason = "ratecard_percentage"
	InvoiceDiscountReasonRatecardUsage      InvoiceDiscountReason = "ratecard_usage"
)

func (InvoiceDiscountReason) Valid

func (value InvoiceDiscountReason) Valid() bool

type InvoiceExternalReferences

type InvoiceExternalReferences struct {
	// The ID assigned by the external invoicing app (e.g. Stripe invoice ID).
	InvoicingID *string `json:"invoicing_id,omitempty"`
	// The ID assigned by the external payment app (e.g. Stripe payment intent ID).
	PaymentID *string `json:"payment_id,omitempty"`
}

External identifiers assigned to an invoice by third-party systems.

type InvoiceFilter

type InvoiceFilter struct {
	// Filter by invoice status.
	Status *StringExactFilter
	// Filter by customer ID.
	CustomerID *StringExactFilter
	// Filter by the time the invoice was issued.
	IssuedAt *DateTimeFilter
	// Filter by service period start.
	ServicePeriodStart *DateTimeFilter
	// Filter by invoice creation time.
	CreatedAt *DateTimeFilter
}

type InvoiceLine

type InvoiceLine struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

A top-level line item on an invoice.

Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.

InvoiceLine is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the InvoiceLineFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func InvoiceLineFromInvoiceStandardLine

func InvoiceLineFromInvoiceStandardLine(value InvoiceStandardLine) (InvoiceLine, error)

func (InvoiceLine) AsInvoiceStandardLine

func (u InvoiceLine) AsInvoiceStandardLine() (*InvoiceStandardLine, error)

func (InvoiceLine) MarshalJSON

func (u InvoiceLine) MarshalJSON() ([]byte, error)

func (*InvoiceLine) UnmarshalJSON

func (u *InvoiceLine) UnmarshalJSON(data []byte) error

type InvoiceLineAmountDiscount

type InvoiceLineAmountDiscount struct {
	// Unique identifier for the discount.
	ID string `json:"id"`
	// The reason this discount was applied.
	Reason InvoiceDiscountReason `json:"reason"`
	// Optional human-readable description of the discount.
	Description *string `json:"description,omitempty"`
	// External identifiers for this discount.
	ExternalReferences *InvoiceLineExternalReferences `json:"external_references,omitempty"`
	// The monetary amount deducted.
	Amount Numeric `json:"amount"`
}

A monetary amount discount applied to an invoice line item.

type InvoiceLineCreditsApplied

type InvoiceLineCreditsApplied struct {
	// The monetary amount credited.
	Amount Numeric `json:"amount"`
	// Optional human-readable description of the credit allocation.
	Description *string `json:"description,omitempty"`
}

A credit allocation applied to an invoice line item.

type InvoiceLineDiscounts

type InvoiceLineDiscounts struct {
	// Monetary amount discounts (e.g. from maximum spend commitments).
	Amount []InvoiceLineAmountDiscount `json:"amount,omitempty"`
	// Usage quantity discounts (e.g. free tier usage allowances).
	Usage []InvoiceLineUsageDiscount `json:"usage,omitempty"`
}

Discounts applied to an invoice line item.

type InvoiceLineExternalReferences

type InvoiceLineExternalReferences struct {
	// The ID assigned by the external invoicing app.
	InvoicingID *string `json:"invoicing_id,omitempty"`
}

External identifiers for an invoice line item assigned by third-party systems.

type InvoiceLineRateCard

type InvoiceLineRateCard struct {
	// The price definition used to calculate charges for this line.
	Price Price `json:"price"`
	// Tax configuration snapshot for this line.
	TaxConfig *RateCardTaxConfig `json:"tax_config,omitempty"`
	// The feature key associated with this line's rate card.
	FeatureKey *string `json:"feature_key,omitempty"`
	// Discount configuration from the rate card.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
}

Rate card configuration snapshot for a usage-based invoice line.

type InvoiceLineType

type InvoiceLineType string

Line item type discriminator.

const (
	InvoiceLineTypeStandardLine InvoiceLineType = "standard_line"
)

func (InvoiceLineType) Valid

func (value InvoiceLineType) Valid() bool

type InvoiceLineUsageDiscount

type InvoiceLineUsageDiscount struct {
	// Unique identifier for the discount.
	ID string `json:"id"`
	// The reason this discount was applied.
	Reason InvoiceDiscountReason `json:"reason"`
	// Optional human-readable description of the discount.
	Description *string `json:"description,omitempty"`
	// External identifiers for this discount.
	ExternalReferences *InvoiceLineExternalReferences `json:"external_references,omitempty"`
	// The usage quantity deducted (in billing units).
	Quantity Numeric `json:"quantity"`
}

A usage quantity discount applied to an invoice line item.

type InvoiceListParams

type InvoiceListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *InvoiceFilter
}

type InvoicePagePaginatedResponse

type InvoicePagePaginatedResponse struct {
	Data []Invoice     `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type InvoiceStandard

type InvoiceStandard struct {
	ID string `json:"id"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// Human-readable invoice number generated by the invoicing app.
	Number string `json:"number"`
	// Three-letter ISO 4217 currency code for the invoice.
	Currency string `json:"currency"`
	// Snapshot of the supplier's contact information at the time the invoice was
	// issued.
	Supplier Supplier `json:"supplier"`
	// Snapshot of the customer's information at the time the invoice was issued.
	Customer InvoiceCustomer `json:"customer"`
	// Aggregated financial totals for the invoice.
	Totals Totals `json:"totals"`
	// The service period covered by this invoice.
	//
	// For flat fee the service period can be empty which means `from` will be equals
	// to `to`. In other cases those fields will be filled with the actual service
	// period.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// Validation issues found during invoice processing.
	//
	// Present only when there are one or more validation findings. An empty list is
	// omitted.
	ValidationIssues []InvoiceValidationIssue `json:"validation_issues,omitempty"`
	// External identifiers assigned to this invoice by third-party systems.
	ExternalReferences *InvoiceExternalReferences `json:"external_references,omitempty"`
	// Discriminator field identifying this as a standard invoice.
	Type InvoiceType `json:"type"`
	// Current lifecycle status of the invoice.
	Status InvoiceStandardStatus `json:"status"`
	// Detailed status information including available actions and workflow state.
	StatusDetails InvoiceStatusDetails `json:"status_details"`
	// Timestamp when the invoice was issued to the customer.
	IssuedAt *time.Time `json:"issued_at,omitempty"`
	// Timestamp until which the invoice remains in draft state.
	//
	// The invoice advances automatically once this time is reached.
	DraftUntil *time.Time `json:"draft_until,omitempty"`
	// Timestamp when usage quantities were last snapshotted for this invoice.
	QuantitySnapshottedAt *time.Time `json:"quantity_snapshotted_at,omitempty"`
	// Timestamp when collection was initiated for this invoice.
	CollectionAt *time.Time `json:"collection_at,omitempty"`
	// Timestamp when payment is due.
	DueAt *time.Time `json:"due_at,omitempty"`
	// Timestamp when the invoice was sent to the customer.
	SentToCustomerAt *time.Time `json:"sent_to_customer_at,omitempty"`
	// Workflow configuration snapshot captured at invoice creation time.
	Workflow InvoiceWorkflowSettings `json:"workflow"`
	// Line items on this invoice.
	//
	// Always returned on single-resource GET; omitted on list endpoints unless
	// explicitly expanded. Editable via update: existing lines are matched by `id`,
	// lines without an `id` are created, and lines present on the invoice but omitted
	// from the update request are deleted. Detailed (child) lines are always computed
	// and cannot be edited directly.
	Lines []InvoiceLine `json:"lines,omitempty"`
}

A standard invoice for charges owed by the customer.

type InvoiceStandardLine

type InvoiceStandardLine struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// ID of the line.
	//
	// Optional on update: omit to create a new line, or supply the ID of an existing
	// line to edit it. Existing lines omitted from an update's `lines` array are
	// deleted.
	ID *string `json:"id,omitempty"`
	// The type of charge this line item represents.
	Type InvoiceLineType `json:"type"`
	// Indicates whether this line item's lifecycle is controlled by OpenMeter or
	// manually overridden by the API user.
	LifecycleController LifecycleController `json:"lifecycle_controller"`
	// The service period covered by this invoice, spanning the earliest line start to
	// the latest line end across all of its lines.
	//
	// For an invoice with no lines the period is empty, which means `from` will be
	// equal to `to`.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// Aggregated financial totals for the line item.
	Totals Totals `json:"totals"`
	// Discounts applied to this line item.
	Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"`
	// Credit applied to this line item.
	CreditsApplied []InvoiceLineCreditsApplied `json:"credits_applied,omitempty"`
	// External identifiers for this line item assigned by third-party systems.
	ExternalReferences *InvoiceLineExternalReferences `json:"external_references,omitempty"`
	// Reference to the subscription item that generated this line.
	Subscription *SubscriptionReference `json:"subscription,omitempty"`
	// The rate card configuration snapshot used to price this line item.
	RateCard InvoiceLineRateCard `json:"rate_card"`
	// Detailed sub-lines that this line has been broken down into.
	//
	// Present when line has individual details.
	DetailedLines []InvoiceDetailedLine `json:"detailed_lines"`
	// Reference to the charge associated with this line item.
	Charge *ChargeReference `json:"charge,omitempty"`
}

A top-level line item on an invoice.

Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.

type InvoiceStandardStatus

type InvoiceStandardStatus string

Lifecycle status of a standard invoice.

const (
	InvoiceStandardStatusDraft             InvoiceStandardStatus = "draft"
	InvoiceStandardStatusIssuing           InvoiceStandardStatus = "issuing"
	InvoiceStandardStatusIssued            InvoiceStandardStatus = "issued"
	InvoiceStandardStatusPaymentProcessing InvoiceStandardStatus = "payment_processing"
	InvoiceStandardStatusOverdue           InvoiceStandardStatus = "overdue"
	InvoiceStandardStatusPaid              InvoiceStandardStatus = "paid"
	InvoiceStandardStatusUncollectible     InvoiceStandardStatus = "uncollectible"
	InvoiceStandardStatusVoided            InvoiceStandardStatus = "voided"
)

func (InvoiceStandardStatus) Valid

func (value InvoiceStandardStatus) Valid() bool

type InvoiceStatusDetails

type InvoiceStatusDetails struct {
	// Whether the invoice is immutable (i.e. cannot be modified or deleted).
	Immutable bool `json:"immutable"`
	// Whether the invoice is in a failed state.
	Failed bool `json:"failed"`
	// Fine-grained internal status string providing additional workflow detail beyond
	// the top-level status enum.
	ExtendedStatus string `json:"extended_status"`
	// The set of state-transition actions currently available for this invoice.
	AvailableActions InvoiceAvailableActions `json:"available_actions"`
}

Detailed status information for a standard invoice.

type InvoiceType

type InvoiceType string

The type of a billing invoice.

const (
	InvoiceTypeStandard InvoiceType = "standard"
)

func (InvoiceType) Valid

func (value InvoiceType) Valid() bool

type InvoiceValidationIssue

type InvoiceValidationIssue struct {
	// Machine-readable error code.
	Code string `json:"code"`
	// Human-readable description of the error.
	Message string `json:"message"`
	// Additional structured context.
	Attributes map[string]any `json:"attributes,omitempty"`
	// Severity of the validation issue.
	Severity InvoiceValidationIssueSeverity `json:"severity"`
	// JSON path to the field that caused this validation issue, if applicable.
	//
	// For example: `lines/0/rate_card/price`.
	Field *string `json:"field,omitempty"`
}

A validation issue found during invoice processing.

Converges on the same structure used by plan and subscription validation errors: a machine-readable `code`, a human-readable `message`, optional structured `attributes`, plus a `severity` and optional `field` path.

type InvoiceValidationIssueSeverity

type InvoiceValidationIssueSeverity string

Severity level of an invoice validation issue.

const (
	InvoiceValidationIssueSeverityCritical InvoiceValidationIssueSeverity = "critical"
	InvoiceValidationIssueSeverityWarning  InvoiceValidationIssueSeverity = "warning"
)

func (InvoiceValidationIssueSeverity) Valid

func (value InvoiceValidationIssueSeverity) Valid() bool

type InvoiceWorkflow

type InvoiceWorkflow struct {
	// Invoicing settings for this invoice.
	Invoicing *InvoiceWorkflowInvoicingSettings `json:"invoicing,omitempty"`
	// Payment settings for this invoice.
	Payment *WorkflowPaymentSettings `json:"payment,omitempty"`
}

Invoice-level snapshot of the workflow configuration.

Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.

type InvoiceWorkflowAppsReferences

type InvoiceWorkflowAppsReferences struct {
	// The tax app used for this workflow
	Tax AppReference `json:"tax"`
	// The invoicing app used for this workflow
	Invoicing AppReference `json:"invoicing"`
	// The payment app used for this workflow
	Payment AppReference `json:"payment"`
}

BillingInvoiceWorkflowAppsReferences represents the references (id) to the apps used by a billing profile

type InvoiceWorkflowInvoicingSettings

type InvoiceWorkflowInvoicingSettings struct {
	// Whether to automatically issue the invoice after the draft_period has passed.
	AutoAdvance *bool `json:"auto_advance,omitempty"`
	// The period for the invoice to be kept in draft status for manual reviews.
	DraftPeriod *string `json:"draft_period,omitempty"`
	// The period after which the invoice is considered overdue if not paid.
	DueAfter *string `json:"due_after,omitempty"`
}

Invoice-level invoicing settings.

A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.

type InvoiceWorkflowSettings

type InvoiceWorkflowSettings struct {
	// The apps that will be used to orchestrate the invoice's workflow.
	Apps *InvoiceWorkflowAppsReferences `json:"apps,omitempty"`
	// The billing profile that was the source of this workflow snapshot.
	SourceBillingProfile ProfileReference `json:"source_billing_profile"`
	// The workflow configuration that was active when the invoice was created.
	//
	// Only the fields that are meaningful at the per-invoice level are included:
	// invoicing behaviour (auto-advance, draft period) and payment settings
	// (collection method, due date). Profile-wide settings such as collection
	// alignment, progressive billing, and tax policy are omitted.
	Workflow InvoiceWorkflow `json:"workflow"`
}

Snapshot of the billing workflow configuration captured at invoice creation.

type InvoicesService

type InvoicesService struct {
	// contains filtered or unexported fields
}

func (*InvoicesService) Delete

func (s *InvoicesService) Delete(ctx context.Context, invoiceID string) error

Delete a billing invoice.

Only standard invoices in draft status can be deleted. Deleting an invoice will also delete all associated line items and workflow configuration.

func (*InvoicesService) Get

func (s *InvoicesService) Get(ctx context.Context, invoiceID string) (*Invoice, error)

Get a billing invoice by ID.

Returns the full invoice resource including line items, status details, totals, and workflow configuration snapshot.

func (*InvoicesService) List

List billing invoices.

Returns a page of invoices. Gathering invoices are never included. Use `filter` to narrow by status, customer, dates, or service period start. Use `sort` to control ordering.

func (*InvoicesService) ListAll

ListAll returns an iterator over all Invoice results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*InvoicesService) Update

func (s *InvoicesService) Update(ctx context.Context, invoiceID string, request UpdateInvoiceRequest) (*Invoice, error)

Update a billing invoice.

Only the mutable fields of the invoice can be edited: description, labels, supplier, customer, workflow settings, and top-level lines. Top-level lines are matched by `id`; lines without an `id` are created, and existing lines omitted from `lines` are deleted. Detailed (child) lines are always computed and cannot be edited directly. Only invoices in draft status can be updated.

type LLMCostModel

type LLMCostModel struct {
	// Identifier of the model, e.g., "gpt-4", "claude-3-5-sonnet".
	ID string `json:"id"`
	// Name of the model, e.g., "GPT-4", "Claude 3.5 Sonnet".
	Name string `json:"name"`
}

LLM Model

type LLMCostModelPricing

type LLMCostModelPricing struct {
	// Input price per token (USD).
	InputPerToken Numeric `json:"input_per_token"`
	// Output price per token (USD).
	OutputPerToken Numeric `json:"output_per_token"`
	// Cache read price per token (USD).
	CacheReadPerToken *Numeric `json:"cache_read_per_token,omitempty"`
	// Cache write price per token (USD).
	CacheWritePerToken *Numeric `json:"cache_write_per_token,omitempty"`
	// Reasoning output price per token (USD).
	ReasoningPerToken *Numeric `json:"reasoning_per_token,omitempty"`
}

Token pricing for an LLM model, denominated per token.

type LLMCostOverrideCreate

type LLMCostOverrideCreate struct {
	// Provider/vendor of the model.
	Provider string `json:"provider"`
	// Canonical model identifier.
	ModelID string `json:"model_id"`
	// Human-readable model name.
	ModelName *string `json:"model_name,omitempty"`
	// Token pricing data.
	Pricing LLMCostModelPricing `json:"pricing"`
	// Currency code.
	Currency string `json:"currency"`
	// When this override becomes effective.
	EffectiveFrom time.Time `json:"effective_from"`
	// When this override expires.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
}

Input for creating a per-namespace price override. Unique per provider, model and currency. If an override already exists for the given provider, model and currency, it will be updated. If an override does not exist, it will be created.

type LLMCostPrice

type LLMCostPrice struct {
	// Unique identifier.
	ID string `json:"id"`
	// Provider of the model.
	Provider LLMCostProvider `json:"provider"`
	// The model.
	Model LLMCostModel `json:"model"`
	// Token pricing data.
	Pricing LLMCostModelPricing `json:"pricing"`
	// Currency code (currently always "USD").
	Currency string `json:"currency"`
	// Where this price came from.
	Source LLMCostPriceSource `json:"source"`
	// When this price becomes effective.
	EffectiveFrom time.Time `json:"effective_from"`
	// When this price expires. Omitted when the price is currently effective.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
	// Creation timestamp.
	CreatedAt time.Time `json:"created_at"`
	// Last update timestamp.
	UpdatedAt time.Time `json:"updated_at"`
}

An LLM cost price record, representing the cost per token for a specific model from a specific provider.

type LLMCostPriceSource

type LLMCostPriceSource string

Identifies where an LLM cost price came from.

const (
	LLMCostPriceSourceManual LLMCostPriceSource = "manual"
	LLMCostPriceSourceSystem LLMCostPriceSource = "system"
)

func (LLMCostPriceSource) Valid

func (value LLMCostPriceSource) Valid() bool

type LLMCostProvider

type LLMCostProvider struct {
	// Identifier of the provider, e.g., "openai", "anthropic".
	ID string `json:"id"`
	// Name of the provider, e.g., "OpenAI", "Anthropic".
	Name string `json:"name"`
}

LLM Provider

type LLMCostService

type LLMCostService struct {
	// contains filtered or unexported fields
}

func (*LLMCostService) CreateOverride

func (s *LLMCostService) CreateOverride(ctx context.Context, request LLMCostOverrideCreate) (*LLMCostPrice, error)

Create a per-namespace price override.

func (*LLMCostService) DeleteOverride

func (s *LLMCostService) DeleteOverride(ctx context.Context, priceID string) error

Delete a per-namespace price override.

func (*LLMCostService) GetPrice

func (s *LLMCostService) GetPrice(ctx context.Context, priceID string) (*LLMCostPrice, error)

Get a specific LLM cost price by ID. Returns the price with overrides applied if any.

func (*LLMCostService) ListOverrides

List per-namespace price overrides.

func (*LLMCostService) ListOverridesAll

ListOverridesAll returns an iterator over all LLMCostPrice results, fetching pages of ListOverrides transparently. Iteration stops at the first error, which is yielded as the second value.

func (*LLMCostService) ListPrices

List global LLM cost prices. Returns prices with overrides applied if any.

func (*LLMCostService) ListPricesAll

ListPricesAll returns an iterator over all LLMCostPrice results, fetching pages of ListPrices transparently. Iteration stops at the first error, which is yielded as the second value.

type LifecycleController

type LifecycleController string

Identifies whether a resource lifecycle is controlled by OpenMeter or manually overridden by the API user.

Values:

- `system`: The resource lifecycle is controlled by OpenMeter. - `manual`: The resource lifecycle was manually overridden by the API user.

const (
	LifecycleControllerSystem LifecycleController = "system"
	LifecycleControllerManual LifecycleController = "manual"
)

func (LifecycleController) Valid

func (value LifecycleController) Valid() bool

type ListCustomerEntitlementAccessResponseData

type ListCustomerEntitlementAccessResponseData struct {
	// The list of entitlement access results.
	Data []EntitlementAccessResult `json:"data"`
}

List customer entitlement access response data.

type ListLLMCostOverridesFilter

type ListLLMCostOverridesFilter struct {
	// Filter by provider. e.g. ?filter[provider][eq]=openai
	Provider *StringFilter
	// Filter by model ID. e.g. ?filter[model_id][eq]=gpt-4
	ModelID *StringFilter
	// Filter by model name. e.g. ?filter[model_name][contains]=gpt
	ModelName *StringFilter
	// Filter by currency code. e.g. ?filter[currency][eq]=USD
	Currency *StringFilter
	// Filter by source. e.g. ?filter[source][eq]=system
	Source *StringFilter
}

type ListLLMCostOverridesParams

type ListLLMCostOverridesParams struct {
	Filter *ListLLMCostOverridesFilter
	Page   *PageParams
}

type ListLLMCostPricesFilter

type ListLLMCostPricesFilter struct {
	// Filter by provider. e.g. ?filter[provider][eq]=openai
	Provider *StringFilter
	// Filter by model ID. e.g. ?filter[model_id][eq]=gpt-4
	ModelID *StringFilter
	// Filter by model name. e.g. ?filter[model_name][contains]=gpt
	ModelName *StringFilter
	// Filter by currency code. e.g. ?filter[currency][eq]=USD
	Currency *StringFilter
	// Filter by source. e.g. ?filter[source][eq]=system
	Source *StringFilter
}

type ListLLMCostPricesParams

type ListLLMCostPricesParams struct {
	Filter *ListLLMCostPricesFilter
	Sort   *Sort
	Page   *PageParams
}

type Meter

type Meter struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	Key       string     `json:"key"`
	// The aggregation type to use for the meter.
	Aggregation MeterAggregation `json:"aggregation"`
	// The event type to include in the aggregation.
	EventType string `json:"event_type"`
	// The date since the meter should include events. Useful to skip old events. If
	// not specified, all historical events are included.
	EventsFrom *time.Time `json:"events_from,omitempty"`
	// JSONPath expression to extract the value from the ingested event's data
	// property.
	//
	// The ingested value for sum, avg, min, and max aggregations is a number or a
	// string that can be parsed to a number.
	//
	// For unique_count aggregation, the ingested value must be a string. For count
	// aggregation the value_property is ignored.
	ValueProperty *string `json:"value_property,omitempty"`
	// Named JSONPath expressions to extract the group by values from the event data.
	//
	// Keys must be unique and consist only alphanumeric and underscore characters.
	Dimensions map[string]string `json:"dimensions,omitempty"`
}

A meter is a configuration that defines how to match and aggregate events.

type MeterAggregation

type MeterAggregation string

The aggregation type to use for the meter.

const (
	MeterAggregationSum         MeterAggregation = "sum"
	MeterAggregationCount       MeterAggregation = "count"
	MeterAggregationUniqueCount MeterAggregation = "unique_count"
	MeterAggregationAvg         MeterAggregation = "avg"
	MeterAggregationMin         MeterAggregation = "min"
	MeterAggregationMax         MeterAggregation = "max"
	MeterAggregationLatest      MeterAggregation = "latest"
)

func (MeterAggregation) Valid

func (value MeterAggregation) Valid() bool

type MeterFilter

type MeterFilter struct {
	// Filter meters by key.
	Key *StringFilter
	// Filter meters by name.
	Name *StringFilter
}

type MeterListParams

type MeterListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *MeterFilter
}

type MeterPagePaginatedResponse

type MeterPagePaginatedResponse struct {
	Data []Meter       `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type MeterQueryFilters

type MeterQueryFilters struct {
	// Filters to apply to the dimensions of the query. For `subject` and `customer_id`
	// only equals ("eq", "in") comparisons are supported.
	Dimensions *map[string]QueryFilterStringMapItemInput `json:"dimensions,omitempty"`
}

Filters to apply to a meter query.

type MeterQueryGranularity

type MeterQueryGranularity string

The granularity of the time grouping. Time durations are specified in ISO 8601 format.

const (
	MeterQueryGranularityMinute MeterQueryGranularity = "PT1M"
	MeterQueryGranularityHour   MeterQueryGranularity = "PT1H"
	MeterQueryGranularityDay    MeterQueryGranularity = "P1D"
	MeterQueryGranularityMonth  MeterQueryGranularity = "P1M"
)

func (MeterQueryGranularity) Valid

func (value MeterQueryGranularity) Valid() bool

type MeterQueryRequest

type MeterQueryRequest struct {
	// The start of the period the usage is queried from.
	From *time.Time `json:"from,omitempty"`
	// The end of the period the usage is queried to.
	To *time.Time `json:"to,omitempty"`
	// The size of the time buckets to group the usage into. If not specified, the
	// usage is aggregated over the entire period.
	Granularity *MeterQueryGranularity `json:"granularity,omitempty"`
	// The value is the name of the time zone as defined in the IANA Time Zone Database
	// (http://www.iana.org/time-zones). The time zone is used to determine the start
	// and end of the time buckets. If not specified, the UTC timezone will be used.
	TimeZone *string `json:"time_zone,omitempty"`
	// The dimensions to group the results by.
	GroupByDimensions *[]string `json:"group_by_dimensions,omitempty"`
	// Filters to apply to the query.
	Filters *MeterQueryFilters `json:"filters,omitempty"`
}

A meter query request.

type MeterQueryResult

type MeterQueryResult struct {
	// The start of the period the usage is queried from.
	From *time.Time `json:"from,omitempty"`
	// The end of the period the usage is queried to.
	To *time.Time `json:"to,omitempty"`
	// The usage data. If no data is available, an empty array is returned.
	Data []MeterQueryRow `json:"data"`
}

Meter query result.

type MeterQueryRow

type MeterQueryRow struct {
	// The aggregated value.
	Value Numeric `json:"value"`
	// The start of the time bucket the value is aggregated over.
	From time.Time `json:"from"`
	// The end of the time bucket the value is aggregated over.
	To time.Time `json:"to"`
	// The dimensions the value is aggregated over. `subject` and `customer_id` are
	// reserved dimensions.
	Dimensions map[string]string `json:"dimensions"`
}

A row in the result of a meter query.

type MetersService

type MetersService struct {
	// contains filtered or unexported fields
}

func (*MetersService) Create

func (s *MetersService) Create(ctx context.Context, request CreateMeterRequest) (*Meter, error)

Create a meter.

func (*MetersService) Delete

func (s *MetersService) Delete(ctx context.Context, meterID string) error

Delete a meter.

func (*MetersService) Get

func (s *MetersService) Get(ctx context.Context, meterID string) (*Meter, error)

Get a meter by ID.

func (*MetersService) List

List meters.

func (*MetersService) ListAll

func (s *MetersService) ListAll(ctx context.Context, params MeterListParams) iter.Seq2[Meter, error]

ListAll returns an iterator over all Meter results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*MetersService) Query

func (s *MetersService) Query(ctx context.Context, meterID string, request MeterQueryRequest) (*MeterQueryResult, error)

Query a meter for usage.

Set `Accept: application/json` (the default) to get a structured JSON response. Set `Accept: text/csv` to download the same data as a CSV file suitable for spreadsheets. The CSV columns, in order, are:

`from, to, [subject,] [customer_id, customer_key, customer_name,] <dimensions...>, value`

The `subject` column is emitted only when `subject` is in the query's `group_by_dimensions`. The three `customer_*` columns are emitted together only when `customer_id` is in the query's `group_by_dimensions`.

func (*MetersService) QueryCSV

func (s *MetersService) QueryCSV(ctx context.Context, meterID string, request MeterQueryRequest) ([]byte, error)

func (*MetersService) QueryCSVStream

func (s *MetersService) QueryCSVStream(ctx context.Context, meterID string, request MeterQueryRequest) (io.ReadCloser, error)

func (*MetersService) Update

func (s *MetersService) Update(ctx context.Context, meterID string, request UpdateMeterRequest) (*Meter, error)

Update a meter.

type Nullable

type Nullable[T any] = nullable.Nullable[T]

Nullable represents a JSON field with three states: unspecified, explicit null, or a concrete value. Optional nullable fields use this as a value with omitempty; do not wrap it in a pointer.

func Null

func Null[T any]() Nullable[T]

Null constructs an explicit JSON null.

func NullableValue

func NullableValue[T any](value T) Nullable[T]

NullableValue constructs a non-null value.

type Numeric

type Numeric = string

Numeric represents an arbitrary-precision number. The API encodes it as a decimal string (e.g. "12.3456") to avoid float precision loss, so the SDK surfaces it as a string. Parse with a decimal library when arithmetic is needed.

type NumericFilter

type NumericFilter struct {
	Eq  *float64
	Neq *float64
	Gt  *float64
	Gte *float64
	Lt  *float64
	Lte *float64
	Oeq []float64
}

NumericFilter expresses numeric comparison operators.

type OneOrMany

type OneOrMany[T any] struct {
	// contains filtered or unexported fields
}

OneOrMany represents a JSON value that accepts either one T or an array of T. The zero value holds neither variant and marshals as JSON null.

func Many

func Many[T any](values []T) OneOrMany[T]

Many wraps an array. A non-nil empty slice is encoded as [].

func One

func One[T any](value T) OneOrMany[T]

One wraps a single value.

func (OneOrMany[T]) AsMany

func (value OneOrMany[T]) AsMany() ([]T, bool)

AsMany returns the array. The boolean is false when the single-value variant is set or the value is empty.

func (OneOrMany[T]) AsOne

func (value OneOrMany[T]) AsOne() (*T, bool)

AsOne returns the single value. The boolean is false when the array variant is set or the value is empty.

func (OneOrMany[T]) MarshalJSON

func (value OneOrMany[T]) MarshalJSON() ([]byte, error)

func (*OneOrMany[T]) UnmarshalJSON

func (value *OneOrMany[T]) UnmarshalJSON(data []byte) error

type Option

type Option func(*Client)

Option configures a Client during New.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the default *http.Client. The provided client owns all transport behavior: retries, timeouts, proxies, TLS, and tracing. Pass nil to keep the default.

func WithToken

func WithToken(token string) Option

WithToken sets the bearer token sent in the Authorization header of every request. The header is applied during request construction, so it is honored regardless of any client injected via WithHTTPClient.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header sent with each request.

type OrganizationDefaultTaxCodes

type OrganizationDefaultTaxCodes struct {
	// Default tax code for invoicing.
	InvoicingTaxCode TaxCodeReference `json:"invoicing_tax_code"`
	// Default tax code for credit grants.
	CreditGrantTaxCode TaxCodeReference `json:"credit_grant_tax_code"`
	// Timestamp of creation.
	CreatedAt time.Time `json:"created_at"`
	// Timestamp of last update.
	UpdatedAt time.Time `json:"updated_at"`
}

Organization-level default tax code references.

Stores the default tax codes applied to specific billing contexts for this organization. Provisioned automatically when the organization is created.

type PageMeta

type PageMeta struct {
	Number int `json:"number"`
	Size   int `json:"size"`
	Total  int `json:"total"`
}

type PageParams

type PageParams struct {
	Size   *int
	Number *int
}

PageParams selects a numbered page.

type PaginatedMeta

type PaginatedMeta struct {
	Page PageMeta `json:"page"`
}

type Party

type Party struct {
	// Unique identifier for the party.
	ID *string `json:"id,omitempty"`
	// An optional unique key of the party.
	Key *string `json:"key,omitempty"`
	// Legal name or representation of the party.
	Name *string `json:"name,omitempty"`
	// The entity's legal identification used for tax purposes. They may have other
	// numbers, but we're only interested in those valid for tax purposes.
	TaxID *PartyTaxIdentity `json:"tax_id,omitempty"`
	// Address for where information should be sent if needed.
	Addresses *PartyAddresses `json:"addresses,omitempty"`
}

Party represents a person or business entity.

type PartyAddresses

type PartyAddresses struct {
	// Billing address.
	BillingAddress Address `json:"billing_address"`
}

A collection of addresses for the party.

type PartyTaxIdentity

type PartyTaxIdentity struct {
	// Normalized tax identification code shown on the original identity document.
	Code *string `json:"code,omitempty"`
}

Identity stores the details required to identify an entity for tax purposes in a specific country.

type Plan

type Plan struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// A key is a semi-unique string that is used to identify the plan. It is used to
	// reference the latest `active` version of the plan and is unique with the version
	// number.
	Key string `json:"key"`
	// Plans are versioned to allow you to make changes without affecting running
	// subscriptions.
	Version int64 `json:"version"`
	// The currency code of the plan.
	Currency string `json:"currency"`
	// The billing cadence for subscriptions using this plan.
	BillingCadence string `json:"billing_cadence"`
	// Whether pro-rating is enabled for this plan.
	ProRatingEnabled *bool `json:"pro_rating_enabled,omitempty"`
	// The date and time when the plan becomes `active`. When not specified, the plan
	// is in `draft` status.
	EffectiveFrom *time.Time `json:"effective_from,omitempty"`
	// A scheduled date and time when the plan becomes `archived`. When not specified,
	// the plan is in `active` status indefinitely.
	EffectiveTo *time.Time `json:"effective_to,omitempty"`
	// The status of the plan. Computed based on the effective start and end dates:
	//
	// - `draft`: `effective_from` is not set.
	// - `scheduled`: `now < effective_from`.
	// - `active`: `effective_from <= now` and (`effective_to` is not set or
	// `now < effective_to`).
	// - `archived`: `effective_to <= now`.
	Status PlanStatus `json:"status"`
	// The plan phases define the pricing ramp for a subscription. A phase switch
	// occurs only at the end of a billing period. At least one phase is required.
	Phases []PlanPhase `json:"phases"`
	// Settlement mode for plan.
	//
	// Values:
	//
	// - `credit_then_invoice`: Credits are applied first, then any remainder is
	// invoiced.
	// - `credit_only`: Usage is settled exclusively against credits.
	SettlementMode *SettlementMode `json:"settlement_mode,omitempty"`
	// List of validation errors in `draft` state that prevent the plan from being
	// published.
	ValidationErrors []ProductCatalogValidationError `json:"validation_errors,omitempty"`
}

Plans provide a template for subscriptions.

type PlanAddon

type PlanAddon struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The add-on associated with the plan.
	Addon AddonReference `json:"addon"`
	// The key of the plan phase from which the add-on becomes available for purchase.
	FromPlanPhase string `json:"from_plan_phase"`
	// The maximum number of times the add-on can be purchased for the plan. For
	// single-instance add-ons this field must be omitted. For multi-instance add-ons
	// when omitted, unlimited quantity can be purchased.
	MaxQuantity *int64 `json:"max_quantity,omitempty"`
	// List of validation errors.
	ValidationErrors []ProductCatalogValidationError `json:"validation_errors,omitempty"`
}

PlanAddon represents an association between a plan and an add-on, controlling which add-ons are available for purchase within a plan.

type PlanAddonListParams

type PlanAddonListParams struct {
	Page *PageParams
}

type PlanAddonPagePaginatedResponse

type PlanAddonPagePaginatedResponse struct {
	Data []PlanAddon   `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type PlanAddonsService

type PlanAddonsService struct {
	// contains filtered or unexported fields
}

func (*PlanAddonsService) Create

func (s *PlanAddonsService) Create(ctx context.Context, planID string, request CreatePlanAddonRequest) (*PlanAddon, error)

Add an add-on to a plan.

func (*PlanAddonsService) Delete

func (s *PlanAddonsService) Delete(ctx context.Context, planID string, planAddonID string) error

Remove an add-on from a plan.

func (*PlanAddonsService) Get

func (s *PlanAddonsService) Get(ctx context.Context, planID string, planAddonID string) (*PlanAddon, error)

Get an add-on association for a plan.

func (*PlanAddonsService) List

List add-ons associated with a plan.

func (*PlanAddonsService) ListAll

ListAll returns an iterator over all PlanAddon results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*PlanAddonsService) Update

func (s *PlanAddonsService) Update(ctx context.Context, planID string, planAddonID string, request UpsertPlanAddonRequest) (*PlanAddon, error)

Update an add-on association for a plan.

type PlanFilter

type PlanFilter struct {
	Key      *StringFilter
	Name     *StringFilter
	Status   *StringExactFilter
	Currency *StringExactFilter
}

type PlanListParams

type PlanListParams struct {
	Page   *PageParams
	Sort   *Sort
	Filter *PlanFilter
}

type PlanPagePaginatedResponse

type PlanPagePaginatedResponse struct {
	Data []Plan        `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type PlanPhase

type PlanPhase struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	Key         string            `json:"key"`
	// The duration of the phase. When not specified, the phase runs indefinitely. Only
	// the last phase may omit the duration.
	Duration *string `json:"duration,omitempty"`
	// The rate cards of the plan.
	RateCards []RateCard `json:"rate_cards"`
}

The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.

type PlanPhaseInput

type PlanPhaseInput struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// The duration of the phase. When not specified, the phase runs indefinitely. Only
	// the last phase may omit the duration.
	Duration *string `json:"duration,omitempty"`
	// The rate cards of the plan.
	RateCards []RateCardInput `json:"rate_cards"`
}

The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.

type PlanStatus

type PlanStatus string

The status of a plan.

- `draft`: The plan has not yet been published and can be edited. - `active`: The plan is published and can be used in subscriptions. - `archived`: The plan is no longer available for use. - `scheduled`: The plan is scheduled to be published at a future date.

const (
	PlanStatusDraft     PlanStatus = "draft"
	PlanStatusActive    PlanStatus = "active"
	PlanStatusArchived  PlanStatus = "archived"
	PlanStatusScheduled PlanStatus = "scheduled"
)

func (PlanStatus) Valid

func (value PlanStatus) Valid() bool

type PlansService

type PlansService struct {
	// contains filtered or unexported fields
}

func (*PlansService) Archive

func (s *PlansService) Archive(ctx context.Context, planID string) (*Plan, error)

Archive a plan version.

func (*PlansService) Create

func (s *PlansService) Create(ctx context.Context, request CreatePlanRequest) (*Plan, error)

Create a new plan.

func (*PlansService) Delete

func (s *PlansService) Delete(ctx context.Context, planID string) error

Delete a plan by id.

func (*PlansService) Get

func (s *PlansService) Get(ctx context.Context, planID string) (*Plan, error)

Get a plan by id.

func (*PlansService) List

List all plans.

func (*PlansService) ListAll

func (s *PlansService) ListAll(ctx context.Context, params PlanListParams) iter.Seq2[Plan, error]

ListAll returns an iterator over all Plan results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*PlansService) Publish

func (s *PlansService) Publish(ctx context.Context, planID string) (*Plan, error)

Publish a plan version.

func (*PlansService) Update

func (s *PlansService) Update(ctx context.Context, planID string, request UpsertPlanRequest) (*Plan, error)

Update a plan by id.

type Price

type Price struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Price.

Price is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the PriceFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func PriceFromPriceFlat

func PriceFromPriceFlat(value PriceFlat) (Price, error)

func PriceFromPriceFree

func PriceFromPriceFree(value PriceFree) (Price, error)

func PriceFromPriceGraduated

func PriceFromPriceGraduated(value PriceGraduated) (Price, error)

func PriceFromPriceUnit

func PriceFromPriceUnit(value PriceUnit) (Price, error)

func PriceFromPriceVolume

func PriceFromPriceVolume(value PriceVolume) (Price, error)

func (Price) AsPriceFlat

func (u Price) AsPriceFlat() (*PriceFlat, error)

func (Price) AsPriceFree

func (u Price) AsPriceFree() (*PriceFree, error)

func (Price) AsPriceGraduated

func (u Price) AsPriceGraduated() (*PriceGraduated, error)

func (Price) AsPriceUnit

func (u Price) AsPriceUnit() (*PriceUnit, error)

func (Price) AsPriceVolume

func (u Price) AsPriceVolume() (*PriceVolume, error)

func (Price) MarshalJSON

func (u Price) MarshalJSON() ([]byte, error)

func (*Price) UnmarshalJSON

func (u *Price) UnmarshalJSON(data []byte) error

type PriceFlat

type PriceFlat struct {
	// The type of the price.
	Type PriceType `json:"type"`
	// The amount of the flat price.
	Amount Numeric `json:"amount"`
}

Flat price.

type PriceFree

type PriceFree struct {
	// The type of the price.
	Type PriceType `json:"type"`
}

Free price.

type PriceGraduated

type PriceGraduated struct {
	// The type of the price.
	Type PriceType `json:"type"`
	// The tiers of the graduated price. At least one tier is required.
	Tiers []PriceTier `json:"tiers"`
}

Graduated tiered price.

Each tier's rate applies only to the usage within that tier. Pricing can change as cumulative usage crosses tier boundaries.

When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.

type PricePagePaginatedResponse

type PricePagePaginatedResponse struct {
	Data []LLMCostPrice `json:"data"`
	Meta PaginatedMeta  `json:"meta"`
}

Page paginated response.

type PricePaymentTerm

type PricePaymentTerm string

The payment term of a flat price.

const (
	PricePaymentTermInAdvance PricePaymentTerm = "in_advance"
	PricePaymentTermInArrears PricePaymentTerm = "in_arrears"
)

func (PricePaymentTerm) Valid

func (value PricePaymentTerm) Valid() bool

type PriceTier

type PriceTier struct {
	// Up to and including this quantity will be contained in the tier. If undefined,
	// the tier is open-ended (the last tier).
	UpToAmount *Numeric `json:"up_to_amount,omitempty"`
	// The flat price component of the tier. Charged once when the tier is entered.
	FlatPrice *PriceFlat `json:"flat_price,omitempty"`
	// The unit price component of the tier. Charged per billing unit within the tier.
	UnitPrice *PriceUnit `json:"unit_price,omitempty"`
}

A price tier used in graduated and volume pricing.

At least one price component (flat_price or unit_price) must be set. When UnitConfig is present on the rate card, up_to_amount is expressed in converted billing units.

type PriceType

type PriceType string

The type of the price.

- `free`: No charge, the rate card is included at no cost. - `flat`: A fixed amount charged once per billing period, regardless of usage. - `unit`: A fixed rate charged per billing unit consumed. - `graduated`: Tiered pricing where each tier's rate applies only to usage within that tier. - `volume`: Tiered pricing where the rate for the highest tier reached applies to all units in the period.

const (
	PriceTypeFree      PriceType = "free"
	PriceTypeFlat      PriceType = "flat"
	PriceTypeUnit      PriceType = "unit"
	PriceTypeGraduated PriceType = "graduated"
	PriceTypeVolume    PriceType = "volume"
)

func (PriceType) Valid

func (value PriceType) Valid() bool

type PriceUnit

type PriceUnit struct {
	// The type of the price.
	Type PriceType `json:"type"`
	// The amount of the unit price.
	Amount Numeric `json:"amount"`
}

Unit price.

Charges a fixed rate per billing unit. When UnitConfig is present on the rate card, billing units are the converted quantities (e.g. GB instead of bytes).

type PriceVolume

type PriceVolume struct {
	// The type of the price.
	Type PriceType `json:"type"`
	// The tiers of the volume price. At least one tier is required.
	Tiers []PriceTier `json:"tiers"`
}

Volume tiered price.

The maximum quantity within a period determines the per-unit price for all units in that period.

When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.

type ProductCatalogValidationError

type ProductCatalogValidationError struct {
	// Machine-readable error code.
	Code string `json:"code"`
	// Human-readable description of the error.
	Message string `json:"message"`
	// Additional structured context.
	Attributes map[string]any `json:"attributes,omitempty"`
	// The path to the field.
	Field string `json:"field"`
}

Validation errors providing detailed description of the issue.

type Profile

type Profile struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// The name and contact information for the supplier this billing profile
	// represents
	Supplier Party `json:"supplier"`
	// The billing workflow settings for this profile
	Workflow Workflow `json:"workflow"`
	// The applications used by this billing profile.
	Apps ProfileAppReferences `json:"apps"`
	// Whether this is the default profile.
	Default bool `json:"default"`
}

Billing profiles contain the settings for billing and controls invoice generation.

type ProfileAppReferences

type ProfileAppReferences struct {
	// The tax app used for this workflow.
	Tax AppReference `json:"tax"`
	// The invoicing app used for this workflow.
	Invoicing AppReference `json:"invoicing"`
	// The payment app used for this workflow.
	Payment AppReference `json:"payment"`
}

References to the applications used by a billing profile.

type ProfileListParams

type ProfileListParams struct {
	Page *PageParams
}

type ProfilePagePaginatedResponse

type ProfilePagePaginatedResponse struct {
	Data []Profile     `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type ProfileReference

type ProfileReference struct {
	// The ID of the billing profile.
	ID string `json:"id"`
}

Billing profile reference.

type QueryFilterString

type QueryFilterString struct {
	// The attribute equals the provided value.
	Eq *string `json:"eq,omitempty"`
	// The attribute does not equal the provided value.
	Neq *string `json:"neq,omitempty"`
	// The attribute is one of the provided values.
	In []string `json:"in,omitempty"`
	// The attribute is not one of the provided values.
	Nin []string `json:"nin,omitempty"`
	// The attribute contains the provided value.
	Contains *string `json:"contains,omitempty"`
	// The attribute does not contain the provided value.
	Ncontains *string `json:"ncontains,omitempty"`
	// Combines the provided filters with a logical AND.
	And []QueryFilterString `json:"and,omitempty"`
	// Combines the provided filters with a logical OR.
	Or []QueryFilterString `json:"or,omitempty"`
}

A query filter for a string attribute. Operators are mutually exclusive, only one operator is allowed at a time.

type QueryFilterStringInput

type QueryFilterStringInput struct {
	// The attribute equals the provided value.
	Eq *string `json:"eq,omitempty"`
	// The attribute does not equal the provided value.
	Neq *string `json:"neq,omitempty"`
	// The attribute is one of the provided values.
	In *[]string `json:"in,omitempty"`
	// The attribute is not one of the provided values.
	Nin *[]string `json:"nin,omitempty"`
	// The attribute contains the provided value.
	Contains *string `json:"contains,omitempty"`
	// The attribute does not contain the provided value.
	Ncontains *string `json:"ncontains,omitempty"`
	// Combines the provided filters with a logical AND.
	And *[]QueryFilterStringInput `json:"and,omitempty"`
	// Combines the provided filters with a logical OR.
	Or *[]QueryFilterStringInput `json:"or,omitempty"`
}

A query filter for a string attribute. Operators are mutually exclusive, only one operator is allowed at a time.

type QueryFilterStringMapItem

type QueryFilterStringMapItem struct {
	// The attribute exists.
	Exists *bool `json:"exists,omitempty"`
	// The attribute equals the provided value.
	Eq *string `json:"eq,omitempty"`
	// The attribute does not equal the provided value.
	Neq *string `json:"neq,omitempty"`
	// The attribute is one of the provided values.
	In []string `json:"in,omitempty"`
	// The attribute is not one of the provided values.
	Nin []string `json:"nin,omitempty"`
	// The attribute contains the provided value.
	Contains *string `json:"contains,omitempty"`
	// The attribute does not contain the provided value.
	Ncontains *string `json:"ncontains,omitempty"`
	// Combines the provided filters with a logical AND.
	And []QueryFilterString `json:"and,omitempty"`
	// Combines the provided filters with a logical OR.
	Or []QueryFilterString `json:"or,omitempty"`
}

A query filter for an item in a string map attribute. Operators are mutually exclusive, only one operator is allowed at a time.

type QueryFilterStringMapItemInput

type QueryFilterStringMapItemInput struct {
	// The attribute exists.
	Exists *bool `json:"exists,omitempty"`
	// The attribute equals the provided value.
	Eq *string `json:"eq,omitempty"`
	// The attribute does not equal the provided value.
	Neq *string `json:"neq,omitempty"`
	// The attribute is one of the provided values.
	In *[]string `json:"in,omitempty"`
	// The attribute is not one of the provided values.
	Nin *[]string `json:"nin,omitempty"`
	// The attribute contains the provided value.
	Contains *string `json:"contains,omitempty"`
	// The attribute does not contain the provided value.
	Ncontains *string `json:"ncontains,omitempty"`
	// Combines the provided filters with a logical AND.
	And *[]QueryFilterStringInput `json:"and,omitempty"`
	// Combines the provided filters with a logical OR.
	Or *[]QueryFilterStringInput `json:"or,omitempty"`
}

A query filter for an item in a string map attribute. Operators are mutually exclusive, only one operator is allowed at a time.

type RateCard

type RateCard struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	Key         string            `json:"key"`
	// The feature associated with the rate card.
	Feature *FeatureReference `json:"feature,omitempty"`
	// The billing cadence of the rate card. When null, the charge is one-time
	// (non-recurring). Only valid for flat prices.
	BillingCadence *string `json:"billing_cadence,omitempty"`
	// The price of the rate card.
	Price Price `json:"price"`
	// Unit conversion configuration for the rate card.
	//
	// Synthesized on read for plans authored with v1 dynamic or package prices:
	// dynamic prices map to a unit price with a multiply unit config, and package
	// prices map to a unit price with a divide unit config.
	//
	// Accepted on create and update only when the UnitConfig feature is enabled on the
	// deployment; otherwise rejected.
	UnitConfig *UnitConfig `json:"unit_config,omitempty"`
	// The payment term of the rate card. In advance payment term can only be used for
	// flat prices.
	PaymentTerm *PricePaymentTerm `json:"payment_term,omitempty"`
	// Spend commitments for this rate card. Only applicable to usage-based prices
	// (unit, graduated, volume).
	Commitments *SpendCommitments `json:"commitments,omitempty"`
	// The discounts of the rate card.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
	// The tax config of the rate card.
	TaxConfig *RateCardTaxConfig `json:"tax_config,omitempty"`
	// The entitlement template granted to subscribers of a plan or addon containing
	// this rate card. Requires `feature` to be set.
	Entitlement *RateCardEntitlement `json:"entitlement,omitempty"`
}

A rate card defines the pricing and entitlement of a feature or service.

type RateCardBooleanEntitlement

type RateCardBooleanEntitlement struct {
	// The type of the entitlement template.
	Type EntitlementType `json:"type"`
}

The entitlement template of a boolean entitlement.

type RateCardDiscounts

type RateCardDiscounts struct {
	// Percentage discount applied to the price (0–100).
	Percentage *float64 `json:"percentage,omitempty"`
	// Number of usage units granted free before billing starts. Only applies to
	// usage-based lines (not flat fees). Usage is treated as zero until this amount is
	// exhausted.
	Usage *Numeric `json:"usage,omitempty"`
}

Discount configuration for a rate card.

type RateCardEntitlement

type RateCardEntitlement struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

Entitlement template configured on a rate card. The feature is taken from the rate card itself, so it is omitted here.

RateCardEntitlement is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the RateCardEntitlementFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func RateCardEntitlementFromRateCardBooleanEntitlement

func RateCardEntitlementFromRateCardBooleanEntitlement(value RateCardBooleanEntitlement) (RateCardEntitlement, error)

func RateCardEntitlementFromRateCardMeteredEntitlement

func RateCardEntitlementFromRateCardMeteredEntitlement(value RateCardMeteredEntitlement) (RateCardEntitlement, error)

func RateCardEntitlementFromRateCardStaticEntitlement

func RateCardEntitlementFromRateCardStaticEntitlement(value RateCardStaticEntitlement) (RateCardEntitlement, error)

func (RateCardEntitlement) AsRateCardBooleanEntitlement

func (u RateCardEntitlement) AsRateCardBooleanEntitlement() (*RateCardBooleanEntitlement, error)

func (RateCardEntitlement) AsRateCardMeteredEntitlement

func (u RateCardEntitlement) AsRateCardMeteredEntitlement() (*RateCardMeteredEntitlement, error)

func (RateCardEntitlement) AsRateCardStaticEntitlement

func (u RateCardEntitlement) AsRateCardStaticEntitlement() (*RateCardStaticEntitlement, error)

func (RateCardEntitlement) MarshalJSON

func (u RateCardEntitlement) MarshalJSON() ([]byte, error)

func (*RateCardEntitlement) UnmarshalJSON

func (u *RateCardEntitlement) UnmarshalJSON(data []byte) error

type RateCardInput

type RateCardInput struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	Key         string             `json:"key"`
	// The feature associated with the rate card.
	Feature *FeatureReference `json:"feature,omitempty"`
	// The billing cadence of the rate card. When null, the charge is one-time
	// (non-recurring). Only valid for flat prices.
	BillingCadence *string `json:"billing_cadence,omitempty"`
	// The price of the rate card.
	Price Price `json:"price"`
	// Unit conversion configuration for the rate card.
	//
	// Synthesized on read for plans authored with v1 dynamic or package prices:
	// dynamic prices map to a unit price with a multiply unit config, and package
	// prices map to a unit price with a divide unit config.
	//
	// Accepted on create and update only when the UnitConfig feature is enabled on the
	// deployment; otherwise rejected.
	UnitConfig *UnitConfig `json:"unit_config,omitempty"`
	// The payment term of the rate card. In advance payment term can only be used for
	// flat prices.
	PaymentTerm *PricePaymentTerm `json:"payment_term,omitempty"`
	// Spend commitments for this rate card. Only applicable to usage-based prices
	// (unit, graduated, volume).
	Commitments *SpendCommitments `json:"commitments,omitempty"`
	// The discounts of the rate card.
	Discounts *RateCardDiscounts `json:"discounts,omitempty"`
	// The tax config of the rate card.
	TaxConfig *RateCardTaxConfig `json:"tax_config,omitempty"`
	// The entitlement template granted to subscribers of a plan or addon containing
	// this rate card. Requires `feature` to be set.
	Entitlement *RateCardEntitlement `json:"entitlement,omitempty"`
}

A rate card defines the pricing and entitlement of a feature or service.

type RateCardMeteredEntitlement

type RateCardMeteredEntitlement struct {
	// The type of the entitlement template.
	Type EntitlementType `json:"type"`
	// If soft limit is true, the subject can use the feature even if the entitlement
	// is exhausted; access remains granted.
	IsSoftLimit *bool `json:"is_soft_limit,omitempty"`
	// The amount of usage granted each usage period, in the feature's unit. Usage is
	// counted against this allowance and the balance resets every usage period. When
	// `is_soft_limit` is true the subject keeps access after the limit is reached;
	// otherwise access is denied once the allowance is exhausted.
	Limit *float64 `json:"limit,omitempty"`
	// The reset interval of the metered entitlement in ISO8601 format. Defaults to the
	// billing cadence of the rate card.
	UsagePeriod *string `json:"usage_period,omitempty"`
}

The entitlement template of a metered entitlement.

type RateCardProrationConfiguration

type RateCardProrationConfiguration struct {
	// The proration mode of the rate card.
	Mode RateCardProrationMode `json:"mode"`
}

The proration configuration of the rate card.

type RateCardProrationMode

type RateCardProrationMode string

The proration mode of the rate card.

Values:

- `no_proration`: No proration. - `prorate_prices`: Prorate the price based on the time remaining in the billing period.

const (
	RateCardProrationModeNoProration   RateCardProrationMode = "no_proration"
	RateCardProrationModeProratePrices RateCardProrationMode = "prorate_prices"
)

func (RateCardProrationMode) Valid

func (value RateCardProrationMode) Valid() bool

type RateCardStaticEntitlement

type RateCardStaticEntitlement struct {
	// The type of the entitlement template.
	Type EntitlementType `json:"type"`
	// The entitlement config as a JSON object. Returned when checking entitlement
	// access; useful for configuring fine-grained access settings implemented in your
	// own system.
	Config any `json:"config"`
}

The entitlement template of a static entitlement.

type RateCardTaxConfig

type RateCardTaxConfig struct {
	Behavior *TaxBehavior     `json:"behavior,omitempty"`
	Code     TaxCodeReference `json:"code"`
}

The tax config of the rate card.

type RecurringPeriod

type RecurringPeriod struct {
	// A date-time anchor to base the recurring period on.
	Anchor time.Time `json:"anchor"`
	// The interval duration in ISO 8601 format.
	Interval string `json:"interval"`
}

Recurring period with an anchor and an interval.

type SettlementMode

type SettlementMode string

Settlement mode for billing.

Values:

- `credit_then_invoice`: Credits are applied first, then any remainder is invoiced. - `credit_only`: Usage is settled exclusively against credits.

const (
	SettlementModeCreditThenInvoice SettlementMode = "credit_then_invoice"
	SettlementModeCreditOnly        SettlementMode = "credit_only"
)

func (SettlementMode) Valid

func (value SettlementMode) Valid() bool

type Sort

type Sort struct {
	By    string
	Order SortOrder
}

Sort selects a wire field and optional direction.

type SortOrder

type SortOrder string

SortOrder is the direction of a sort expression.

const (
	SortOrderAsc  SortOrder = "asc"
	SortOrderDesc SortOrder = "desc"
)

type SpendCommitments

type SpendCommitments struct {
	// The customer is committed to spend at least the amount.
	MinimumAmount *Numeric `json:"minimum_amount,omitempty"`
	// The customer is limited to spend at most the amount.
	MaximumAmount *Numeric `json:"maximum_amount,omitempty"`
}

Spend commitments for a rate card. The customer is committed to spend at least the minimum amount and at most the maximum amount.

type StringExactFilter

type StringExactFilter struct {
	Eq  *string
	Neq *string
	Oeq []string
}

StringExactFilter expresses exact comparisons for strings and ULIDs.

type StringFilter

type StringFilter struct {
	Eq        *string
	Neq       *string
	Gt        *string
	Gte       *string
	Lt        *string
	Lte       *string
	Contains  *string
	Oeq       []string
	Ocontains []string
	Exists    *bool
}

StringFilter expresses the comparison operators accepted for string fields.

type SubscriptionAddon

type SubscriptionAddon struct {
	ID     string            `json:"id"`
	Labels map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string `json:"description,omitempty"`
	// The add-on associated with the subscription.
	Addon AddonReference `json:"addon"`
	// The quantity of the add-on. Always 1 for single instance add-ons.
	Quantity int64 `json:"quantity"`
	// An ISO-8601 timestamp representation of which point in time the quantity was
	// resolved to.
	QuantityAt time.Time `json:"quantity_at"`
	// An ISO-8601 timestamp representation of the cadence start of the resource.
	ActiveFrom time.Time `json:"active_from"`
	// An ISO-8601 timestamp representation of the cadence end of the resource.
	ActiveTo *time.Time `json:"active_to,omitempty"`
	// The timeline of the add-on. The returned periods are sorted and continuous.
	Timeline []SubscriptionAddonTimelineSegment `json:"timeline"`
	// The rate cards of the add-on.
	RateCards []SubscriptionAddonRateCard `json:"rate_cards"`
}

Addon purchased with a subscription.

type SubscriptionAddonListParams

type SubscriptionAddonListParams struct {
	Page *PageParams
	Sort *Sort
}

type SubscriptionAddonPagePaginatedResponse

type SubscriptionAddonPagePaginatedResponse struct {
	Data []SubscriptionAddon `json:"data"`
	Meta PaginatedMeta       `json:"meta"`
}

Page paginated response.

type SubscriptionAddonRateCard

type SubscriptionAddonRateCard struct {
	// The rate card.
	RateCard RateCard `json:"rate_card"`
	// The IDs of the subscription items that this rate card belongs to.
	AffectedSubscriptionItemIds []string `json:"affected_subscription_item_ids"`
}

A rate card for a subscription add-on.

type SubscriptionAddonTimelineSegment

type SubscriptionAddonTimelineSegment struct {
	// An ISO-8601 timestamp representation of the cadence start of the resource.
	ActiveFrom time.Time `json:"active_from"`
	// An ISO-8601 timestamp representation of the cadence end of the resource.
	ActiveTo *time.Time `json:"active_to,omitempty"`
	// The quantity of the add-on for the given period.
	Quantity int64 `json:"quantity"`
}

A subscription add-on event.

type SubscriptionCancel

type SubscriptionCancel struct {
	// If not provided the subscription is canceled immediately.
	Timing *SubscriptionEditTiming `json:"timing,omitempty"`
}

Request for canceling a subscription.

type SubscriptionChange

type SubscriptionChange struct {
	Labels *map[string]string `json:"labels,omitempty"`
	// Settlement mode for billing.
	//
	// Values:
	//
	// - `credit_then_invoice`: Credits are applied first, then any remainder is
	// invoiced.
	// - `credit_only`: Usage is settled exclusively against credits.
	SettlementMode *SettlementMode `json:"settlement_mode,omitempty"`
	// The customer to create the subscription for.
	Customer SubscriptionChangeCustomer `json:"customer"`
	// The plan reference of the subscription.
	Plan SubscriptionChangePlan `json:"plan"`
	// A billing anchor is the fixed point in time that determines the subscription's
	// recurring billing cycle. It affects when charges occur and how prorations are
	// calculated. Common anchors:
	//
	// - Calendar month (1st of each month): `2025-01-01T00:00:00Z`
	// - Subscription anniversary (day customer signed up)
	// - Custom date (customer-specified day)
	//
	// If not provided, the subscription will be created with the subscription's
	// creation time as the billing anchor.
	BillingAnchor *time.Time `json:"billing_anchor,omitempty"`
	// Timing configuration for the change, when the change should take effect. For
	// changing a subscription, the accepted values depend on the subscription
	// configuration.
	Timing SubscriptionEditTiming `json:"timing"`
}

Request for changing a subscription.

type SubscriptionChangeCustomer

type SubscriptionChangeCustomer struct {
	// The ID of the customer to create the subscription for.
	//
	// Either customer ID or customer key must be provided. If both are provided, the
	// ID will be used.
	ID *string `json:"id,omitempty"`
	// The key of the customer to create the subscription for.
	//
	// Either customer ID or customer key must be provided. If both are provided, the
	// ID will be used.
	Key *string `json:"key,omitempty"`
}

type SubscriptionChangePlan

type SubscriptionChangePlan struct {
	// The plan ID of the subscription. Set if subscription is created from a plan.
	//
	// ID or Key of the plan is required if creating a subscription from a plan. If
	// both are provided, the ID will be used.
	ID *string `json:"id,omitempty"`
	// The plan Key of the subscription, if any. Set if subscription is created from a
	// plan.
	//
	// ID or Key of the plan is required if creating a subscription from a plan. If
	// both are provided, the ID will be used.
	Key *string `json:"key,omitempty"`
	// The plan version of the subscription, if any. If not provided, the latest
	// version of the plan will be used.
	Version *int64 `json:"version,omitempty"`
}

type SubscriptionChangeResponse

type SubscriptionChangeResponse struct {
	// The current subscription before the change.
	Current BillingSubscription `json:"current"`
	// The new state of the subscription after the change.
	Next BillingSubscription `json:"next"`
}

Response for changing a subscription.

type SubscriptionCreate

type SubscriptionCreate struct {
	Labels *map[string]string `json:"labels,omitempty"`
	// Settlement mode for billing.
	//
	// Values:
	//
	// - `credit_then_invoice`: Credits are applied first, then any remainder is
	// invoiced.
	// - `credit_only`: Usage is settled exclusively against credits.
	SettlementMode *SettlementMode `json:"settlement_mode,omitempty"`
	// The customer to create the subscription for.
	Customer SubscriptionChangeCustomer `json:"customer"`
	// The plan reference of the subscription.
	Plan SubscriptionChangePlan `json:"plan"`
	// A billing anchor is the fixed point in time that determines the subscription's
	// recurring billing cycle. It affects when charges occur and how prorations are
	// calculated. Common anchors:
	//
	// - Calendar month (1st of each month): `2025-01-01T00:00:00Z`
	// - Subscription anniversary (day customer signed up)
	// - Custom date (customer-specified day)
	//
	// If not provided, the subscription will be created with the subscription's
	// creation time as the billing anchor.
	BillingAnchor *time.Time `json:"billing_anchor,omitempty"`
}

Subscription create request.

type SubscriptionEditTiming

type SubscriptionEditTiming struct {
	// contains filtered or unexported fields
}

Subscription edit timing defined when the changes should take effect. If the provided configuration is not supported by the subscription, an error will be returned.

SubscriptionEditTiming is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the SubscriptionEditTimingFrom* constructors.

func SubscriptionEditTimingFromCustom

func SubscriptionEditTimingFromCustom(value time.Time) (SubscriptionEditTiming, error)

func SubscriptionEditTimingFromEnum

func SubscriptionEditTimingFromEnum(value SubscriptionEditTimingEnum) (SubscriptionEditTiming, error)

func (SubscriptionEditTiming) AsCustom

func (u SubscriptionEditTiming) AsCustom() (*time.Time, error)

func (SubscriptionEditTiming) AsEnum

func (SubscriptionEditTiming) MarshalJSON

func (u SubscriptionEditTiming) MarshalJSON() ([]byte, error)

func (*SubscriptionEditTiming) UnmarshalJSON

func (u *SubscriptionEditTiming) UnmarshalJSON(data []byte) error

type SubscriptionEditTimingEnum

type SubscriptionEditTimingEnum string

Subscription edit timing. When immediate, the requested changes take effect immediately. When next_billing_cycle, the requested changes take effect at the next billing cycle.

const (
	SubscriptionEditTimingEnumImmediate        SubscriptionEditTimingEnum = "immediate"
	SubscriptionEditTimingEnumNextBillingCycle SubscriptionEditTimingEnum = "next_billing_cycle"
)

func (SubscriptionEditTimingEnum) Valid

func (value SubscriptionEditTimingEnum) Valid() bool

type SubscriptionPagePaginatedResponse

type SubscriptionPagePaginatedResponse struct {
	Data []BillingSubscription `json:"data"`
	Meta PaginatedMeta         `json:"meta"`
}

Page paginated response.

type SubscriptionReference

type SubscriptionReference struct {
	// The ID of the subscription.
	ID string `json:"id"`
	// The phase of the subscription.
	Phase SubscriptionReferencePhase `json:"phase"`
}

Subscription reference represents a reference to the specific subscription item this entity represents.

type SubscriptionReferencePhase

type SubscriptionReferencePhase struct {
	// The ID of the phase.
	ID string `json:"id"`
	// The item of the phase.
	Item SubscriptionReferencePhaseItem `json:"item"`
}

type SubscriptionReferencePhaseItem

type SubscriptionReferencePhaseItem struct {
	// The ID of the item.
	ID string `json:"id"`
}

type SubscriptionStatus

type SubscriptionStatus string

Subscription status.

const (
	SubscriptionStatusActive    SubscriptionStatus = "active"
	SubscriptionStatusInactive  SubscriptionStatus = "inactive"
	SubscriptionStatusCanceled  SubscriptionStatus = "canceled"
	SubscriptionStatusScheduled SubscriptionStatus = "scheduled"
)

func (SubscriptionStatus) Valid

func (value SubscriptionStatus) Valid() bool

type SubscriptionsService

type SubscriptionsService struct {
	// contains filtered or unexported fields
}

func (*SubscriptionsService) Cancel

func (s *SubscriptionsService) Cancel(ctx context.Context, subscriptionID string, request SubscriptionCancel) (*BillingSubscription, error)

Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancelation time.

func (*SubscriptionsService) Change

Closes a running subscription and starts a new one according to the specification. Can be used for upgrades, downgrades, and plan changes.

func (*SubscriptionsService) Create

func (*SubscriptionsService) CreateAddon

func (s *SubscriptionsService) CreateAddon(ctx context.Context, subscriptionID string, request CreateSubscriptionAddonRequest) (*SubscriptionAddon, error)

Add add-on to a subscription.

func (*SubscriptionsService) Get

func (s *SubscriptionsService) Get(ctx context.Context, subscriptionID string) (*BillingSubscription, error)

func (*SubscriptionsService) GetAddon

func (s *SubscriptionsService) GetAddon(ctx context.Context, subscriptionID string, subscriptionAddonID string) (*SubscriptionAddon, error)

Get an add-on association for a subscription.

func (*SubscriptionsService) ListAddons

List the add-ons of a subscription.

func (*SubscriptionsService) ListAddonsAll

func (s *SubscriptionsService) ListAddonsAll(ctx context.Context, subscriptionID string, params SubscriptionAddonListParams) iter.Seq2[SubscriptionAddon, error]

ListAddonsAll returns an iterator over all SubscriptionAddon results, fetching pages of ListAddons transparently. Iteration stops at the first error, which is yielded as the second value.

func (*SubscriptionsService) ListAll

ListAll returns an iterator over all BillingSubscription results, fetching pages of List transparently. Iteration stops at the first error, which is yielded as the second value.

func (*SubscriptionsService) UnscheduleCancelation

func (s *SubscriptionsService) UnscheduleCancelation(ctx context.Context, subscriptionID string) (*BillingSubscription, error)

Unschedules the subscription cancelation.

type Supplier

type Supplier struct {
	// Legal name or representation of the party.
	Name *string `json:"name,omitempty"`
	// The entity's legal identification used for tax purposes. They may have other
	// numbers, but we're only interested in those valid for tax purposes.
	TaxID *PartyTaxIdentity `json:"tax_id,omitempty"`
	// Address for where information should be sent if needed.
	Addresses *PartyAddresses `json:"addresses,omitempty"`
	// Unique identifier for the party.
	ID *string `json:"id,omitempty"`
}

Snapshot of the supplier's information at the time the invoice was issued.

Structurally a read-only subset of `BillingParty` (the type configured on the billing profile), so the snapshot stays aligned with the source. `key` is omitted because it is not part of the snapshotted supplier data.

type TaxBehavior

type TaxBehavior string

Tax behavior.

This enum is used to specify whether tax is included in the price or excluded from the price.

const (
	TaxBehaviorInclusive TaxBehavior = "inclusive"
	TaxBehaviorExclusive TaxBehavior = "exclusive"
)

func (TaxBehavior) Valid

func (value TaxBehavior) Valid() bool

type TaxCode

type TaxCode struct {
	ID string `json:"id"`
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string           `json:"description,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	// An ISO-8601 timestamp representation of entity creation date.
	CreatedAt time.Time `json:"created_at"`
	// An ISO-8601 timestamp representation of entity last update date.
	UpdatedAt time.Time `json:"updated_at"`
	// An ISO-8601 timestamp representation of entity deletion date.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	Key       string     `json:"key"`
	// Mapping of app types to tax codes.
	AppMappings []TaxCodeAppMapping `json:"app_mappings"`
}

Tax codes by provider.

type TaxCodeAppMapping

type TaxCodeAppMapping struct {
	// The app type that the tax code is associated with.
	AppType AppType `json:"app_type"`
	// Tax code.
	TaxCode string `json:"tax_code"`
}

Mapping of app types to tax codes.

type TaxCodeListParams

type TaxCodeListParams struct {
	Page           *PageParams
	IncludeDeleted *bool
}

type TaxCodePagePaginatedResponse

type TaxCodePagePaginatedResponse struct {
	Data []TaxCode     `json:"data"`
	Meta PaginatedMeta `json:"meta"`
}

Page paginated response.

type TaxCodeReference

type TaxCodeReference struct {
	ID string `json:"id"`
}

TaxCode reference.

type TaxConfig

type TaxConfig struct {
	// Tax behavior.
	//
	// If not specified the billing profile is used to determine the tax behavior. If
	// not specified in the billing profile, the provider's default behavior is used.
	Behavior *TaxBehavior `json:"behavior,omitempty"`
	// Stripe tax config.
	Stripe *TaxConfigStripe `json:"stripe,omitempty"`
	// External invoicing tax config.
	ExternalInvoicing *TaxConfigExternalInvoicing `json:"external_invoicing,omitempty"`
	// Tax code ID.
	TaxCodeID *string `json:"tax_code_id,omitempty"`
	// Tax code reference.
	//
	// When both `tax_code` and `tax_code_id` are provided, `tax_code` takes
	// precedence. When `stripe.code` is also provided, `tax_code` still wins and
	// `stripe.code` is ignored.
	TaxCode *TaxCodeReference `json:"tax_code,omitempty"`
}

Set of provider specific tax configs.

type TaxConfigExternalInvoicing

type TaxConfigExternalInvoicing struct {
	// The tax code should be interpreted by the external invoicing provider.
	Code string `json:"code"`
}

External invoicing tax config.

type TaxConfigStripe

type TaxConfigStripe struct {
	// Product [tax code](https://docs.stripe.com/tax/tax-codes).
	Code string `json:"code"`
}

The tax config for Stripe.

type TaxService

type TaxService struct {
	// contains filtered or unexported fields
}

func (*TaxService) CreateCode

func (s *TaxService) CreateCode(ctx context.Context, request CreateTaxCodeRequest) (*TaxCode, error)

func (*TaxService) DeleteCode

func (s *TaxService) DeleteCode(ctx context.Context, taxCodeID string) error

func (*TaxService) GetCode

func (s *TaxService) GetCode(ctx context.Context, taxCodeID string) (*TaxCode, error)

func (*TaxService) ListCodes

func (*TaxService) ListCodesAll

func (s *TaxService) ListCodesAll(ctx context.Context, params TaxCodeListParams) iter.Seq2[TaxCode, error]

ListCodesAll returns an iterator over all TaxCode results, fetching pages of ListCodes transparently. Iteration stops at the first error, which is yielded as the second value.

func (*TaxService) UpsertCode

func (s *TaxService) UpsertCode(ctx context.Context, taxCodeID string, request UpsertTaxCodeRequest) (*TaxCode, error)

type Totals

type Totals struct {
	// The total value of the resource before taxes, discounts and commitments.
	Amount Numeric `json:"amount"`
	// The total tax amount applied to the resource.
	TaxesTotal Numeric `json:"taxes_total"`
	// The total tax amount already included in the resource amount.
	TaxesInclusiveTotal Numeric `json:"taxes_inclusive_total"`
	// The total tax amount added on top of the resource amount.
	TaxesExclusiveTotal Numeric `json:"taxes_exclusive_total"`
	// The total amount contributed by additional charges.
	ChargesTotal Numeric `json:"charges_total"`
	// The total amount deducted through discounts.
	DiscountsTotal Numeric `json:"discounts_total"`
	// The total amount deducted through credits before taxes are applied.
	CreditsTotal Numeric `json:"credits_total"`
	// The final total value of the resource after taxes, discounts and commitments.
	Total Numeric `json:"total"`
}

Totals contains the summaries of all calculations for a billing resource.

type UnitConfig

type UnitConfig struct {
	// The arithmetic operation to apply to the raw metered quantity.
	Operation UnitConfigOperation `json:"operation"`
	// The factor used in the conversion operation.
	//
	// - For `divide`: `converted = raw / conversionFactor`.
	// - For `multiply`: `converted = raw × conversionFactor`.
	//
	// Must be a positive non-zero value.
	ConversionFactor Numeric `json:"conversion_factor"`
	// The rounding mode applied to the converted quantity for invoicing.
	//
	// Defaults to none (no rounding). Entitlement checks always use the precise
	// (unrounded) value.
	Rounding *UnitConfigRoundingMode `json:"rounding,omitempty"`
	// The number of decimal places to retain after rounding.
	//
	// Only meaningful when rounding is not "none". Defaults to 0 (round to whole
	// numbers).
	Precision *int64 `json:"precision,omitempty"`
	// A human-readable label for the converted unit shown on invoices and in the
	// customer portal (e.g., "GB", "hours", "M tokens").
	//
	// Optional. When omitted, no unit label is rendered.
	DisplayUnit *string `json:"display_unit,omitempty"`
}

Unit conversion configuration.

Transforms raw metered quantities into billing-ready units before pricing and entitlement evaluation. Applied at the rate card level so the same feature can be billed in different units across plans.

Examples:

- Meter bytes, bill GB: operation=divide, conversionFactor=1e9, rounding=ceiling, displayUnit="GB" - Meter seconds, bill hours: operation=divide, conversionFactor=3600, rounding=ceiling, displayUnit="hours" - Cost + 20% margin: operation=multiply, conversionFactor=1.2 - Bill per million tokens: operation=divide, conversionFactor=1e6, rounding=ceiling, displayUnit="M"

v1 equivalents:

- DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + UnitPrice(amount=1) - PackagePrice(amount, quantityPerPkg): operation=divide, conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount)

type UnitConfigOperation

type UnitConfigOperation string

The arithmetic operation used to convert raw metered units into billing units.

- `divide`: Divide the metered quantity by the conversion factor (e.g., bytes ÷ 1e9 = GB). - `multiply`: Multiply the metered quantity by the conversion factor (e.g., cost × 1.2 = cost + 20% margin).

const (
	UnitConfigOperationDivide   UnitConfigOperation = "divide"
	UnitConfigOperationMultiply UnitConfigOperation = "multiply"
)

func (UnitConfigOperation) Valid

func (value UnitConfigOperation) Valid() bool

type UnitConfigRoundingMode

type UnitConfigRoundingMode string

The rounding mode applied to the converted quantity for invoicing.

Rounding is applied only to the invoiced quantity. Entitlement balance checks use the precise decimal value after conversion.

- `ceiling`: Round up to the next integer (typical for package-style billing). - `floor`: Round down to the previous integer. - `half_up`: Round to the nearest integer, with 0.5 rounding up. - `none`: No rounding; the converted value is used as-is.

const (
	UnitConfigRoundingModeCeiling UnitConfigRoundingMode = "ceiling"
	UnitConfigRoundingModeFloor   UnitConfigRoundingMode = "floor"
	UnitConfigRoundingModeHalfUp  UnitConfigRoundingMode = "half_up"
	UnitConfigRoundingModeNone    UnitConfigRoundingMode = "none"
)

func (UnitConfigRoundingMode) Valid

func (value UnitConfigRoundingMode) Valid() bool

type UpdateBillingInvoiceWorkflow

type UpdateBillingInvoiceWorkflow struct {
	// Invoicing settings for this invoice.
	Invoicing *UpdateBillingInvoiceWorkflowInvoicingSettings `json:"invoicing,omitempty"`
	// Payment settings for this invoice.
	Payment *WorkflowPaymentSettings `json:"payment,omitempty"`
}

Invoice-level snapshot of the workflow configuration.

Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.

type UpdateBillingInvoiceWorkflowInvoicingSettings

type UpdateBillingInvoiceWorkflowInvoicingSettings struct {
	// Whether to automatically issue the invoice after the draft_period has passed.
	AutoAdvance *bool `json:"auto_advance,omitempty"`
	// The period for the invoice to be kept in draft status for manual reviews.
	DraftPeriod *string `json:"draft_period,omitempty"`
}

Invoice-level invoicing settings.

A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.

type UpdateCreditGrantExternalSettlementRequest

type UpdateCreditGrantExternalSettlementRequest struct {
	// The new payment settlement status.
	Status CreditPurchasePaymentSettlementStatus `json:"status"`
}

Request body for updating the external payment settlement status of a credit grant.

type UpdateFeatureRequest

type UpdateFeatureRequest struct {
	// Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or
	// "llm" to look up cost from the LLM cost database based on meter group-by
	// properties. Set to `null` to clear the existing unit cost; omit to leave it
	// unchanged.
	UnitCost Nullable[FeatureUnitCost] `json:"unit_cost,omitempty"`
}

Request body for updating a feature. Currently only the unit_cost field can be updated.

type UpdateInvoiceLine

type UpdateInvoiceLine struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

A top-level line item on an invoice.

Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.

UpdateInvoiceLine is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the UpdateInvoiceLineFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func UpdateInvoiceLineFromUpdateInvoiceStandardLine

func UpdateInvoiceLineFromUpdateInvoiceStandardLine(value UpdateInvoiceStandardLine) (UpdateInvoiceLine, error)

func (UpdateInvoiceLine) AsUpdateInvoiceStandardLine

func (u UpdateInvoiceLine) AsUpdateInvoiceStandardLine() (*UpdateInvoiceStandardLine, error)

func (UpdateInvoiceLine) MarshalJSON

func (u UpdateInvoiceLine) MarshalJSON() ([]byte, error)

func (*UpdateInvoiceLine) UnmarshalJSON

func (u *UpdateInvoiceLine) UnmarshalJSON(data []byte) error

type UpdateInvoiceRequest

type UpdateInvoiceRequest struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

UpdateInvoiceRequest update request.

UpdateInvoiceRequest is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the UpdateInvoiceRequestFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func UpdateInvoiceRequestFromUpdateInvoiceStandardRequest

func UpdateInvoiceRequestFromUpdateInvoiceStandardRequest(value UpdateInvoiceStandardRequest) (UpdateInvoiceRequest, error)

func (UpdateInvoiceRequest) AsUpdateInvoiceStandardRequest

func (u UpdateInvoiceRequest) AsUpdateInvoiceStandardRequest() (*UpdateInvoiceStandardRequest, error)

func (UpdateInvoiceRequest) MarshalJSON

func (u UpdateInvoiceRequest) MarshalJSON() ([]byte, error)

func (*UpdateInvoiceRequest) UnmarshalJSON

func (u *UpdateInvoiceRequest) UnmarshalJSON(data []byte) error

type UpdateInvoiceStandardLine

type UpdateInvoiceStandardLine struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// ID of the line.
	//
	// Optional on update: omit to create a new line, or supply the ID of an existing
	// line to edit it. Existing lines omitted from an update's `lines` array are
	// deleted.
	ID *string `json:"id,omitempty"`
	// The type of charge this line item represents.
	Type InvoiceLineType `json:"type"`
	// The service period covered by this invoice, spanning the earliest line start to
	// the latest line end across all of its lines.
	//
	// For an invoice with no lines the period is empty, which means `from` will be
	// equal to `to`.
	ServicePeriod ClosedPeriod `json:"service_period"`
	// The rate card configuration snapshot used to price this line item.
	RateCard InvoiceLineRateCard `json:"rate_card"`
}

A top-level line item on an invoice.

Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.

type UpdateInvoiceStandardRequest

type UpdateInvoiceStandardRequest struct {
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Snapshot of the supplier's contact information at the time the invoice was
	// issued.
	Supplier Supplier `json:"supplier"`
	// Snapshot of the customer's information at the time the invoice was issued.
	Customer InvoiceCustomer `json:"customer"`
	// Discriminator field identifying this as a standard invoice.
	Type InvoiceType `json:"type"`
	// Workflow configuration snapshot captured at invoice creation time.
	Workflow UpdateInvoiceWorkflowSettings `json:"workflow"`
	// Line items on this invoice.
	//
	// Always returned on single-resource GET; omitted on list endpoints unless
	// explicitly expanded. Editable via update: existing lines are matched by `id`,
	// lines without an `id` are created, and lines present on the invoice but omitted
	// from the update request are deleted. Detailed (child) lines are always computed
	// and cannot be edited directly.
	Lines *[]UpdateInvoiceLine `json:"lines,omitempty"`
}

InvoiceStandard update request.

type UpdateInvoiceWorkflowSettings

type UpdateInvoiceWorkflowSettings struct {
	// The workflow configuration that was active when the invoice was created.
	//
	// Only the fields that are meaningful at the per-invoice level are included:
	// invoicing behaviour (auto-advance, draft period) and payment settings
	// (collection method, due date). Profile-wide settings such as collection
	// alignment, progressive billing, and tax policy are omitted.
	Workflow UpdateBillingInvoiceWorkflow `json:"workflow"`
}

Snapshot of the billing workflow configuration captured at invoice creation.

type UpdateMeterRequest

type UpdateMeterRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name *string `json:"name,omitempty"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Named JSONPath expressions to extract the group by values from the event data.
	//
	// Keys must be unique and consist only alphanumeric and underscore characters.
	Dimensions *map[string]string `json:"dimensions,omitempty"`
}

Meter update request.

type UpdateOrganizationDefaultTaxCodesRequest

type UpdateOrganizationDefaultTaxCodesRequest struct {
	// Default tax code for invoicing.
	InvoicingTaxCode *TaxCodeReference `json:"invoicing_tax_code,omitempty"`
	// Default tax code for credit grants.
	CreditGrantTaxCode *TaxCodeReference `json:"credit_grant_tax_code,omitempty"`
}

OrganizationDefaultTaxCodes update request.

type UpsertAddonRequest

type UpsertAddonRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The InstanceType of the add-ons. Can be "single" or "multiple".
	InstanceType AddonInstanceType `json:"instance_type"`
	// The rate cards of the add-on.
	RateCards []RateCardInput `json:"rate_cards"`
}

Addon upsert request.

type UpsertAppCustomerDataRequest

type UpsertAppCustomerDataRequest struct {
	// Used if the customer has a linked Stripe app.
	Stripe *AppCustomerDataStripeInput `json:"stripe,omitempty"`
	// Used if the customer has a linked external invoicing app.
	ExternalInvoicing *AppCustomerDataExternalInvoicingInput `json:"external_invoicing,omitempty"`
}

AppCustomerData upsert request.

type UpsertBillingProfileRequest

type UpsertBillingProfileRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The name and contact information for the supplier this billing profile
	// represents
	Supplier Party `json:"supplier"`
	// The billing workflow settings for this profile
	Workflow Workflow `json:"workflow"`
	// Whether this is the default profile.
	Default bool `json:"default"`
}

BillingProfile upsert request.

type UpsertCustomerBillingDataRequest

type UpsertCustomerBillingDataRequest struct {
	// The billing profile for the customer.
	//
	// If not provided, the default billing profile will be used.
	BillingProfile *ProfileReference `json:"billing_profile,omitempty"`
	// App customer data.
	AppData *AppCustomerDataInput `json:"app_data,omitempty"`
}

CustomerBillingData upsert request.

type UpsertCustomerRequest

type UpsertCustomerRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Mapping to attribute metered usage to the customer by the event subject.
	UsageAttribution *CustomerUsageAttribution `json:"usage_attribution,omitempty"`
	// The primary email address of the customer.
	PrimaryEmail *string `json:"primary_email,omitempty"`
	// Currency of the customer. Used for billing, tax and invoicing.
	Currency *string `json:"currency,omitempty"`
	// The billing address of the customer. Used for tax and invoicing.
	BillingAddress *Address `json:"billing_address,omitempty"`
}

Customer upsert request.

type UpsertPlanAddonRequest

type UpsertPlanAddonRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// The key of the plan phase from which the add-on becomes available for purchase.
	FromPlanPhase string `json:"from_plan_phase"`
	// The maximum number of times the add-on can be purchased for the plan. For
	// single-instance add-ons this field must be omitted. For multi-instance add-ons
	// when omitted, unlimited quantity can be purchased.
	MaxQuantity *int64 `json:"max_quantity,omitempty"`
}

PlanAddon upsert request.

type UpsertPlanRequest

type UpsertPlanRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Whether pro-rating is enabled for this plan.
	ProRatingEnabled *bool `json:"pro_rating_enabled,omitempty"`
	// The plan phases define the pricing ramp for a subscription. A phase switch
	// occurs only at the end of a billing period. At least one phase is required.
	Phases []PlanPhaseInput `json:"phases"`
}

Plan upsert request.

type UpsertTaxCodeRequest

type UpsertTaxCodeRequest struct {
	// Display name of the resource.
	//
	// Between 1 and 256 characters.
	Name string `json:"name"`
	// Optional description of the resource.
	//
	// Maximum 1024 characters.
	Description *string            `json:"description,omitempty"`
	Labels      *map[string]string `json:"labels,omitempty"`
	// Mapping of app types to tax codes.
	AppMappings []TaxCodeAppMapping `json:"app_mappings"`
}

TaxCode upsert request.

type Workflow

type Workflow struct {
	// The collection settings for this workflow
	Collection *WorkflowCollectionSettings `json:"collection,omitempty"`
	// The invoicing settings for this workflow
	Invoicing *WorkflowInvoicingSettings `json:"invoicing,omitempty"`
	// The payment settings for this workflow
	Payment *WorkflowPaymentSettings `json:"payment,omitempty"`
	// The tax settings for this workflow
	Tax *WorkflowTaxSettings `json:"tax,omitempty"`
}

Billing workflow settings.

type WorkflowCollectionAlignment

type WorkflowCollectionAlignment struct {
	Type string `json:"type"`
	// contains filtered or unexported fields
}

The alignment for collecting the pending line items into an invoice.

Defaults to subscription, which means that we are to create a new invoice every time the a subscription period starts (for in advance items) or ends (for in arrears items).

WorkflowCollectionAlignment is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the WorkflowCollectionAlignmentFrom* constructors. The exported Type field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func WorkflowCollectionAlignmentFromWorkflowCollectionAlignmentAnchored

func WorkflowCollectionAlignmentFromWorkflowCollectionAlignmentAnchored(value WorkflowCollectionAlignmentAnchored) (WorkflowCollectionAlignment, error)

func WorkflowCollectionAlignmentFromWorkflowCollectionAlignmentSubscription

func WorkflowCollectionAlignmentFromWorkflowCollectionAlignmentSubscription(value WorkflowCollectionAlignmentSubscription) (WorkflowCollectionAlignment, error)

func (WorkflowCollectionAlignment) AsWorkflowCollectionAlignmentAnchored

func (u WorkflowCollectionAlignment) AsWorkflowCollectionAlignmentAnchored() (*WorkflowCollectionAlignmentAnchored, error)

func (WorkflowCollectionAlignment) AsWorkflowCollectionAlignmentSubscription

func (u WorkflowCollectionAlignment) AsWorkflowCollectionAlignmentSubscription() (*WorkflowCollectionAlignmentSubscription, error)

func (WorkflowCollectionAlignment) MarshalJSON

func (u WorkflowCollectionAlignment) MarshalJSON() ([]byte, error)

func (*WorkflowCollectionAlignment) UnmarshalJSON

func (u *WorkflowCollectionAlignment) UnmarshalJSON(data []byte) error

type WorkflowCollectionAlignmentAnchored

type WorkflowCollectionAlignmentAnchored struct {
	// The type of alignment.
	Type CollectionAlignment `json:"type"`
	// The recurring period for the alignment.
	RecurringPeriod RecurringPeriod `json:"recurring_period"`
}

BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items into an invoice.

type WorkflowCollectionAlignmentSubscription

type WorkflowCollectionAlignmentSubscription struct {
	// The type of alignment.
	Type CollectionAlignment `json:"type"`
}

BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items into an invoice.

type WorkflowCollectionSettings

type WorkflowCollectionSettings struct {
	// The alignment for collecting the pending line items into an invoice.
	Alignment *WorkflowCollectionAlignment `json:"alignment,omitempty"`
	// This grace period can be used to delay the collection of the pending line items
	// specified in alignment.
	//
	// This is useful, in case of multiple subscriptions having slightly different
	// billing periods.
	Interval *string `json:"interval,omitempty"`
}

Workflow collection specifies how to collect the pending line items for an invoice.

type WorkflowInvoicingSettings

type WorkflowInvoicingSettings struct {
	// Whether to automatically issue the invoice after the draftPeriod has passed.
	AutoAdvance *bool `json:"auto_advance,omitempty"`
	// The period for the invoice to be kept in draft status for manual reviews.
	DraftPeriod *string `json:"draft_period,omitempty"`
	// Should progressive billing be allowed for this workflow?
	ProgressiveBilling *bool `json:"progressive_billing,omitempty"`
	// Controls how subscription-ending shortened service periods are billed.
	SubscriptionEndProrationMode *WorkflowInvoicingSubscriptionEndProrationMode `json:"subscription_end_proration_mode,omitempty"`
}

Invoice settings for a billing workflow.

type WorkflowInvoicingSubscriptionEndProrationMode

type WorkflowInvoicingSubscriptionEndProrationMode string

Billing workflow subscription end proration mode.

const (
	WorkflowInvoicingSubscriptionEndProrationModeBillFullPeriod   WorkflowInvoicingSubscriptionEndProrationMode = "bill_full_period"
	WorkflowInvoicingSubscriptionEndProrationModeBillActualPeriod WorkflowInvoicingSubscriptionEndProrationMode = "bill_actual_period"
)

func (WorkflowInvoicingSubscriptionEndProrationMode) Valid

type WorkflowPaymentChargeAutomaticallySettings

type WorkflowPaymentChargeAutomaticallySettings struct {
	// The collection method for the invoice.
	CollectionMethod CollectionMethod `json:"collection_method"`
}

Payment settings for a billing workflow when the collection method is charge automatically.

type WorkflowPaymentSendInvoiceSettings

type WorkflowPaymentSendInvoiceSettings struct {
	// The collection method for the invoice.
	CollectionMethod CollectionMethod `json:"collection_method"`
	// The period after which the invoice is due. With some payment solutions it's only
	// applicable for manual collection method.
	DueAfter *string `json:"due_after,omitempty"`
}

Payment settings for a billing workflow when the collection method is send invoice.

type WorkflowPaymentSettings

type WorkflowPaymentSettings struct {
	CollectionMethod string `json:"collection_method"`
	// contains filtered or unexported fields
}

Payment settings for a billing workflow.

WorkflowPaymentSettings is a JSON-preserving tagged union: its zero value marshals as JSON null, and values must be built with the WorkflowPaymentSettingsFrom* constructors. The exported CollectionMethod field is decode-side metadata; MarshalJSON round-trips the original payload and ignores writes to it.

func WorkflowPaymentSettingsFromWorkflowPaymentChargeAutomaticallySettings

func WorkflowPaymentSettingsFromWorkflowPaymentChargeAutomaticallySettings(value WorkflowPaymentChargeAutomaticallySettings) (WorkflowPaymentSettings, error)

func WorkflowPaymentSettingsFromWorkflowPaymentSendInvoiceSettings

func WorkflowPaymentSettingsFromWorkflowPaymentSendInvoiceSettings(value WorkflowPaymentSendInvoiceSettings) (WorkflowPaymentSettings, error)

func (WorkflowPaymentSettings) AsWorkflowPaymentChargeAutomaticallySettings

func (u WorkflowPaymentSettings) AsWorkflowPaymentChargeAutomaticallySettings() (*WorkflowPaymentChargeAutomaticallySettings, error)

func (WorkflowPaymentSettings) AsWorkflowPaymentSendInvoiceSettings

func (u WorkflowPaymentSettings) AsWorkflowPaymentSendInvoiceSettings() (*WorkflowPaymentSendInvoiceSettings, error)

func (WorkflowPaymentSettings) MarshalJSON

func (u WorkflowPaymentSettings) MarshalJSON() ([]byte, error)

func (*WorkflowPaymentSettings) UnmarshalJSON

func (u *WorkflowPaymentSettings) UnmarshalJSON(data []byte) error

type WorkflowTaxSettings

type WorkflowTaxSettings struct {
	// Enable automatic tax calculation when tax is supported by the app. For example,
	// with Stripe Invoicing when enabled, tax is calculated via Stripe Tax.
	Enabled *bool `json:"enabled,omitempty"`
	// Enforce tax calculation when tax is supported by the app. When enabled, the
	// billing system will not allow to create an invoice without tax calculation.
	// Enforcement is different per apps, for example, Stripe app requires customer to
	// have a tax location when starting a paid subscription.
	Enforced *bool `json:"enforced,omitempty"`
	// Default tax configuration to apply to the invoices for line items.
	//
	// Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax
	// config is deprecated and can no longer be added or changed: the organization
	// default tax code is used instead. Existing tax-code values may still be removed,
	// and `behavior` remains fully supported.
	DefaultTaxConfig *TaxConfig `json:"default_tax_config,omitempty"`
}

Tax settings for a billing workflow.

Jump to

Keyboard shortcuts

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