control

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2023 License: BSD-3-Clause Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const Inf = 1<<63 - 1

Variables

View Source
var (
	ErrFeatureExists     = errors.New("feature already exists")
	ErrFeatureNotFound   = errors.New("feature not found")
	ErrNoFeatures        = errors.New("no features")
	ErrFeatureNotMetered = errors.New("feature is not metered")
	ErrPlanExists        = errors.New("plan already exists")
	ErrInvalidEmail      = errors.New("invalid email")
	ErrTooManyItems      = errors.New("too many subscription items")
	ErrInvalidPrice      = errors.New("invalid price")
)

Errors

View Source
var (
	ErrOrgNotFound     = errors.New("org not found")
	ErrInvalidMetadata = errors.New("invalid metadata")
	ErrInvalidPhase    = errors.New("invalid phase")
	ErrInvalidCancel   = errors.New("invalid cancel")

	// ErrInvalidFeature is returned when a customer that should have been
	// created is not found after "creating" it. This can happen in Test
	// Mode if the test data was cleared but the idempotency key is still
	// cached at Stripe.
	ErrUnexpectedMissingOrg = errors.New("unexpected missing org")
)

Errors

Functions

func Expand

func Expand(m []Feature, names ...string) ([]refs.FeaturePlan, error)

func FeaturePlans

func FeaturePlans(fs []Feature) []refs.FeaturePlan

func WithClock added in v0.10.0

func WithClock(ctx context.Context, clockID string) context.Context

Types

type Account added in v0.5.0

type Account struct {
	ProviderID string `json:"id"`
	Email      string `json:"email"`
	CreatedAt  int64  `json:"created"`
	KeySource  string `json:"key_source"`
	Isolated   bool   `json:"isolated"`
}

func (*Account) Created added in v0.5.0

func (a *Account) Created() time.Time

func (*Account) URL added in v0.5.0

func (a *Account) URL() string

type CheckoutParams added in v0.7.1

type CheckoutParams struct {
	TrialDays             int
	Features              []Feature
	CancelURL             string
	RequireBillingAddress bool
	AutomaticTax          bool
	CollectTaxID          bool
}

type Client

type Client struct {
	Logf      func(format string, args ...any)
	Stripe    *stripe.Client
	KeySource string // the source of the API key
	// contains filtered or unexported fields
}

func (*Client) Checkout added in v0.7.1

func (c *Client) Checkout(ctx context.Context, org string, successURL string, p *CheckoutParams) (link string, err error)

func (*Client) ClockFromID added in v0.10.0

func (c *Client) ClockFromID(id string) *Clock

ClockFromID returns a Clock for the given clock ID. It does not check that the clock exists or what its status is. If the status or present time are needed, clients should call Sync.

func (*Client) Isolated added in v0.5.0

func (c *Client) Isolated() bool

func (*Client) ListOrgs

func (c *Client) ListOrgs(ctx context.Context) ([]Org, error)

ListOrgs returns a list of all known customers in Stripe.

func (*Client) Live

func (c *Client) Live() bool

Live reports if APIKey is set to a "live" key.

func (*Client) LookupInvoices added in v0.7.0

func (c *Client) LookupInvoices(ctx context.Context, org string) ([]Invoice, error)

func (*Client) LookupLimits

func (c *Client) LookupLimits(ctx context.Context, org string) ([]Usage, error)

func (*Client) LookupOrg added in v0.6.0

func (c *Client) LookupOrg(ctx context.Context, org string) (*OrgInfo, error)

LookupOrg returns the org information on file with Stripe, uncached.

func (*Client) LookupPaymentMethods added in v0.9.0

func (c *Client) LookupPaymentMethods(ctx context.Context, org string) ([]payment.Method, error)

LookupPaymentMethods returns the payment methods for the given org.

func (*Client) LookupPhases

func (c *Client) LookupPhases(ctx context.Context, org string) (ps *Schedule, err error)

func (*Client) LookupStatus added in v0.7.0

func (c *Client) LookupStatus(ctx context.Context, org string) (string, error)

func (*Client) NewClock added in v0.10.0

func (c *Client) NewClock(ctx context.Context, name string, start time.Time) (*Clock, error)

NewClock creates a new clock in the Stripe account associated with the client and returns a Clock ready to use.

func (*Client) Pull

func (c *Client) Pull(ctx context.Context, limit int) ([]Feature, error)

Pull retrieves the feature from Stripe.

func (*Client) Push

func (c *Client) Push(ctx context.Context, fs []Feature, cb PushReportFunc) error

Push pushes each feature in fs to Stripe as a product and price combination. A new price and product are created in Stripe if one does not already exist.

All features intended to be in the same plan must all be pushed in a single call to Push. Any subsequent calls attempting to push a feature in a plan that has already been pushed, will result in ErrPlanExists, and no attempt to push any feature in fs will be made. This constraint keeps plan immutable.

Each call to push is subject to rate limiting via the clients shared rate limit.

It returns the first error encountered if any.

func (*Client) PutCustomer added in v0.6.0

func (c *Client) PutCustomer(ctx context.Context, org string, info *OrgInfo) error

PutCustomer safely creates or updates a customer in Stripe. It does this being careful to not duplicate customer records. If the customer already exists, it will be updated with the provided info.

func (*Client) ReportUsage

func (c *Client) ReportUsage(ctx context.Context, org string, feature refs.Name, use Report) error

func (*Client) Schedule

func (c *Client) Schedule(ctx context.Context, org string, p ScheduleParams) error

func (*Client) SubscribeTo

func (c *Client) SubscribeTo(ctx context.Context, org string, fs []refs.FeaturePlan) error

SubscribeTo subscribes org to the provided features effective immediately, taking over any in-progress schedule. The customer is billed immediately with prorations if any.

func (*Client) WhoAmI added in v0.5.0

func (c *Client) WhoAmI(ctx context.Context) (Account, error)

func (*Client) WhoIs

func (c *Client) WhoIs(ctx context.Context, org string) (id string, err error)

type Clock added in v0.10.0

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

func (*Clock) Advance added in v0.10.0

func (c *Clock) Advance(ctx context.Context, to time.Time) error

Advance advances the clock to the given time.

func (*Clock) ID added in v0.10.0

func (c *Clock) ID() string
func (c *Clock) Link() string

Link returns a link to the clock in the Stripe dashboard.

func (*Clock) Present added in v0.10.0

func (c *Clock) Present() time.Time

func (*Clock) Status added in v0.10.0

func (c *Clock) Status() string

func (*Clock) Sync added in v0.10.0

func (c *Clock) Sync(ctx context.Context) error

func (*Clock) Wait added in v0.10.0

func (c *Clock) Wait(ctx context.Context) error

Wait waits for the clock to be ready, or until the context is canceled. It returns an error if any.

type Coupon added in v0.12.0

type Coupon struct {
	ID               string `json:"id"`
	Metadata         map[string]string
	Created          time.Time
	AmountOff        int     `json:"amount_off"`
	Currency         string  `json:"currency"`
	Duration         string  `json:"duration"`
	DurationInMonths int     `json:"duration_in_months"`
	MaxRedemptions   int     `json:"max_redemptions"`
	Name             string  `json:"name"`
	PercentOff       float64 `json:"percent_off"`
	RedeemBy         time.Time
	TimesRedeemed    int  `json:"times_redeemed"`
	Valid            bool `json:"valid"`
}

type Feature

type Feature struct {
	refs.FeaturePlan // the feature name prefixed with ("feature:")

	ProviderID string // identifier set by the billing engine provider
	PlanTitle  string // a human readable title for the plan
	Title      string // a human readable title for the feature

	// Interval specifies the billing interval for the feature.
	//
	// Known intervals are "@daily", "@weekly", "@monthly", and "@yearly".
	Interval string

	// Currency is the ISO 4217 currency code for the feature.
	//
	// Known currencies look like "usd", "eur", "gbp", "cad", "aud", "jpy", "chf",
	// etc. Please see your billing engine provider for a complete list.
	Currency string

	// Base is the base price for the feature. If Tiers is not empty, then Base
	// is ignored.
	Base float64

	// Mode specifies the billing mode for use with Tiers.
	//
	// Known modes are "graduated" and "volume".
	Mode string

	// Aggregate specifies the usage aggregation method for use with Tiers.
	//
	// Known aggregates are "sum", "max", "last", and "perpetual".
	Aggregate string

	// Tiers optionally specifies the pricing tiers for this feature. If
	// empty, feature is billed at the beginning of each billing period at
	// the flat rate specified by Base. If non-empty, the feature is billed
	// at the end of each billing period based on usage, and at a price
	// determined by Tiers, Mode, and Aggregate.
	Tiers []Tier

	// ReportID is the ID for reporting usage to the billing provider.
	ReportID string

	TransformDenominator int  // the denominator for transforming usage
	TransformRoundUp     bool // whether to round up transformed usage; otherwise round down
}

func ExpandPlans added in v0.7.1

func ExpandPlans(fs []Feature, names ...string) ([]Feature, error)

ExpandPlans parses each ref in refs and adds it to the result. If the ref is a plan ref, Expand will append all features in fs for that plan to the result. returns an error if any ref is invalid or not availabe in the

The parameter fs is assumed to have no two features with the same FeaturePlan.

It returns an error if any.

func (*Feature) ID

func (f *Feature) ID() string

func (*Feature) IsMetered

func (f *Feature) IsMetered() bool

IsMetered reports if the feature is metered.

func (*Feature) Limit

func (f *Feature) Limit() int

type Invoice added in v0.7.0

type Invoice struct {
	Amount float64
	Period Period
	Lines  []InvoiceLineItem

	SubtotalPreTax int
	Subtotal       int
	TotalPreTax    int
	Total          int
}

type InvoiceLineItem added in v0.7.0

type InvoiceLineItem struct {
	Period    Period
	Feature   refs.FeaturePlan
	Quantity  int
	Amount    float64
	Proration bool
}

type InvoiceSettings added in v0.7.1

type InvoiceSettings struct {
	DefaultPaymentMethod string `json:"default_payment_method"`
}

type Org

type Org struct {
	ProviderID string
	ID         string
	Email      string
}

type OrgInfo added in v0.6.0

type OrgInfo struct {
	Email       string
	Name        string
	Description string
	Phone       string
	Metadata    map[string]string
	Created     int

	PaymentMethod   string
	InvoiceSettings InvoiceSettings `json:"invoice_settings"`
}

func (*OrgInfo) CreatedAt added in v0.10.0

func (oi *OrgInfo) CreatedAt() time.Time

type Period added in v0.7.0

type Period struct {
	Effective time.Time
	End       time.Time
}

type Phase

type Phase struct {
	Org       string // set on read
	Effective time.Time
	Features  []refs.FeaturePlan
	Current   bool

	Trial bool // Marks the phase as a trial phase. No fees will be incurred during a trial phase.

	// Plans is the set of plans that are currently active for the phase. A
	// plan is considered active in a phase if all of its features are
	// listed in the phase. If any features from a plan is in the phase
	// without the other features in the plan, this phase is considered
	// "fragmented".
	Plans []refs.Plan

	AutomaticTax bool

	Coupon string // deprecated

	// CouponData is the coupon that was applied to the subscription. It is
	// nil if no coupon was applied.
	CouponData *Coupon
}

func (*Phase) Fragments

func (p *Phase) Fragments() []refs.FeaturePlan

func (*Phase) Valid added in v0.7.1

func (p *Phase) Valid() bool

Valid reports if the Phase is one that would be retured from the Stripe API. Currently, this is determined if the phase has any features.

type PushReportFunc added in v0.5.2

type PushReportFunc func(Feature, error)

PushReportFunc is called for each feature pushed to Stripe. Implementations must be safe to use accross goroutines.

type Report

type Report struct {
	N       int
	At      time.Time
	Clobber bool
}

type Schedule added in v0.10.0

type Schedule struct {
	Current Period
	Phases  []Phase
}

type ScheduleParams added in v0.9.0

type ScheduleParams struct {
	PaymentMethod string
	Phases        []Phase
}

type Tier

type Tier struct {
	Upto  int     // the upper limit of the tier
	Price float64 // the price of the tier
	Base  int     // the base price of the tier
}

Tier holds the pricing information for a single tier.

type Usage

type Usage struct {
	Feature refs.FeaturePlan
	Start   time.Time
	End     time.Time
	Used    int
	Limit   int
}

type ValidationError

type ValidationError struct {
	Message string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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