entitlements

package
v0.45.13 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

README

Entitlements

The entitlements package wraps Stripe billing APIs and OpenFGA feature authorization. It manages organization subscriptions, available modules, and runtime feature checks. This package centralizes the logic for creating and updating Stripe resources while keeping feature state in OpenFGA with a Redis cache for ideally faster lookup (not yet benchmarked but a decently safe assumption).

Purpose

  • Provide a Go client for Stripe that exposes helper functions to create customers, prices, products and subscriptions
  • Process Stripe webhooks to keep feature tuples in sync with purchases
  • Offer the TupleChecker utility for feature gating via OpenFGA with optional Redis caching

A more in‑depth discussion of how modules and entitlements flow through the system can be found in docs/entitlements.md.

Approach

The package relies on the official stripe-go client. Helper functions use functional options so callers can supply only the fields they need. When webhooks are received the handler translates Stripe events into updates to OpenFGA tuples and refreshes the cached feature list. Feature checks first consult Redis and fall back to OpenFGA if no cache entry exists.

Key types include:

  • StripeClient – thin wrapper around stripe.Client with higher level helpers
  • OrganizationCustomer and Subscription – internal representations of Stripe customers/subscriptions
  • TupleChecker – verifies feature tuples and creates/deletes them in OpenFGA while caching results in Redis

Integration

Application configuration embeds entitlements.Config in the global config.Config struct. When the HTTP server starts it constructs a StripeClient using that config and stores it on the handler:

h := &handlers.Handler{
    Entitlements: stripeClient,
}

The webhook receiver in internal/httpserve/handlers/webhook.go uses this client to update subscriptions and feature tuples when events arrive. Ent hooks in internal/ent/hooks/organization.go create default feature tuples for new organizations.

Examples

Creating a client and customer
sc, err := entitlements.NewStripeClient(
    entitlements.WithAPIKey("sk_test_..."),
)
if err != nil {
    log.Fatal(err)
}

cust, err := sc.CreateCustomer(context.Background(), &entitlements.OrganizationCustomer{
    OrganizationID: "org_123",
    Email:          "billing@example.com",
})
Feature checks with TupleChecker
redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
tc := entitlements.NewTupleChecker(
    entitlements.WithRedisClient(redisClient),
    entitlements.WithFGAClient(myFGAClient),
)

allowed, err := tc.CheckFeatureTuple(ctx, entitlements.FeatureTuple{
    UserID:  "user1",
    Feature: "compliance-module",
    Context: map[string]any{"org": "org_123"},
})
Local webhook testing

Install the Stripe CLI and forward events to your server:

stripe login
stripe listen --forward-to localhost:17608/v1/stripe/webhook

You can then trigger events, for example:

stripe trigger payment_intent.succeeded

This mirrors the flow described in the "End‑to‑End Flow" section of the docs/entitlements.md document.

Documentation

Overview

Package entitlements is a wrapper package for the entitlements service and a basic stripe integration

Index

Constants

View Source
const (
	StatusSuccess = "success"
	StatusError   = "error"
)
View Source
const (
	TupleObjectType = "feature"
	TupleRelation   = "enabled"
)
View Source
const MigrateToKey = "migrate_to"

MigrateToKey is the metadata key used to indicate the price that a subscription should migrate to

View Source
const UpsellToKey = "upsell_to"

UpsellToKey is the metadata key used to denote the price that another price should upsell into

Variables

View Source
var (
	// ErrFoundMultipleCustomers is returned when multiple customers are found
	ErrFoundMultipleCustomers = errors.New("found multiple customers with the same name")
	// ErrMultipleSubscriptions = errors.New("multiple subscriptions found")
	ErrMultipleSubscriptions = errors.New("multiple subscriptions found")
	// ErrNoSubscriptions is returned when no subscriptions are found
	ErrNoSubscriptions = errors.New("no subscriptions found")
	// ErrCustomerNotFound is returned when a customer is not found
	ErrCustomerNotFound = errors.New("customer not found")
	// ErrCustomerLookupFailed is returned when a customer lookup fails
	ErrCustomerLookupFailed = errors.New("failed to lookup customer")
	// ErrCustomerSearchFailed is returned when a customer search fails
	ErrCustomerSearchFailed = errors.New("failed to search for customer")
	// ErrProductListFailed is returned when a product list fails
	ErrProductListFailed = errors.New("failed to list products")
	// ErrCustomerIDRequired is returned when a customer ID is required
	ErrCustomerIDRequired = errors.New("customer ID is required")
	// ErrMissingAPIKey is returned when the API key is missing
	ErrMissingAPIKey = errors.New("missing API key")
	// ErrNoSubscriptionItems is returned when no subscription items are found
	ErrNoSubscriptionItems = errors.New("no subscription items found to create subscription")
)
View Source
var (
	// ErrWebhookNotFound is returned when a webhook endpoint is not found
	ErrWebhookNotFound = errors.New("webhook endpoint not found")
	// ErrWebhookAlreadyExists is returned when a webhook endpoint already exists
	ErrWebhookAlreadyExists = errors.New("webhook endpoint already exists")
	// ErrWebhookVersionMismatch is returned when webhook API version does not match SDK version
	ErrWebhookVersionMismatch = errors.New("webhook API version does not match SDK version")
	// ErrMultipleWebhooksFound is returned when multiple webhooks are found for the same URL
	ErrMultipleWebhooksFound = errors.New("multiple webhook endpoints found for URL")
	// ErrWebhookURLRequired is returned when webhook URL is required but not provided
	ErrWebhookURLRequired = errors.New("webhook URL is required")
	// ErrInvalidMigrationState is returned when the migration state is invalid for the requested operation
	ErrInvalidMigrationState = errors.New("invalid migration state for requested operation")
	// ErrOldWebhookNotFound is returned when the old webhook endpoint is not found during migration
	ErrOldWebhookNotFound = errors.New("old webhook endpoint not found for migration")
	// ErrNewWebhookAlreadyExists is returned when attempting to create a new webhook that already exists
	ErrNewWebhookAlreadyExists = errors.New("new webhook endpoint already exists")
	// ErrAPIVersionRequired is returned when an API version is required but not provided
	ErrAPIVersionRequired = errors.New("api version is required")
	// ErrEnabledWebhookNotFoundByVersion is returned when no enabled webhook matches the requested version
	ErrEnabledWebhookNotFoundByVersion = errors.New("enabled webhook not found for version")
)
View Source
var (
	// ErrTupleCheckerNotConfigured is returned when TupleChecker is not properly configured
	ErrTupleCheckerNotConfigured = errors.New("TupleChecker not properly configured")
)

SupportedEventTypes defines the Stripe events the webhook handler listens for.

Functions

func AddNewItemsIfNotExist added in v0.20.0

func AddNewItemsIfNotExist(existing []*stripe.SubscriptionItem, params *stripe.SubscriptionUpdateParams, newItems ...*stripe.SubscriptionUpdateItemParams)

AddNewItemsIfNotExist is a helper to add new items to update params if they don't already exist

func CompareWebhookEvents added in v0.43.4

func CompareWebhookEvents(a, b []string) bool

CompareWebhookEvents compares two sets of webhook events and returns true if they match

func CreateFeatureTuples added in v0.30.10

func CreateFeatureTuples(ctx context.Context, authz *fgax.Client, orgID string, feats []models.OrgModule) error

CreateFeatureTuples writes default feature tuples to FGA and inserts them into the feature cache if available.

func CreateProductFeatureAssociationWithOptions added in v0.20.0

func CreateProductFeatureAssociationWithOptions(baseParams *stripe.ProductFeatureCreateParams, opts ...ProductFeatureCreateOption) *stripe.ProductFeatureCreateParams

CreateProductFeatureAssociationWithOptions creates params for associating a feature to a product

func DeleteModuleTuple added in v0.30.10

func DeleteModuleTuple(ctx context.Context, authz *fgax.Client, orgID, moduleName string) error

DeleteModuleTuple removes the enabled feature from the organization in the authorization service

func GetNextMigrationAction added in v0.43.4

func GetNextMigrationAction(stage string) string

GetNextMigrationAction returns a description of the next action to take in the migration

func GetOrganizationIDFromMetadata added in v0.7.4

func GetOrganizationIDFromMetadata(metadata map[string]string) string

GetOrganizationIDFromMetadata gets the organization ID from the metadata if it exists, otherwise returns an empty string

func GetOrganizationNameFromMetadata added in v0.7.4

func GetOrganizationNameFromMetadata(metadata map[string]string) string

GetOrganizationNameFromMetadata gets the organization name from the metadata if it exists, otherwise returns an empty string

func GetOrganizationSettingsIDFromMetadata added in v0.7.4

func GetOrganizationSettingsIDFromMetadata(metadata map[string]string) string

GetOrganizationSettingsIDFromMetadata gets the organization settings ID from the metadata if it exists, otherwise returns an empty string

func GetOrganizationSubscriptionIDFromMetadata added in v0.7.4

func GetOrganizationSubscriptionIDFromMetadata(metadata map[string]string) string

GetOrganizationSubscriptionIDFromMetadata gets the organization subscription ID from the metadata if it exists, otherwise returns an empty string

func GetUpdatedFields added in v0.7.4

func GetUpdatedFields(props map[string]any, orgCustomer *OrganizationCustomer) (params *stripe.CustomerUpdateParams)

GetUpdatedFields checks for updates to billing information in the properties and returns a stripe.CustomerParams object with the updated information and a boolean indicating whether there are updates

func IsSubscriptionActive added in v0.10.11

func IsSubscriptionActive(status stripe.SubscriptionStatus) bool

IsSubscriptionActive checks if a subscription is active based on its status

func Seq2IsEmpty added in v0.23.0

func Seq2IsEmpty[K any, V error](seq stripe.Seq2[K, V]) bool

Seq2IsEmpty checks if a stripe.Seq2 is empty.

Parameters:

  • seq: a stripe.Seq2 iterator of type K and error type V.

Returns:

  • bool: true if the sequence is empty, false otherwise.

func SupportedEventTypeStrings added in v0.20.0

func SupportedEventTypeStrings() []string

SupportedEventTypeStrings returns SupportedEventTypes as a slice of strings.

func SyncTuples added in v0.20.0

func SyncTuples(ctx context.Context, client *fgax.Client, subjectID, subjectType, objectType, relation string, oldItems, newItems []string,
) error

SyncTuples updates openFGA tuples for a given subject and object type/relation. It adds tuples for items in 'newItems' not in 'oldItems', and deletes tuples for items in 'oldItems' not in 'newItems'. This function is generic and can be reused for different subject/object types and relations.

func WritePlansToYAML

func WritePlansToYAML(product []Product, filename string) error

WritePlansToYAML writes the []Product information into a YAML file.

Types

type AttachFeatureToProductWithOptions added in v0.20.0

type AttachFeatureToProductWithOptions func(params *stripe.ProductFeatureCreateParams)

AttachFeatureToProductWithOptions creates params for attaching a feature to a product

type BillingPortalSession added in v0.7.4

type BillingPortalSession struct {
	ManageSubscription string `json:"manage_subscription"`
	PaymentMethods     string `json:"payment_methods"`
	Cancellation       string `json:"cancellation"`
	HomePage           string `json:"home_page"`
}

BillingPortalSession holds the billing portal session information

type Config

type Config struct {
	// Enabled determines if the entitlements service is enabled
	Enabled bool `json:"enabled" koanf:"enabled" default:"false"`
	// PrivateStripeKey is the key for the stripe service
	PrivateStripeKey string `json:"privateStripeKey" koanf:"privateStripeKey" default:"" sensitive:"true"`
	// StripeWebhookSecret is the secret for the stripe service (legacy, use StripeWebhookSecrets for version-specific secrets)
	StripeWebhookSecret string `json:"stripeWebhookSecret" koanf:"stripeWebhookSecret" default:"" sensitive:"true"`
	// StripeWebhookSecrets is a map of API version to webhook secrets for safe migration rollback
	StripeWebhookSecrets map[string]string `json:"stripeWebhookSecrets" koanf:"stripeWebhookSecrets" sensitive:"true"`
	// StripeWebhookURL is the URL for the stripe webhook
	StripeWebhookURL string `` /* 178-byte string literal not displayed */
	// StripeBillingPortalSuccessURL
	StripeBillingPortalSuccessURL string `` /* 239-byte string literal not displayed */
	// StripeCancellationReturnURL is the URL for the stripe cancellation return
	StripeCancellationReturnURL string `` /* 235-byte string literal not displayed */
	// StripeWebhookEvents is the list of events to register when creating a webhook endpoint
	StripeWebhookEvents []string `json:"stripeWebhookEvents" koanf:"stripeWebhookEvents"`
	// StripeWebhookAPIVersion is the Stripe API version currently accepted by the webhook handler
	StripeWebhookAPIVersion string `json:"stripeWebhookAPIVersion" koanf:"stripeWebhookAPIVersion" default:"2025_10_29_CLOVER"`
	// StripeWebhookDiscardAPIVersion is the Stripe API version to discard during migration
	StripeWebhookDiscardAPIVersion string `json:"stripeWebhookDiscardAPIVersion" koanf:"stripeWebhookDiscardAPIVersion" default:""`
}

func NewConfig added in v0.5.0

func NewConfig(opts ...ConfigOpts) *Config

NewConfig creates a new entitlements config

func (*Config) GetWebhookSecretForVersion added in v0.43.4

func (c *Config) GetWebhookSecretForVersion(apiVersion string) string

GetWebhookSecretForVersion returns the webhook secret for a specific API version It first checks the version-specific secrets map, then falls back to the legacy StripeWebhookSecret

func (*Config) IsEnabled added in v0.30.10

func (c *Config) IsEnabled() bool

IsEnabled checks if the entitlements feature is enabled based on the status of the Stripe client settings

type ConfigOpts added in v0.5.0

type ConfigOpts func(*Config)

func WithEnabled added in v0.5.0

func WithEnabled(enabled bool) ConfigOpts

WithEnabled sets the enabled field

func WithPrivateStripeKey added in v0.5.0

func WithPrivateStripeKey(privateStripeKey string) ConfigOpts

WithPrivateStripeKey sets the private stripe key

func WithStripeBillingPortalSuccessURL added in v0.5.0

func WithStripeBillingPortalSuccessURL(stripeBillingPortalSuccessURL string) ConfigOpts

WithStripeBillingPortalSuccessURL sets the stripe billing portal success URL

func WithStripeCancellationReturnURL added in v0.7.4

func WithStripeCancellationReturnURL(stripeCancellationReturnURL string) ConfigOpts

WithStripeCancellationReturnURL sets the stripe cancellation return URL

func WithStripeWebhookAPIVersion added in v0.43.4

func WithStripeWebhookAPIVersion(version string) ConfigOpts

WithStripeWebhookAPIVersion sets the current accepted Stripe API version for webhooks

func WithStripeWebhookDiscardAPIVersion added in v0.43.4

func WithStripeWebhookDiscardAPIVersion(version string) ConfigOpts

WithStripeWebhookDiscardAPIVersion sets the Stripe API version to discard during migration

func WithStripeWebhookEvents added in v0.20.0

func WithStripeWebhookEvents(events []string) ConfigOpts

WithStripeWebhookEvents sets the stripe webhook events

func WithStripeWebhookSecret added in v0.5.0

func WithStripeWebhookSecret(stripeWebhookSecret string) ConfigOpts

WithStripeWebhookSecret sets the stripe webhook secret

func WithStripeWebhookSecrets added in v0.43.4

func WithStripeWebhookSecrets(secrets map[string]string) ConfigOpts

WithStripeWebhookSecrets sets the map of version-specific webhook secrets

func WithStripeWebhookURL added in v0.5.0

func WithStripeWebhookURL(stripeWebhookURL string) ConfigOpts

WithStripeWebhookURL sets the stripe webhook URL

type ContactInfo added in v0.6.5

type ContactInfo struct {
	Email      string  `json:"email"`
	Phone      string  `json:"phone"`
	City       *string `form:"city"`
	Country    *string `form:"country"`
	Line1      *string `form:"line1"`
	Line2      *string `form:"line2"`
	PostalCode *string `form:"postal_code"`
	State      *string `form:"state"`
}

ContactInfo holds the contact information for the organization

type CustomerCreateOption added in v0.20.0

type CustomerCreateOption func(params *stripe.CustomerCreateParams)

CustomerCreateOption allows customizing CustomerCreateParams

func WithCustomerAddress added in v0.20.0

func WithCustomerAddress(addr *stripe.AddressParams) CustomerCreateOption

WithCustomerAddress sets the address for the customer

func WithCustomerEmail added in v0.20.0

func WithCustomerEmail(email string) CustomerCreateOption

WithCustomerEmail sets the email for the customer

func WithCustomerMetadata added in v0.20.0

func WithCustomerMetadata(metadata map[string]string) CustomerCreateOption

WithCustomerMetadata sets metadata for the customer

func WithCustomerName added in v0.20.0

func WithCustomerName(name string) CustomerCreateOption

WithCustomerName sets the name for the customer

func WithCustomerPhone added in v0.20.0

func WithCustomerPhone(phone string) CustomerCreateOption

WithCustomerPhone sets the phone for the customer

type CustomerUpdateOption added in v0.20.0

type CustomerUpdateOption func(params *stripe.CustomerUpdateParams)

CustomerUpdateOption allows customizing CustomerUpdateParams

func WithUpdateCustomerAddress added in v0.20.0

func WithUpdateCustomerAddress(addr *stripe.AddressParams) CustomerUpdateOption

WithUpdateCustomerAddress sets the address for the customer update

func WithUpdateCustomerEmail added in v0.20.0

func WithUpdateCustomerEmail(email string) CustomerUpdateOption

WithUpdateCustomerEmail sets the email for the customer update

func WithUpdateCustomerMetadata added in v0.20.0

func WithUpdateCustomerMetadata(metadata map[string]string) CustomerUpdateOption

WithUpdateCustomerMetadata sets metadata for the customer update

func WithUpdateCustomerPhone added in v0.20.0

func WithUpdateCustomerPhone(phone string) CustomerUpdateOption

WithUpdateCustomerPhone sets the phone for the customer update

type FGAClient added in v0.20.0

type FGAClient interface {
	CheckTuple(ctx context.Context, tuple FeatureTuple) (bool, error)
	CreateTuple(ctx context.Context, tuple FeatureTuple) error
	DeleteTuple(ctx context.Context, tuple FeatureTuple) error
}

FGAClient is an interface for FGA tuple checking/creation/deletion

type Feature

type Feature struct {
	ID        string `json:"id" yaml:"id"`
	Name      string `json:"name" yaml:"name"`
	Lookupkey string `json:"lookupkey" yaml:"lookupkey"`
}

Feature are part of a product

type FeatureCreateOption added in v0.20.0

type FeatureCreateOption func(params *stripe.EntitlementsFeatureCreateParams)

FeatureCreateOption allows customizing EntitlementsFeatureCreateParams

func WithFeatureLookupKey added in v0.20.0

func WithFeatureLookupKey(lookupKey string) FeatureCreateOption

WithFeatureLookupKey allows setting the lookup key for a feature

func WithFeatureName added in v0.20.0

func WithFeatureName(name string) FeatureCreateOption

WithFeatureName allows setting the name of the feature

type FeatureTuple added in v0.20.0

type FeatureTuple struct {
	// UserID is the identifier for the user or entity being checked
	UserID string
	// Feature is the name of the feature being checked - can be any feature
	Feature string
	// Context is a map of additional context for the tuple, can be used for feature flags or other metadata
	Context map[string]any
}

FeatureTuple represents a generic tuple for feature checks

type FeatureUpdateOption added in v0.20.0

type FeatureUpdateOption func(params *stripe.EntitlementsFeatureUpdateParams)

EntitlementsFeatureCreateWithOptions creates create params with functional options

func WithUpdateFeatureName added in v0.20.0

func WithUpdateFeatureName(name string) FeatureUpdateOption

WithUpdateFeatureName allows setting the name of the feature in update params

type MigrationStage added in v0.43.4

type MigrationStage string

MigrationStage represents the stages of webhook migration

const (
	// MigrationStageNone indicates no migration is in progress
	MigrationStageNone MigrationStage = "none"
	// MigrationStageReady indicates ready to start migration
	MigrationStageReady MigrationStage = "ready"
	// MigrationStageNewCreated indicates new webhook has been created but disabled
	MigrationStageNewCreated MigrationStage = "new_created"
	// MigrationStageDualProcessing indicates both webhooks are enabled
	MigrationStageDualProcessing MigrationStage = "dual_processing"
	// MigrationStageComplete indicates migration is complete, only new webhook is active
	MigrationStageComplete MigrationStage = "complete"
)

type OrganizationCustomer added in v0.5.0

type OrganizationCustomer struct {
	OrganizationID               string `json:"organization_id"`
	OrganizationSettingsID       string `json:"organization_settings_id"`
	StripeCustomerID             string `json:"stripe_customer_id"`
	OrganizationName             string `json:"organization_name"`
	OrganizationSubscriptionID   string `json:"organization_subscription_id"`
	StripeSubscriptionID         string `json:"stripe_subscription_id"`
	StripeSubscriptionScheduleID string `json:"stripe_subscription_schedule_id"`
	PaymentMethodAdded           bool   `json:"payment_method_added"`
	Features                     []string
	FeatureNames                 []string
	Metadata                     map[string]string `json:"metadata"`

	Subscription
	ContactInfo
}

OrganizationCustomer is a struct which holds both internal organization infos and external stripe infos

func MapStripeCustomer added in v0.7.4

func MapStripeCustomer(c *stripe.Customer) *OrganizationCustomer

MapStripeCustomer maps a stripe customer to an organization customer this is used to convert the stripe customer object to our internal customer object we use the metadata to store the organization ID, settings ID, and subscription ID

func (*OrganizationCustomer) Validate added in v0.5.0

func (o *OrganizationCustomer) Validate() error

Validate checks if the OrganizationCustomer contains necessary fields

type Price

type Price struct {
	ID          string  `json:"price_id" yaml:"price_id"`
	Price       float64 `json:"price" yaml:"price"`
	Currency    string  `json:"currency" yaml:"currency"`
	ProductID   string  `json:"product_id" yaml:"-"`
	ProductName string  `json:"product_name" yaml:"product_name"`
	Interval    string  `json:"interval" yaml:"interval"`
}

Price holds stripe price params and the associated Product

type PriceCreateOption added in v0.20.0

type PriceCreateOption func(params *stripe.PriceCreateParams)

PriceCreateOption allows customizing PriceCreateParams

func WithPriceAmount added in v0.20.0

func WithPriceAmount(amount int64) PriceCreateOption

WithPriceAmount sets the unit amount for the price

func WithPriceCurrency added in v0.20.0

func WithPriceCurrency(currency string) PriceCreateOption

WithPriceCurrency sets the currency for the price

func WithPriceMetadata added in v0.20.0

func WithPriceMetadata(metadata map[string]string) PriceCreateOption

WithPriceMetadata sets metadata for the price

func WithPriceProduct added in v0.20.0

func WithPriceProduct(productID string) PriceCreateOption

WithPriceProduct sets the product ID for the price

func WithPriceRecurring added in v0.20.0

func WithPriceRecurring(interval string) PriceCreateOption

WithPriceRecurring sets the recurring interval for the price

type PriceUpdateOption added in v0.20.0

type PriceUpdateOption func(params *stripe.PriceUpdateParams)

PriceUpdateOption allows customizing PriceUpdateParams

func WithUpdatePriceMetadata added in v0.20.0

func WithUpdatePriceMetadata(metadata map[string]string) PriceUpdateOption

WithUpdatePriceMetadata sets metadata for the price update

type Product

type Product struct {
	ID          string    `json:"product_id" yaml:"product_id"`
	Name        string    `json:"name" yaml:"name"`
	Description string    `json:"description,omitempty" yaml:"description,omitempty"`
	Features    []Feature `json:"features" yaml:"features"`
	Prices      []Price   `json:"prices" yaml:"prices"`
}

Product holds what we'd more commply call a "tier"

type ProductFeature

type ProductFeature struct {
	FeatureID string `json:"feature_id" yaml:"feature_id"`
	ProductID string `json:"product_id"`
	Name      string `json:"name" yaml:"name"`
	Lookupkey string `json:"lookupkey" yaml:"lookupkey"`
}

ProductFeature is the defined relationship between the product and feature

type ProductFeatureCreateOption added in v0.20.0

type ProductFeatureCreateOption func(params *stripe.ProductFeatureCreateParams)

ProductFeatureCreateOption allows customizing ProductFeatureCreateParams

func WithProductFeatureEntitlementFeatureID added in v0.20.0

func WithProductFeatureEntitlementFeatureID(featureID string) ProductFeatureCreateOption

WithProductFeatureEntitlementFeatureID allows setting the entitlement feature ID for a product feature

func WithProductFeatureProductID added in v0.20.0

func WithProductFeatureProductID(productID string) ProductFeatureCreateOption

WithProductFeatureProductID allows setting the product ID for a product feature

type ProductUpdateOption added in v0.20.0

type ProductUpdateOption func(params *stripe.ProductUpdateParams)

ProductUpdateOption allows customizing ProductUpdateParams

func WithUpdateProductDescription added in v0.20.0

func WithUpdateProductDescription(desc string) ProductUpdateOption

func WithUpdateProductMetadata added in v0.20.0

func WithUpdateProductMetadata(metadata map[string]string) ProductUpdateOption

func WithUpdateProductName added in v0.20.0

func WithUpdateProductName(name string) ProductUpdateOption

type StripeClient

type StripeClient struct {
	// Client is the Stripe client and is used for accessing all subsequent stripe objects, e.g. products, prices, etc.
	Client *stripe.Client

	// config is the configuration for the Stripe client
	Config *Config
	// contains filtered or unexported fields
}

StripeClient is a client for the Stripe API

func NewStripeClient

func NewStripeClient(opts ...StripeOptions) (*StripeClient, error)

NewStripeClient creates a new Stripe client

func (*StripeClient) AttachFeatureToProductWithOptions added in v0.20.0

func (sc *StripeClient) AttachFeatureToProductWithOptions(ctx context.Context, baseParams *stripe.ProductFeatureCreateParams, opts ...ProductFeatureCreateOption) (*stripe.ProductFeature, error)

AttachFeatureToProductWithOptions attaches an existing entitlements feature to a product using functional options.

func (*StripeClient) CancelSubscription

func (sc *StripeClient) CancelSubscription(ctx context.Context, id string, params *stripe.SubscriptionCancelParams) (*stripe.Subscription, error)

CancelSubscription cancels a subscription

func (*StripeClient) CreateBillingPortalPaymentMethods added in v0.7.4

func (sc *StripeClient) CreateBillingPortalPaymentMethods(ctx context.Context, custID string) (*BillingPortalSession, error)

CreateBillingPortalPaymentMethods generates a session in stripe's billing portal which allows the customer to add / update payment methods

func (*StripeClient) CreateCustomer

func (sc *StripeClient) CreateCustomer(ctx context.Context, c *OrganizationCustomer) (*stripe.Customer, error)

CreateCustomer creates a customer leveraging the openlane organization ID as the organization name, and the email provided as the billing email we assume that the billing email will be changed, so lookups are performed by the organization ID

func (*StripeClient) CreateCustomerAndSubscription added in v0.28.0

func (sc *StripeClient) CreateCustomerAndSubscription(ctx context.Context, o *OrganizationCustomer) error

CreateCustomerAndSubscription handles the case where no customer exists by creating both the customer and their initial subscription

func (*StripeClient) CreateCustomerWithOptions added in v0.20.0

func (sc *StripeClient) CreateCustomerWithOptions(baseParams *stripe.CustomerCreateParams, opts ...CustomerCreateOption) *stripe.CustomerCreateParams

CreateCustomerWithOptions creates a customer with functional options

func (*StripeClient) CreateNewWebhookForMigration added in v0.43.4

func (sc *StripeClient) CreateNewWebhookForMigration(ctx context.Context, baseURL string, events []string, apiVersion string) (*stripe.WebhookEndpoint, error)

CreateNewWebhookForMigration creates a new webhook endpoint with the provided API version

func (*StripeClient) CreatePrice added in v0.8.9

func (sc *StripeClient) CreatePrice(ctx context.Context, productID string, unitAmount int64, currency, interval, nickname, lookupKey string, metadata map[string]string) (*stripe.Price, error)

CreatePrice a price for a product in stripe

func (*StripeClient) CreatePriceWithOptions added in v0.20.0

func (sc *StripeClient) CreatePriceWithOptions(baseParams *stripe.PriceCreateParams, opts ...PriceCreateOption) *stripe.PriceCreateParams

CreatePriceWithOptions creates a price with functional options

func (*StripeClient) CreatePriceWithParams added in v0.20.0

func (sc *StripeClient) CreatePriceWithParams(ctx context.Context, params *stripe.PriceCreateParams) (*stripe.Price, error)

CreatePriceWithParams creates a price with the given parameters

func (*StripeClient) CreateProduct added in v0.8.9

func (sc *StripeClient) CreateProduct(ctx context.Context, name, description string, metadata map[string]string) (*stripe.Product, error)

CreateProduct creates a new product in Stripe

func (*StripeClient) CreateProductFeatureWithOptions added in v0.20.0

func (sc *StripeClient) CreateProductFeatureWithOptions(ctx context.Context, baseParams *stripe.EntitlementsFeatureCreateParams, opts ...FeatureCreateOption) (*stripe.EntitlementsFeature, error)

CreateProductFeatureWithOptions creates a product feature using functional options

func (*StripeClient) CreateProductWithParams added in v0.20.0

func (sc *StripeClient) CreateProductWithParams(ctx context.Context, params *stripe.ProductCreateParams) (*stripe.Product, error)

CreateProductWithParams creates a product in Stripe with the given parameters

func (*StripeClient) CreateSubscription

func (sc *StripeClient) CreateSubscription(ctx context.Context, params *stripe.SubscriptionCreateParams) (*stripe.Subscription, error)

CreateSubscription creates a new subscription

func (*StripeClient) CreateSubscriptionScheduleFromSubs added in v0.32.1

func (sc *StripeClient) CreateSubscriptionScheduleFromSubs(ctx context.Context, subscriptionID string) (*stripe.SubscriptionSchedule, error)

CreateSubscriptionScheduleFromSubs creates a subscription schedule from an existing subscription

func (*StripeClient) CreateSubscriptionWithOptions added in v0.20.0

func (sc *StripeClient) CreateSubscriptionWithOptions(ctx context.Context, baseParams *stripe.SubscriptionCreateParams, opts ...SubscriptionCreateOption) (*stripe.Subscription, error)

CreateSubscriptionWithOptions creates a subscription with functional options

func (*StripeClient) CreateSubscriptionWithPrices added in v0.23.0

func (sc *StripeClient) CreateSubscriptionWithPrices(ctx context.Context, cust *stripe.Customer, o *OrganizationCustomer) (*Subscription, error)

CreateSubscriptionWithPrices creates a subscription using the provided prices

func (*StripeClient) CreateWebhookEndpoint added in v0.20.0

func (sc *StripeClient) CreateWebhookEndpoint(ctx context.Context, url string, events []string, apiVersion string, disabled bool) (*stripe.WebhookEndpoint, error)

CreateWebhookEndpoint creates a webhook endpoint in Stripe and returns the resulting webhook endpoint

func (*StripeClient) DeleteCustomer

func (sc *StripeClient) DeleteCustomer(ctx context.Context, id string) error

DeleteCustomer deletes a customer by ID from stripe

func (*StripeClient) DeleteProduct added in v0.8.9

func (sc *StripeClient) DeleteProduct(ctx context.Context, productID string) (*stripe.Product, error)

DeleteProduct deletes a product in Stripe

func (*StripeClient) DeleteWebhookEndpoint added in v0.43.4

func (sc *StripeClient) DeleteWebhookEndpoint(ctx context.Context, id string) (*stripe.WebhookEndpoint, error)

DeleteWebhookEndpoint deletes a webhook endpoint in Stripe

func (*StripeClient) DisableWebhookByVersion added in v0.43.4

func (sc *StripeClient) DisableWebhookByVersion(ctx context.Context, baseURL string, apiVersion string) (*stripe.WebhookEndpoint, error)

DisableWebhookByVersion disables the webhook endpoint matching the specified API version

func (*StripeClient) DisableWebhookEndpoint added in v0.43.4

func (sc *StripeClient) DisableWebhookEndpoint(ctx context.Context, id string) (*stripe.WebhookEndpoint, error)

DisableWebhookEndpoint disables a webhook endpoint in Stripe

func (*StripeClient) EnableNewWebhook added in v0.43.4

func (sc *StripeClient) EnableNewWebhook(ctx context.Context, baseURL string, opts ...WebhookMigrationOption) (*stripe.WebhookEndpoint, error)

EnableNewWebhook enables the new webhook endpoint to begin dual processing

func (*StripeClient) EnableWebhookEndpoint added in v0.43.4

func (sc *StripeClient) EnableWebhookEndpoint(ctx context.Context, id string) (*stripe.WebhookEndpoint, error)

EnableWebhookEndpoint enables a webhook endpoint in Stripe

func (*StripeClient) FindAndDeactivateCustomerSubscription added in v0.10.11

func (sc *StripeClient) FindAndDeactivateCustomerSubscription(ctx context.Context, customerID string) error

FindAndDeactivateCustomerSubscription finds a customer by the organization ID and deactivates their subscription this is used when an organization is deleted - we retain the customer record and keep a referenced to the deactivated subscription we do not delete the customer record in stripe for record / references we also do not delete the subscription record in stripe for record / references this will cancel the subscription immediately, because the organization is being deleted and should not retain access

func (*StripeClient) FindOrCreateCustomer added in v0.6.7

func (sc *StripeClient) FindOrCreateCustomer(ctx context.Context, o *OrganizationCustomer) error

FindOrCreateCustomer attempts to lookup a customer by the organization ID which is set in both the name field attribute as well as in the object metadata field

func (*StripeClient) FindPriceForProduct added in v0.20.0

func (sc *StripeClient) FindPriceForProduct(ctx context.Context, productID, priceID string, unitAmount int64, currency, interval, nickname, lookupKey string, metadata map[string]string) (*stripe.Price, error)

FindPriceForProduct searches existing prices for a matching interval, amount and optional metadata. It prefers locating by price ID or lookup key before falling back to attribute matching within the specified product.

func (*StripeClient) FindProductByID added in v0.28.0

func (sc *StripeClient) FindProductByID(ctx context.Context, id string) (*stripe.Product, error)

FindProductByID retrieves a product directly by its ID from Stripe It returns the product or nil if not found

func (*StripeClient) FindProductByName added in v0.23.0

func (sc *StripeClient) FindProductByName(ctx context.Context, name string) (*stripe.Product, error)

FindProductByName searches for a product in Stripe matching the provided name It returns the first product found or nil when none match

func (*StripeClient) GetAllProductPricesMapped added in v0.8.9

func (sc *StripeClient) GetAllProductPricesMapped(ctx context.Context) (products []Product)

GetAllProductPricesMapped retrieves all products and prices from stripe which are active

func (*StripeClient) GetCustomerByStripeID added in v0.5.0

func (sc *StripeClient) GetCustomerByStripeID(ctx context.Context, customerID string) (*stripe.Customer, error)

GetCustomerByStripeID gets a customer by ID

func (*StripeClient) GetFeatureByLookupKey added in v0.23.0

func (sc *StripeClient) GetFeatureByLookupKey(ctx context.Context, lookupKey string) (*stripe.EntitlementsFeature, error)

GetFeatureByLookupKey retrieves the first entitlements feature matching the lookup key.

func (*StripeClient) GetFeaturesByProductID added in v0.8.9

func (sc *StripeClient) GetFeaturesByProductID(ctx context.Context, productID string) []ProductFeature

GetFeaturesByProductID retrieves all product features from stripe which are active and maps them into a []ProductFeature struct

func (*StripeClient) GetPrice added in v0.8.9

func (sc *StripeClient) GetPrice(ctx context.Context, priceID string) (*stripe.Price, error)

GetPrice retrieves a price from stripe by its ID

func (*StripeClient) GetPriceByLookupKey added in v0.20.0

func (sc *StripeClient) GetPriceByLookupKey(ctx context.Context, lookupKey string) (*stripe.Price, error)

GetPriceByLookupKey returns the first price matching the provided lookup key.

func (*StripeClient) GetPricesMapped added in v0.8.9

func (sc *StripeClient) GetPricesMapped(ctx context.Context) (prices []Price)

GetPricesMapped retrieves all prices from stripe which are active and maps them into a []Price struct

func (*StripeClient) GetProduct added in v0.8.9

func (sc *StripeClient) GetProduct(ctx context.Context, productID string) (*stripe.Product, error)

GetProduct retrieves a product by its ID

func (*StripeClient) GetProductByID added in v0.6.7

func (sc *StripeClient) GetProductByID(ctx context.Context, id string) (*stripe.Product, error)

GetProductByID gets a product by ID

func (*StripeClient) GetSubscriptionByID

func (sc *StripeClient) GetSubscriptionByID(ctx context.Context, id string) (*stripe.Subscription, error)

GetSubscriptionByID gets a subscription by ID

func (*StripeClient) GetWebhookEndpoint added in v0.43.4

func (sc *StripeClient) GetWebhookEndpoint(ctx context.Context, id string) (*stripe.WebhookEndpoint, error)

GetWebhookEndpoint retrieves a webhook endpoint by ID from Stripe

func (*StripeClient) GetWebhookMigrationState added in v0.43.4

func (sc *StripeClient) GetWebhookMigrationState(ctx context.Context, baseURL string, opts ...WebhookMigrationOption) (*WebhookMigrationState, error)

GetWebhookMigrationState analyzes the current webhook configuration and returns migration state

func (*StripeClient) ListPrices added in v0.8.9

func (sc *StripeClient) ListPrices(ctx context.Context) ([]*stripe.Price, error)

ListPrices retrieves all prices from stripe

func (*StripeClient) ListPricesForProduct added in v0.20.0

func (sc *StripeClient) ListPricesForProduct(ctx context.Context, productID string) ([]*stripe.Price, error)

ListPricesForProduct returns all prices for a given product

func (*StripeClient) ListProductFeatures added in v0.20.0

func (sc *StripeClient) ListProductFeatures(ctx context.Context, productID string) ([]*stripe.ProductFeature, error)

ListProductFeatures lists all product features for a product

func (*StripeClient) ListProducts added in v0.8.9

func (sc *StripeClient) ListProducts(ctx context.Context) (products []*stripe.Product, err error)

ListProducts lists all products in Stripe

func (*StripeClient) ListSubscriptions added in v0.20.0

func (sc *StripeClient) ListSubscriptions(ctx context.Context, customerID string) ([]*stripe.Subscription, error)

ListSubscriptions retrieves all subscriptions for the given customer without creating new ones

func (*StripeClient) ListWebhookEndpoints added in v0.43.4

func (sc *StripeClient) ListWebhookEndpoints(ctx context.Context) ([]*stripe.WebhookEndpoint, error)

ListWebhookEndpoints lists all webhook endpoints in Stripe

func (*StripeClient) MapStripeSubscription added in v0.7.4

func (sc *StripeClient) MapStripeSubscription(ctx context.Context, subs *stripe.Subscription, sched *stripe.SubscriptionSchedule) *Subscription

MapStripeSubscription maps a stripe.Subscription to a "internal" subscription struct

func (*StripeClient) MigrateSubscriptionPrice added in v0.20.0

func (sc *StripeClient) MigrateSubscriptionPrice(ctx context.Context, sub *stripe.Subscription, oldPriceID, newPriceID string) (*stripe.Subscription, error)

MigrateSubscriptionPrice replaces occurrences of oldPriceID with newPriceID on the subscription Don't run unless you know what you're doing!

func (*StripeClient) RollbackMigration added in v0.43.4

func (sc *StripeClient) RollbackMigration(ctx context.Context, baseURL string, opts ...WebhookMigrationOption) error

RollbackMigration rolls back the migration by disabling the new webhook and re-enabling the old one

func (*StripeClient) SearchCustomers added in v0.5.0

func (sc *StripeClient) SearchCustomers(ctx context.Context, query string) (customers []*stripe.Customer, err error)

SearchCustomers searches for customers with a structured stripe query as input leverage QueryBuilder to construct more complex queries, otherwise see: https://docs.stripe.com/search#search-query-language

func (*StripeClient) TagPriceMigration added in v0.20.0

func (sc *StripeClient) TagPriceMigration(ctx context.Context, fromPriceID, toPriceID string) error

TagPriceMigration annotates a price in preparation for migration to a new price

func (*StripeClient) TagPriceUpsell added in v0.23.0

func (sc *StripeClient) TagPriceUpsell(ctx context.Context, fromPriceID, toPriceID string) error

TagPriceUpsell annotates a price so that consumers can upsell to a new price.

func (*StripeClient) UpdateCustomer

func (sc *StripeClient) UpdateCustomer(ctx context.Context, id string, params *stripe.CustomerUpdateParams) (*stripe.Customer, error)

UpdateCustomer updates a customer in stripe with the provided params and ID

func (*StripeClient) UpdateCustomerWithOptions added in v0.20.0

func (sc *StripeClient) UpdateCustomerWithOptions(baseParams *stripe.CustomerUpdateParams, opts ...CustomerUpdateOption) *stripe.CustomerUpdateParams

UpdateCustomerWithOptions creates update params with functional options

func (*StripeClient) UpdateFeatureWithOptions added in v0.20.0

UpdateFeatureWithOptions creates update params with functional options

func (*StripeClient) UpdatePriceMetadata added in v0.20.0

func (sc *StripeClient) UpdatePriceMetadata(ctx context.Context, priceID string, metadata map[string]string) (*stripe.Price, error)

UpdatePriceMetadata updates the metadata for a price

func (*StripeClient) UpdatePriceWithOptions added in v0.20.0

func (sc *StripeClient) UpdatePriceWithOptions(baseParams *stripe.PriceUpdateParams, opts ...PriceUpdateOption) *stripe.PriceUpdateParams

UpdatePriceWithOptions creates update params with functional options

func (*StripeClient) UpdateProduct added in v0.8.9

func (sc *StripeClient) UpdateProduct(ctx context.Context, productID, name, description string) (*stripe.Product, error)

UpdateProduct updates a product in Stripe

func (*StripeClient) UpdateProductFeatureWithOptions added in v0.20.0

func (sc *StripeClient) UpdateProductFeatureWithOptions(ctx context.Context, featureID string, baseParams *stripe.EntitlementsFeatureUpdateParams, opts ...FeatureUpdateOption) (*stripe.EntitlementsFeature, error)

UpdateProductFeatureWithOptions updates a product feature using functional options

func (*StripeClient) UpdateProductWithOptions added in v0.20.0

func (sc *StripeClient) UpdateProductWithOptions(baseParams *stripe.ProductUpdateParams, opts ...ProductUpdateOption) *stripe.ProductUpdateParams

UpdateProductWithOptions creates update params with functional options

func (*StripeClient) UpdateProductWithParams added in v0.20.0

func (sc *StripeClient) UpdateProductWithParams(ctx context.Context, productID string, params *stripe.ProductUpdateParams) (*stripe.Product, error)

UpdateProductWithParams updates a product in Stripe with the given parameters

func (*StripeClient) UpdateSubscription

func (sc *StripeClient) UpdateSubscription(ctx context.Context, id string, params *stripe.SubscriptionUpdateParams) (*stripe.Subscription, error)

UpdateSubscription updates a subscription

func (*StripeClient) UpdateSubscriptionWithOptions added in v0.20.0

func (sc *StripeClient) UpdateSubscriptionWithOptions(ctx context.Context, id string, baseParams *stripe.SubscriptionUpdateParams, opts ...SubscriptionUpdateOption) (*stripe.Subscription, error)

UpdateSubscriptionWithOptions updates a subscription with functional options

func (*StripeClient) UpdateWebhookEndpoint added in v0.43.4

func (sc *StripeClient) UpdateWebhookEndpoint(ctx context.Context, id string, params *stripe.WebhookEndpointUpdateParams) (*stripe.WebhookEndpoint, error)

UpdateWebhookEndpoint updates a webhook endpoint in Stripe

type StripeOptions

type StripeOptions func(*StripeClient)

StripeOptions is a type for setting options on the Stripe client

func WithAPIKey

func WithAPIKey(apiKey string) StripeOptions

WithAPIKey sets the API key for the Stripe client

func WithBackends added in v0.7.4

func WithBackends(backends *stripe.Backends) StripeOptions

WithBackends sets the backends for the Stripe client

func WithConfig added in v0.5.0

func WithConfig(config Config) StripeOptions

WithConfig sets the config for the Stripe client

type Subscription

type Subscription struct {
	ID                           string `json:"plan_id" yaml:"plan_id"`
	ProductID                    string `json:"product_id" yaml:"product_id"`
	PriceID                      string `json:"price_id" yaml:"price_id"`
	StartDate                    int64  `json:"start_date" yaml:"start_date"`
	EndDate                      int64  `json:"end_date" yaml:"end_date"`
	Features                     []Feature
	Prices                       []Price
	TrialEnd                     int64
	Status                       string
	StripeCustomerID             string
	OrganizationID               string
	StripeSubscriptionScheduleID string
	DaysUntilDue                 int64
	Metadata                     map[string]string
}

Subscription is the recurring context that holds the payment information

type SubscriptionCreateOption added in v0.20.0

type SubscriptionCreateOption func(params *stripe.SubscriptionCreateParams)

SubscriptionCreateOption allows customizing SubscriptionCreateParams

func WithSubscriptionItems added in v0.20.0

func WithSubscriptionItems(items ...*stripe.SubscriptionCreateItemParams) SubscriptionCreateOption

WithSubscriptionItems allows adding multiple items to the subscription creation params

type SubscriptionUpdateOption added in v0.20.0

type SubscriptionUpdateOption func(params *stripe.SubscriptionUpdateParams)

SubscriptionUpdateOption allows customizing SubscriptionUpdateParams

func WithUpdateSubscriptionItems added in v0.20.0

func WithUpdateSubscriptionItems(newItems ...*stripe.SubscriptionUpdateItemParams) SubscriptionUpdateOption

WithUpdateSubscriptionItems allows adding multiple items to the subscription update params

type TupleChecker added in v0.20.0

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

TupleChecker provides methods to create/check tuples with Redis cache fallback to FGA.

func NewTupleChecker added in v0.20.0

func NewTupleChecker(opts ...TupleCheckerOption) *TupleChecker

NewTupleChecker creates a new TupleChecker with options

func (*TupleChecker) CheckFeatureTuple added in v0.20.0

func (tc *TupleChecker) CheckFeatureTuple(ctx context.Context, tuple FeatureTuple) (bool, error)

CheckFeatureTuple checks if a tuple exists, using Redis cache first, then FGA

func (*TupleChecker) CreateFeatureTuple added in v0.20.0

func (tc *TupleChecker) CreateFeatureTuple(ctx context.Context, tuple FeatureTuple) error

CreateFeatureTuple creates a tuple in FGA and updates the cache

func (*TupleChecker) DeleteFeatureTuple added in v0.20.0

func (tc *TupleChecker) DeleteFeatureTuple(ctx context.Context, tuple FeatureTuple) error

DeleteFeatureTuple deletes a tuple in FGA and removes it from the cache

type TupleCheckerOption added in v0.20.0

type TupleCheckerOption func(*TupleChecker)

TupleCheckerOption allows functional options for TupleChecker.

func WithCacheTTL added in v0.20.0

func WithCacheTTL(ttl time.Duration) TupleCheckerOption

WithCacheTTL sets the cache TTL for TupleChecker

func WithFGAClient added in v0.20.0

func WithFGAClient(client FGAClient) TupleCheckerOption

WithFGAClient sets a custom FGA client

func WithRedisClient added in v0.20.0

func WithRedisClient(client *redis.Client) TupleCheckerOption

WithRedisClient sets a custom Redis client

type WebhookMigrationOption added in v0.43.4

type WebhookMigrationOption func(*webhookMigrationOptions)

WebhookMigrationOption is a functional option for GetWebhookMigrationState

func WithCurrentVersion added in v0.43.4

func WithCurrentVersion(version string) WebhookMigrationOption

WithCurrentVersion sets the current API version from config

type WebhookMigrationState added in v0.43.4

type WebhookMigrationState struct {
	OldWebhook        *stripe.WebhookEndpoint
	NewWebhook        *stripe.WebhookEndpoint
	CurrentSDKVersion string
	CanMigrate        bool
	MigrationStage    string
}

WebhookMigrationState represents the current state of webhook migration

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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