commet

package module
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 16 Imported by: 0

README

Commet Go SDK

Billing and usage tracking for SaaS applications.

Installation

go get github.com/commet-labs/commet-go

Quick start

package main

import (
	"context"
	"log"

	commet "github.com/commet-labs/commet-go"
)

func main() {
	client, err := commet.New("ck_xxx",
		commet.WithEnvironment(commet.Production),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()

	// Create a customer
	client.Customers.Create(ctx, &commet.CreateCustomerParams{
		Email:      "user@example.com",
		ExternalID: "user_123",
	})

	// Create a subscription
	client.Subscriptions.Create(ctx, &commet.CreateSubscriptionParams{
		ExternalID: "user_123",
		PlanCode:   "pro",
	})

	// Track usage
	client.Usage.Track(ctx, &commet.TrackUsageParams{
		Feature:    "api_calls",
		ExternalID: "user_123",
	})

	// Track AI token usage
	inputTokens := 1000
	outputTokens := 500
	client.Usage.Track(ctx, &commet.TrackUsageParams{
		Feature:      "ai_generation",
		ExternalID:   "user_123",
		Model:        "claude-sonnet-4-20250514",
		InputTokens:  &inputTokens,
		OutputTokens: &outputTokens,
	})
}

Customer context

Scope all operations to a customer to avoid repeating ExternalID:

customer := client.Customer("user_123")

customer.Usage.Track(ctx, "api_calls")
customer.Features.Check(ctx, "custom_branding")
customer.Seats.Add(ctx, "editor", 3)
customer.Portal.GetURL(ctx)

Webhook verification

webhooks := &commet.Webhooks{}

payload, err := webhooks.VerifyAndParse(
	requestBody,
	request.Header.Get("x-commet-signature"),
	"whsec_xxx",
)
if err != nil {
	log.Fatal("Invalid webhook signature")
}

if payload["event"] == "subscription.activated" {
	// handle activation
}

Environments

The SDK defaults to Sandbox. Set Production for live operations:

client, err := commet.New("ck_xxx",
	commet.WithEnvironment(commet.Production),
)

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActiveSubscription added in v1.9.0

type ActiveSubscription struct {
	ID                string             `json:"id"`
	CustomerID        string             `json:"customer_id"`
	Plan              SubscriptionPlan   `json:"plan"`
	Name              string             `json:"name"`
	Description       string             `json:"description,omitempty"`
	Status            string             `json:"status"`
	ConsumptionModel  string             `json:"consumption_model"`
	TrialEndsAt       string             `json:"trial_ends_at,omitempty"`
	CurrentPeriod     SubscriptionPeriod `json:"current_period"`
	Features          []FeatureSummary   `json:"features"`
	Credits           *CreditsSummary    `json:"credits,omitempty"`
	Balance           *BalanceSummary    `json:"balance,omitempty"`
	StartDate         string             `json:"start_date"`
	EndDate           string             `json:"end_date,omitempty"`
	BillingDayOfMonth int                `json:"billing_day_of_month"`
	NextBillingDate   string             `json:"next_billing_date"`
	CheckoutURL       string             `json:"checkout_url,omitempty"`
	CreatedAt         string             `json:"created_at"`
	UpdatedAt         string             `json:"updated_at"`
}

type ApiResponse

type ApiResponse[T any] struct {
	Success    bool   `json:"success"`
	Data       T      `json:"data,omitempty"`
	Code       string `json:"code,omitempty"`
	Message    string `json:"message,omitempty"`
	HasMore    bool   `json:"has_more,omitempty"`
	NextCursor string `json:"next_cursor,omitempty"`
}

type BalanceSummary added in v1.10.0

type BalanceSummary struct {
	Remaining int    `json:"remaining"`
	Included  int    `json:"included"`
	Currency  string `json:"currency"`
}

type BatchFailure added in v1.9.0

type BatchFailure struct {
	Index int    `json:"index"`
	Error string `json:"error"`
	Data  any    `json:"data"`
}

type BatchResult added in v1.9.0

type BatchResult struct {
	Successful []Customer     `json:"successful"`
	Failed     []BatchFailure `json:"failed"`
}

type CanUseResult added in v1.9.0

type CanUseResult struct {
	Allowed       bool   `json:"allowed"`
	WillBeCharged bool   `json:"will_be_charged"`
	Reason        string `json:"reason,omitempty"`
}

type CancelSubscriptionParams

type CancelSubscriptionParams struct {
	Reason         string `json:"reason,omitempty"`
	Immediate      *bool  `json:"immediate,omitempty"`
	IdempotencyKey string `json:"-"`
}

type CheckResult added in v1.9.0

type CheckResult struct {
	Allowed bool `json:"allowed"`
}

type Client

type Client struct {
	Customers     Customers
	Plans         Plans
	Subscriptions Subscriptions
	Usage         Usage
	Seats         Seats
	Features      Features
	Portal        Portal
	CreditPacks   CreditPacks
	Webhooks      WebhookVerifier
	// contains filtered or unexported fields
}

Client is the Commet SDK client.

func New

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

New creates a new Commet client with the given API key and options.

func (*Client) Close

func (c *Client) Close()

Close releases resources held by the client.

func (*Client) Customer

func (c *Client) Customer(customerID string) *CustomerContext

Customer returns a customer-scoped context for cleaner API usage.

func (*Client) Environment

func (c *Client) Environment() Environment

Environment returns the configured environment.

func (*Client) IsProduction

func (c *Client) IsProduction() bool

IsProduction returns true if the client is configured for production.

func (*Client) IsSandbox

func (c *Client) IsSandbox() bool

IsSandbox returns true if the client is configured for sandbox.

type CommetError

type CommetError struct {
	Message    string
	Code       string
	StatusCode int
	Details    any
}

CommetError is the base error type for all SDK errors.

func (*CommetError) Error

func (e *CommetError) Error() string

type CreateCustomerParams

type CreateCustomerParams struct {
	Email          string            `json:"billing_email"`
	ID             string            `json:"-"`
	FullName       string            `json:"full_name,omitempty"`
	Domain         string            `json:"domain,omitempty"`
	Website        string            `json:"website,omitempty"`
	Timezone       string            `json:"timezone,omitempty"`
	Language       string            `json:"language,omitempty"`
	Industry       string            `json:"industry,omitempty"`
	Metadata       map[string]any    `json:"metadata,omitempty"`
	Address        map[string]string `json:"address,omitempty"`
	IdempotencyKey string            `json:"-"`
}

type CreateSubscriptionParams

type CreateSubscriptionParams struct {
	CustomerID      string         `json:"customer_id,omitempty"`
	PlanCode        string         `json:"plan_code,omitempty"`
	PlanID          string         `json:"plan_id,omitempty"`
	BillingInterval string         `json:"billing_interval,omitempty"`
	InitialSeats    map[string]int `json:"initial_seats,omitempty"`
	SkipTrial       *bool          `json:"skip_trial,omitempty"`
	Name            string         `json:"name,omitempty"`
	StartDate       string         `json:"start_date,omitempty"`
	SuccessURL      string         `json:"success_url,omitempty"`
	IdempotencyKey  string         `json:"-"`
}

type CreditPack added in v1.9.0

type CreditPack struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Credits     int    `json:"credits"`
	Price       int    `json:"price"`
	Currency    string `json:"currency"`
}

type CreditPacks added in v1.9.0

type CreditPacks interface {
	List(ctx context.Context) (*ApiResponse[[]CreditPack], error)
}

type CreditPacksResource

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

func (*CreditPacksResource) List

type CreditsSummary added in v1.10.0

type CreditsSummary struct {
	Remaining int `json:"remaining"`
	Included  int `json:"included"`
	Purchased int `json:"purchased"`
}

type Customer added in v1.9.0

type Customer struct {
	ID             string         `json:"id"`
	OrganizationID string         `json:"organization_id"`
	ExternalID     string         `json:"external_id,omitempty"`
	FullName       string         `json:"full_name,omitempty"`
	Domain         string         `json:"domain,omitempty"`
	Website        string         `json:"website,omitempty"`
	BillingEmail   string         `json:"billing_email"`
	Timezone       string         `json:"timezone,omitempty"`
	Language       string         `json:"language,omitempty"`
	Industry       string         `json:"industry,omitempty"`
	EmployeeCount  string         `json:"employee_count,omitempty"`
	Metadata       map[string]any `json:"metadata,omitempty"`
	IsActive       bool           `json:"is_active"`
	CreatedAt      string         `json:"created_at"`
	UpdatedAt      string         `json:"updated_at"`
}

type CustomerContext

type CustomerContext struct {
	Features     CustomerContextFeatures
	Seats        CustomerContextSeats
	Usage        CustomerContextUsage
	Subscription CustomerContextSubscription
	Portal       CustomerContextPortal
}

type CustomerContextFeatures added in v1.9.0

type CustomerContextFeatures interface {
	Get(ctx context.Context, code string) (*ApiResponse[FeatureAccess], error)
	Check(ctx context.Context, code string) (*ApiResponse[CheckResult], error)
	CanUse(ctx context.Context, code string) (*ApiResponse[CanUseResult], error)
	List(ctx context.Context) (*ApiResponse[[]FeatureAccess], error)
}

type CustomerContextPortal added in v1.9.0

type CustomerContextPortal interface {
	GetURL(ctx context.Context) (*ApiResponse[PortalSession], error)
}

type CustomerContextSeats added in v1.9.0

type CustomerContextSeats interface {
	Add(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)
	Remove(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)
	Set(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)
	GetBalance(ctx context.Context, seatType string) (*ApiResponse[SeatBalance], error)
}

type CustomerContextSubscription added in v1.9.0

type CustomerContextSubscription interface {
	Get(ctx context.Context) (*ApiResponse[ActiveSubscription], error)
}

type CustomerContextUsage added in v1.9.0

type CustomerContextUsage interface {
	Track(ctx context.Context, feature string, opts ...TrackOption) (*ApiResponse[UsageEvent], error)
}

type CustomerFeatures

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

func (*CustomerFeatures) CanUse

func (*CustomerFeatures) Check

func (*CustomerFeatures) Get

func (*CustomerFeatures) List

type CustomerPortal

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

func (*CustomerPortal) GetURL

type CustomerSeats

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

func (*CustomerSeats) Add

func (s *CustomerSeats) Add(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)

func (*CustomerSeats) GetBalance

func (s *CustomerSeats) GetBalance(ctx context.Context, seatType string) (*ApiResponse[SeatBalance], error)

func (*CustomerSeats) Remove

func (s *CustomerSeats) Remove(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)

func (*CustomerSeats) Set

func (s *CustomerSeats) Set(ctx context.Context, seatType string, count int) (*ApiResponse[SeatEvent], error)

type CustomerSubscription

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

func (*CustomerSubscription) Get

type CustomerUsage

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

func (*CustomerUsage) Track

func (u *CustomerUsage) Track(ctx context.Context, feature string, opts ...TrackOption) (*ApiResponse[UsageEvent], error)

type Customers added in v1.9.0

type Customers interface {
	Create(ctx context.Context, params *CreateCustomerParams) (*ApiResponse[Customer], error)
	CreateBatch(ctx context.Context, customers []CreateCustomerParams, idempotencyKey string) (*ApiResponse[BatchResult], error)
	Get(ctx context.Context, customerID string) (*ApiResponse[Customer], error)
	Update(ctx context.Context, customerID string, params *UpdateCustomerParams) (*ApiResponse[Customer], error)
	List(ctx context.Context, params *ListCustomersParams) (*ApiResponse[[]Customer], error)
	Archive(ctx context.Context, customerID string, idempotencyKey string) (*ApiResponse[Customer], error)
}

type CustomersResource

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

func (*CustomersResource) Archive

func (r *CustomersResource) Archive(ctx context.Context, customerID string, idempotencyKey string) (*ApiResponse[Customer], error)

func (*CustomersResource) Create

func (*CustomersResource) CreateBatch

func (r *CustomersResource) CreateBatch(ctx context.Context, customers []CreateCustomerParams, idempotencyKey string) (*ApiResponse[BatchResult], error)

func (*CustomersResource) Get

func (r *CustomersResource) Get(ctx context.Context, customerID string) (*ApiResponse[Customer], error)

func (*CustomersResource) List

func (*CustomersResource) Update

func (r *CustomersResource) Update(ctx context.Context, customerID string, params *UpdateCustomerParams) (*ApiResponse[Customer], error)

type Environment

type Environment string

Environment represents the target API environment.

const (
	Sandbox    Environment = "sandbox"
	Production Environment = "production"
)

type FeatureAccess added in v1.9.0

type FeatureAccess struct {
	Code             string   `json:"code"`
	Name             string   `json:"name"`
	Type             string   `json:"type"`
	Allowed          bool     `json:"allowed"`
	Enabled          *bool    `json:"enabled,omitempty"`
	Current          *int     `json:"current,omitempty"`
	Included         *int     `json:"included,omitempty"`
	Remaining        *int     `json:"remaining,omitempty"`
	Overage          *int     `json:"overage,omitempty"`
	OverageUnitPrice *float64 `json:"overage_unit_price,omitempty"`
	Unlimited        *bool    `json:"unlimited,omitempty"`
	OverageEnabled   *bool    `json:"overage_enabled,omitempty"`
}

type FeatureSummary added in v1.9.0

type FeatureSummary struct {
	Code    string        `json:"code"`
	Name    string        `json:"name"`
	Type    string        `json:"type"`
	Enabled *bool         `json:"enabled,omitempty"`
	Usage   *FeatureUsage `json:"usage,omitempty"`
}

type FeatureUsage added in v1.9.0

type FeatureUsage struct {
	Current          int      `json:"current"`
	Included         int      `json:"included"`
	Overage          int      `json:"overage"`
	OverageUnitPrice *float64 `json:"overage_unit_price,omitempty"`
}

type Features added in v1.9.0

type Features interface {
	Get(ctx context.Context, code string, customerID string) (*ApiResponse[FeatureAccess], error)
	Check(ctx context.Context, code string, customerID string) (*ApiResponse[CheckResult], error)
	CanUse(ctx context.Context, code string, customerID string) (*ApiResponse[CanUseResult], error)
	List(ctx context.Context, customerID string) (*ApiResponse[[]FeatureAccess], error)
}

type FeaturesResource

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

func (*FeaturesResource) CanUse

func (r *FeaturesResource) CanUse(ctx context.Context, code string, customerID string) (*ApiResponse[CanUseResult], error)

func (*FeaturesResource) Check

func (r *FeaturesResource) Check(ctx context.Context, code string, customerID string) (*ApiResponse[CheckResult], error)

func (*FeaturesResource) Get

func (r *FeaturesResource) Get(ctx context.Context, code string, customerID string) (*ApiResponse[FeatureAccess], error)

func (*FeaturesResource) List

func (r *FeaturesResource) List(ctx context.Context, customerID string) (*ApiResponse[[]FeatureAccess], error)

type GetAllSeatBalancesParams

type GetAllSeatBalancesParams struct {
	CustomerID string `json:"customer_id"`
}

type GetPortalURLParams

type GetPortalURLParams struct {
	CustomerID     string `json:"customer_id,omitempty"`
	Email          string `json:"email,omitempty"`
	IdempotencyKey string `json:"-"`
}

type GetSeatBalanceParams

type GetSeatBalanceParams struct {
	SeatType   string `json:"seat_type"`
	CustomerID string `json:"customer_id"`
}

type ListCustomersParams

type ListCustomersParams struct {
	CustomerID string `json:"customer_id,omitempty"`
	IsActive   *bool  `json:"is_active,omitempty"`
	Search     string `json:"search,omitempty"`
	Limit      *int   `json:"limit,omitempty"`
	Cursor     string `json:"cursor,omitempty"`
}

type ListPlansParams

type ListPlansParams struct {
	IncludePrivate *bool  `json:"include_private,omitempty"`
	Limit          *int   `json:"limit,omitempty"`
	Cursor         string `json:"cursor,omitempty"`
}

type Option

type Option func(*clientConfig)

Option configures the Commet client.

func WithEnvironment

func WithEnvironment(env Environment) Option

WithEnvironment sets the API environment. Defaults to Sandbox.

func WithRetries

func WithRetries(retries int) Option

WithRetries sets the maximum number of retries for failed requests. Defaults to 3.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the HTTP request timeout. Defaults to 30 seconds.

type OverageConfig added in v1.9.0

type OverageConfig struct {
	Enabled   bool     `json:"enabled"`
	Model     string   `json:"model,omitempty"`
	UnitPrice *float64 `json:"unit_price,omitempty"`
}

type Plan added in v1.9.0

type Plan struct {
	ID          string        `json:"id"`
	Code        string        `json:"code"`
	Name        string        `json:"name"`
	Description string        `json:"description,omitempty"`
	IsPublic    bool          `json:"is_public"`
	IsFree      bool          `json:"is_free"`
	IsDefault   bool          `json:"is_default"`
	SortOrder   int           `json:"sort_order"`
	Prices      []PlanPrice   `json:"prices"`
	Features    []PlanFeature `json:"features"`
	CreatedAt   string        `json:"created_at"`
}

type PlanDetail added in v1.9.0

type PlanDetail struct {
	ID          string              `json:"id"`
	Code        string              `json:"code"`
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	IsPublic    bool                `json:"is_public"`
	IsDefault   bool                `json:"is_default"`
	SortOrder   int                 `json:"sort_order"`
	Prices      []PlanDetailPrice   `json:"prices"`
	Features    []PlanDetailFeature `json:"features"`
	CreatedAt   string              `json:"created_at"`
	UpdatedAt   string              `json:"updated_at"`
}

type PlanDetailFeature added in v1.9.0

type PlanDetailFeature struct {
	Code             string         `json:"code"`
	Name             string         `json:"name"`
	Type             string         `json:"type"`
	UnitName         string         `json:"unit_name,omitempty"`
	Enabled          *bool          `json:"enabled,omitempty"`
	IncludedAmount   *int           `json:"included_amount,omitempty"`
	Unlimited        *bool          `json:"unlimited,omitempty"`
	OverageEnabled   *bool          `json:"overage_enabled,omitempty"`
	OverageUnitPrice *float64       `json:"overage_unit_price,omitempty"`
	Overage          *OverageConfig `json:"overage,omitempty"`
}

type PlanDetailPrice added in v1.9.0

type PlanDetailPrice struct {
	BillingInterval string          `json:"billing_interval"`
	Price           int             `json:"price"`
	IsDefault       bool            `json:"is_default"`
	TrialDays       int             `json:"trial_days"`
	IntroOffer      *PlanIntroOffer `json:"intro_offer,omitempty"`
}

type PlanFeature added in v1.9.0

type PlanFeature struct {
	Code             string   `json:"code"`
	Name             string   `json:"name"`
	Type             string   `json:"type"`
	UnitName         string   `json:"unit_name,omitempty"`
	Enabled          *bool    `json:"enabled,omitempty"`
	IncludedAmount   *int     `json:"included_amount,omitempty"`
	Unlimited        *bool    `json:"unlimited,omitempty"`
	OverageEnabled   *bool    `json:"overage_enabled,omitempty"`
	OverageUnitPrice *float64 `json:"overage_unit_price,omitempty"`
}

type PlanIntroOffer added in v1.9.0

type PlanIntroOffer struct {
	Enabled        bool     `json:"enabled"`
	DiscountType   string   `json:"discount_type,omitempty"`
	DiscountValue  *float64 `json:"discount_value,omitempty"`
	DurationCycles *int     `json:"duration_cycles,omitempty"`
}

type PlanPrice added in v1.9.0

type PlanPrice struct {
	BillingInterval string `json:"billing_interval"`
	Price           int    `json:"price"`
	IsDefault       bool   `json:"is_default"`
	TrialDays       int    `json:"trial_days"`
}

type Plans added in v1.9.0

type Plans interface {
	List(ctx context.Context, params *ListPlansParams) (*ApiResponse[[]Plan], error)
	Get(ctx context.Context, planCode string) (*ApiResponse[PlanDetail], error)
}

type PlansResource

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

func (*PlansResource) Get

func (r *PlansResource) Get(ctx context.Context, planCode string) (*ApiResponse[PlanDetail], error)

func (*PlansResource) List

func (r *PlansResource) List(ctx context.Context, params *ListPlansParams) (*ApiResponse[[]Plan], error)

type Portal added in v1.9.0

type Portal interface {
	GetURL(ctx context.Context, params *GetPortalURLParams) (*ApiResponse[PortalSession], error)
}

type PortalResource

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

func (*PortalResource) GetURL

type PortalSession added in v1.9.0

type PortalSession struct {
	Success   bool   `json:"success"`
	Message   string `json:"message"`
	PortalURL string `json:"portal_url"`
}

type SeatBalance added in v1.9.0

type SeatBalance struct {
	Current int    `json:"current"`
	AsOf    string `json:"as_of"`
}

type SeatEvent added in v1.9.0

type SeatEvent struct {
	ID              string `json:"id"`
	OrganizationID  string `json:"organization_id"`
	CustomerID      string `json:"customer_id"`
	SeatType        string `json:"seat_type"`
	EventType       string `json:"event_type"`
	Quantity        int    `json:"quantity"`
	PreviousBalance *int   `json:"previous_balance,omitempty"`
	NewBalance      int    `json:"new_balance"`
	Ts              string `json:"ts"`
	CreatedAt       string `json:"created_at"`
}

type SeatParams

type SeatParams struct {
	SeatType       string `json:"seat_type"`
	Count          int    `json:"count"`
	CustomerID     string `json:"customer_id"`
	IdempotencyKey string `json:"-"`
}

type Seats added in v1.9.0

type Seats interface {
	Add(ctx context.Context, params *SeatParams) (*ApiResponse[SeatEvent], error)
	Remove(ctx context.Context, params *SeatParams) (*ApiResponse[SeatEvent], error)
	Set(ctx context.Context, params *SeatParams) (*ApiResponse[SeatEvent], error)
	SetAll(ctx context.Context, params *SetAllSeatsParams) (*ApiResponse[[]SeatEvent], error)
	GetBalance(ctx context.Context, params *GetSeatBalanceParams) (*ApiResponse[SeatBalance], error)
	GetAllBalances(ctx context.Context, params *GetAllSeatBalancesParams) (*ApiResponse[map[string]SeatBalance], error)
}

type SeatsResource

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

func (*SeatsResource) Add

func (*SeatsResource) GetAllBalances

func (r *SeatsResource) GetAllBalances(ctx context.Context, params *GetAllSeatBalancesParams) (*ApiResponse[map[string]SeatBalance], error)

func (*SeatsResource) GetBalance

func (*SeatsResource) Remove

func (r *SeatsResource) Remove(ctx context.Context, params *SeatParams) (*ApiResponse[SeatEvent], error)

func (*SeatsResource) Set

func (*SeatsResource) SetAll

func (r *SeatsResource) SetAll(ctx context.Context, params *SetAllSeatsParams) (*ApiResponse[[]SeatEvent], error)

type SetAllSeatsParams

type SetAllSeatsParams struct {
	Seats          map[string]int `json:"seats"`
	CustomerID     string         `json:"customer_id"`
	IdempotencyKey string         `json:"-"`
}

type Subscription added in v1.9.0

type Subscription struct {
	ID                      string   `json:"id"`
	CustomerID              string   `json:"customer_id"`
	PlanID                  string   `json:"plan_id"`
	PlanName                string   `json:"plan_name"`
	Name                    string   `json:"name"`
	Description             string   `json:"description,omitempty"`
	Status                  string   `json:"status"`
	BillingInterval         string   `json:"billing_interval,omitempty"`
	TrialEndsAt             string   `json:"trial_ends_at,omitempty"`
	StartDate               string   `json:"start_date"`
	EndDate                 string   `json:"end_date,omitempty"`
	CurrentPeriodStart      string   `json:"current_period_start,omitempty"`
	CurrentPeriodEnd        string   `json:"current_period_end,omitempty"`
	BillingDayOfMonth       int      `json:"billing_day_of_month"`
	CheckoutURL             string   `json:"checkout_url,omitempty"`
	CreatedAt               string   `json:"created_at"`
	UpdatedAt               string   `json:"updated_at"`
	IntroOfferEndsAt        string   `json:"intro_offer_ends_at,omitempty"`
	IntroOfferDiscountType  string   `json:"intro_offer_discount_type,omitempty"`
	IntroOfferDiscountValue *float64 `json:"intro_offer_discount_value,omitempty"`
}

type SubscriptionPeriod added in v1.9.0

type SubscriptionPeriod struct {
	Start         string `json:"start"`
	End           string `json:"end"`
	DaysRemaining int    `json:"days_remaining"`
}

type SubscriptionPlan added in v1.9.0

type SubscriptionPlan struct {
	ID              string  `json:"id"`
	Name            string  `json:"name"`
	BasePrice       float64 `json:"base_price"`
	BillingInterval string  `json:"billing_interval,omitempty"`
}

type Subscriptions added in v1.9.0

type Subscriptions interface {
	Create(ctx context.Context, params *CreateSubscriptionParams) (*ApiResponse[Subscription], error)
	Get(ctx context.Context, customerID string) (*ApiResponse[ActiveSubscription], error)
	Cancel(ctx context.Context, subscriptionID string, params *CancelSubscriptionParams) (*ApiResponse[Subscription], error)
}

type SubscriptionsResource

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

func (*SubscriptionsResource) Cancel

func (*SubscriptionsResource) Create

func (*SubscriptionsResource) Get

type TrackOption

type TrackOption func(*TrackUsageParams)

func WithProperties

func WithProperties(properties map[string]string) TrackOption

func WithValue

func WithValue(value int) TrackOption

type TrackUsageParams

type TrackUsageParams struct {
	Feature          string            `json:"feature"`
	CustomerID       string            `json:"customer_id"`
	Value            *int              `json:"value,omitempty"`
	Model            string            `json:"model,omitempty"`
	InputTokens      *int              `json:"input_tokens,omitempty"`
	OutputTokens     *int              `json:"output_tokens,omitempty"`
	CacheReadTokens  *int              `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens *int              `json:"cache_write_tokens,omitempty"`
	IdempotencyKey   string            `json:"-"`
	Timestamp        string            `json:"timestamp,omitempty"`
	Properties       map[string]string `json:"properties,omitempty"`
}

type UpdateCustomerParams

type UpdateCustomerParams struct {
	Email          string            `json:"billing_email,omitempty"`
	ExternalID     string            `json:"external_id,omitempty"`
	FullName       string            `json:"full_name,omitempty"`
	Domain         string            `json:"domain,omitempty"`
	Website        string            `json:"website,omitempty"`
	Timezone       string            `json:"timezone,omitempty"`
	Language       string            `json:"language,omitempty"`
	Industry       string            `json:"industry,omitempty"`
	Metadata       map[string]any    `json:"metadata,omitempty"`
	Address        map[string]string `json:"address,omitempty"`
	IdempotencyKey string            `json:"-"`
}

type Usage added in v1.9.0

type Usage interface {
	Track(ctx context.Context, params *TrackUsageParams) (*ApiResponse[UsageEvent], error)
}

type UsageEvent added in v1.9.0

type UsageEvent struct {
	ID             string               `json:"id"`
	OrganizationID string               `json:"organization_id"`
	CustomerID     string               `json:"customer_id"`
	Feature        string               `json:"feature"`
	IdempotencyKey string               `json:"idempotency_key,omitempty"`
	Ts             string               `json:"ts"`
	Properties     []UsageEventProperty `json:"properties,omitempty"`
	CreatedAt      string               `json:"created_at"`
}

type UsageEventProperty added in v1.9.0

type UsageEventProperty struct {
	ID           string `json:"id"`
	UsageEventID string `json:"usage_event_id"`
	Property     string `json:"property"`
	Value        string `json:"value"`
	CreatedAt    string `json:"created_at"`
}

type UsageResource

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

func (*UsageResource) Track

type ValidationError

type ValidationError struct {
	CommetError
	ValidationErrors map[string][]string
}

ValidationError represents a validation failure from the API.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WebhookVerifier added in v1.9.0

type WebhookVerifier interface {
	Verify(payload string, signature string, secret string) bool
	VerifyAndParse(rawBody string, signature string, secret string) (map[string]any, error)
}

type Webhooks

type Webhooks struct{}

Webhooks provides webhook signature verification.

func (*Webhooks) Verify

func (w *Webhooks) Verify(payload string, signature string, secret string) bool

Verify checks that a webhook payload signature is valid.

func (*Webhooks) VerifyAndParse

func (w *Webhooks) VerifyAndParse(rawBody string, signature string, secret string) (map[string]any, error)

VerifyAndParse verifies the signature and parses the payload as JSON.

Jump to

Keyboard shortcuts

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