stripe

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EventUserCreated is published when a new user is created in the application.
	EventUserCreated = "auth:user:created"

	// EventStripeCustomerCreated is published when a new Stripe customer is created and linked.
	EventStripeCustomerCreated = "stripe:customer:created"

	// EventStripeSubscriptionCreated is published when a subscription is successfully created.
	EventStripeSubscriptionCreated = "stripe:subscription:created"

	// EventStripeSubscriptionUpdated is published when a subscription state, tier, or period updates.
	EventStripeSubscriptionUpdated = "stripe:subscription:updated"

	// EventStripeSubscriptionDeleted is published when a subscription is canceled or deleted.
	EventStripeSubscriptionDeleted = "stripe:subscription:deleted"

	// EventStripeInvoicePaymentSucceeded is published when an invoice payment succeeds.
	EventStripeInvoicePaymentSucceeded = "stripe:invoice:payment_succeeded"

	// EventStripeInvoicePaymentFailed is published when an invoice payment attempt fails.
	EventStripeInvoicePaymentFailed = "stripe:invoice:payment_failed"

	// EventStripeWebhookReceived is published upon successfully receiving and verifying a webhook event.
	EventStripeWebhookReceived = "stripe:webhook:received"
)
View Source
const (
	MetadataKeyReferenceID    = "referenceId"
	MetadataKeyEntityType     = "entityType"
	MetadataKeyUserID         = "userId"
	MetadataKeyOrganizationID = "organizationId"
)
View Source
const (
	ReferenceIDContextKey  contextKey = "stripe:reference_id"
	SubscriptionContextKey contextKey = "stripe:subscription"
)
View Source
const PluginID = "stripe"

PluginID is the unique string identifier for the Stripe plugin ("stripe").

Variables

View Source
var (
	// ErrRepositoryRequired is returned when no Repository implementation is provided.
	ErrRepositoryRequired = errors.New("stripe: repository is required")

	// ErrStripeAPIKeyRequired is returned when no Stripe secret API key is configured.
	ErrStripeAPIKeyRequired = errors.New("stripe: stripe API key is required")

	// ErrSubscriptionNotFound is returned when a subscription record cannot be located.
	ErrSubscriptionNotFound = errors.New("stripe: subscription not found")

	// ErrCustomerNotFound is returned when no Stripe Customer ID is linked to an entity.
	ErrCustomerNotFound = errors.New("stripe: customer not found")

	// ErrInvalidWebhookSignature is returned when a Stripe webhook signature fails verification.
	ErrInvalidWebhookSignature = errors.New("stripe: invalid webhook signature")

	// ErrUnauthorizedReference is returned when a user lacks authorization over a referenceId.
	ErrUnauthorizedReference = errors.New("stripe: unauthorized reference access")

	// ErrInvalidPlan is returned when an unrecognized or missing plan ID is specified.
	ErrInvalidPlan = errors.New("stripe: invalid plan specified")
)

Functions

func BuildMetadata

func BuildMetadata(referenceID, entityType string, customMeta map[string]string) map[string]string

BuildMetadata creates a safe map of metadata key-value pairs for Stripe entities, preserving reserved fields.

func EscapeStripeSearchValue

func EscapeStripeSearchValue(val string) string

EscapeStripeSearchValue safely escapes special characters for Stripe Search API queries.

func ExtractReferenceID

func ExtractReferenceID(meta map[string]string) (string, string, bool)

ExtractReferenceID extracts referenceId and entityType from Stripe metadata maps.

func IsActiveOrTrialing

func IsActiveOrTrialing(sub *Subscription) bool

IsActiveOrTrialing returns true if the subscription is currently active or trialing.

func ReferenceIDFromContext

func ReferenceIDFromContext(ctx context.Context) (string, bool)

ReferenceIDFromContext retrieves the referenceId injected into the request Context by middleware.

Types

type AuthorizeReferenceData

type AuthorizeReferenceData struct {
	ReferenceID    string `json:"reference_id"`
	UserID         string `json:"user_id,omitempty"`
	OrganizationID string `json:"organization_id,omitempty"`
	Action         string `json:"action"`
}

AuthorizeReferenceData represents context passed to the AuthorizeReference callback for access control.

type AuthorizeReferenceFunc

type AuthorizeReferenceFunc func(ctx context.Context, data AuthorizeReferenceData) (bool, error)

Callback type definitions for lifecycle extension points.

type BillingPortalParams

type BillingPortalParams struct {
	StripeCustomerID string `json:"stripe_customer_id"`
	ReturnURL        string `json:"return_url"`
}

BillingPortalParams holds parameters for generating a Stripe Customer Billing Portal session URL.

type CancelSubscriptionParams

type CancelSubscriptionParams struct {
	SubscriptionID    string `json:"subscription_id"`
	CancelAtPeriodEnd bool   `json:"cancel_at_period_end"`
}

CancelSubscriptionParams holds parameters for canceling a subscription.

type Config

type Config struct {
	// StripeAPIKey is the secret API key used to initialize the Stripe API client (e.g. "sk_test_...").
	StripeAPIKey string

	// WebhookSecret is the secret used to cryptographically verify incoming Stripe-Signature headers.
	WebhookSecret string

	// CreateCustomerOnSignUp automatically creates a Stripe Customer record when a new user registers.
	CreateCustomerOnSignUp bool

	// Subscription contains configuration options for subscription billing.
	Subscription *SubscriptionOptions

	// Organization contains configuration options for organization seat-based billing.
	Organization *OrganizationOptions
}

Config holds operational settings and options for the Stripe plugin.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns recommended production default settings for the Stripe plugin.

type CreateCheckoutParams

type CreateCheckoutParams struct {
	ReferenceID   string            `json:"reference_id"`
	PlanID        string            `json:"plan_id"`
	SuccessURL    string            `json:"success_url"`
	CancelURL     string            `json:"cancel_url"`
	CustomerEmail string            `json:"customer_email,omitempty"`
	Seats         int               `json:"seats,omitempty"`
	TrialDays     int               `json:"trial_days,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`
}

CreateCheckoutParams holds parameters for initiating a Stripe Checkout session.

type CustomerCreatedPayload

type CustomerCreatedPayload struct {
	EntityType       string `json:"entity_type"` // "user" or "organization"
	EntityID         string `json:"entity_id"`
	StripeCustomerID string `json:"stripe_customer_id"`
	Email            string `json:"email,omitempty"`
}

CustomerCreatedPayload represents the EventBus payload for EventStripeCustomerCreated.

type InvoiceCallbackFunc

type InvoiceCallbackFunc func(ctx context.Context, inv *InvoiceData) error

type InvoiceData

type InvoiceData struct {
	InvoiceID            string    `json:"invoice_id"`
	StripeCustomerID     string    `json:"stripe_customer_id"`
	StripeSubscriptionID string    `json:"stripe_subscription_id"`
	AmountPaid           int64     `json:"amount_paid"`
	Currency             string    `json:"currency"`
	Status               string    `json:"status"`
	PaidAt               time.Time `json:"paid_at"`
}

InvoiceData holds parsed payment details extracted from invoice webhooks.

type InvoiceEventPayload

type InvoiceEventPayload struct {
	Invoice       *InvoiceData `json:"invoice"`
	StripeEventID string       `json:"stripe_event_id,omitempty"`
	EventType     string       `json:"event_type"`
}

InvoiceEventPayload represents the EventBus payload for invoice payment events.

type MemoryRepository

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

MemoryRepository provides a thread-safe, in-memory implementation of Repository for testing and lightweight usage.

func NewMemoryRepository

func NewMemoryRepository() *MemoryRepository

NewMemoryRepository initializes a fresh MemoryRepository instance.

func (*MemoryRepository) CreateSubscription

func (r *MemoryRepository) CreateSubscription(_ context.Context, sub *Subscription) error

CreateSubscription persists a new subscription entity in memory.

func (*MemoryRepository) DeleteSubscription

func (r *MemoryRepository) DeleteSubscription(_ context.Context, id string) error

DeleteSubscription removes an in-memory subscription entity by ID.

func (*MemoryRepository) FindSubscriptionByID

func (r *MemoryRepository) FindSubscriptionByID(_ context.Context, id string) (*Subscription, error)

FindSubscriptionByID retrieves an in-memory subscription by local ID.

func (*MemoryRepository) FindSubscriptionByStripeID

func (r *MemoryRepository) FindSubscriptionByStripeID(_ context.Context, stripeSubID string) (*Subscription, error)

FindSubscriptionByStripeID retrieves an in-memory subscription by remote Stripe ID.

func (*MemoryRepository) GetCustomerStripeID

func (r *MemoryRepository) GetCustomerStripeID(_ context.Context, entityType, entityID string) (string, error)

GetCustomerStripeID retrieves the Stripe Customer ID linked to an entity in memory.

func (*MemoryRepository) ListSubscriptionsByReferenceID

func (r *MemoryRepository) ListSubscriptionsByReferenceID(_ context.Context, referenceID string) ([]*Subscription, error)

ListSubscriptionsByReferenceID retrieves all in-memory subscriptions linked to a referenceId.

func (*MemoryRepository) SaveCustomerStripeID

func (r *MemoryRepository) SaveCustomerStripeID(_ context.Context, entityType, entityID, stripeCustomerID string) error

SaveCustomerStripeID persists the entity-to-Stripe Customer ID mapping in memory.

func (*MemoryRepository) UpdateSubscription

func (r *MemoryRepository) UpdateSubscription(_ context.Context, sub *Subscription) error

UpdateSubscription updates an existing in-memory subscription entity.

type Option

type Option func(*Config)

Option represents a functional configuration option for configuring the Stripe plugin.

func WithAuthorizeReference

func WithAuthorizeReference(fn AuthorizeReferenceFunc) Option

WithAuthorizeReference configures a callback to authorize referenceId access during subscription actions.

func WithCreateCustomerOnSignUp

func WithCreateCustomerOnSignUp(enable bool) Option

WithCreateCustomerOnSignUp toggles automatic creation of a Stripe customer record during sign-up.

func WithOnInvoicePaymentFailed

func WithOnInvoicePaymentFailed(fn InvoiceCallbackFunc) Option

WithOnInvoicePaymentFailed registers a callback triggered when an invoice payment fails.

func WithOnInvoicePaymentSucceeded

func WithOnInvoicePaymentSucceeded(fn InvoiceCallbackFunc) Option

WithOnInvoicePaymentSucceeded registers a callback triggered when an invoice payment succeeds.

func WithOnSubscriptionCreated

func WithOnSubscriptionCreated(fn SubscriptionCallbackFunc) Option

WithOnSubscriptionCreated registers a callback triggered when a subscription is created.

func WithOnSubscriptionDeleted

func WithOnSubscriptionDeleted(fn SubscriptionCallbackFunc) Option

WithOnSubscriptionDeleted registers a callback triggered when a subscription is canceled or deleted.

func WithOnSubscriptionUpdated

func WithOnSubscriptionUpdated(fn SubscriptionCallbackFunc) Option

WithOnSubscriptionUpdated registers a callback triggered when a subscription state updates.

func WithPlans

func WithPlans(plans ...StripePlan) Option

WithPlans defines static subscription plans available in the application.

func WithPlansFunc

func WithPlansFunc(fn PlansFunc) Option

WithPlansFunc sets a dynamic function for resolving available subscription plans.

func WithSeatPriceID

func WithSeatPriceID(seatPriceID string) Option

WithSeatPriceID configures organization seat-based billing with a specific Stripe Seat Price ID.

func WithStripeAPIKey

func WithStripeAPIKey(key string) Option

WithStripeAPIKey sets the Stripe secret API key.

func WithWebhookSecret

func WithWebhookSecret(secret string) Option

WithWebhookSecret sets the webhook secret key for verifying Stripe-Signature HTTP headers.

type OrganizationOptions

type OrganizationOptions struct {
	Enabled     bool
	SeatPriceID string
}

OrganizationOptions holds options for organization-level seat-based billing.

type PlansFunc

type PlansFunc func(ctx context.Context) ([]StripePlan, error)

type Plugin

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

Plugin implements the Stripe billing, subscription, and webhook integration plugin for go-modular-auth.

func New

func New(repo Repository, opts ...Option) (*Plugin, error)

New instantiates a new Stripe plugin configured with a mandatory Repository implementation and functional options.

func (*Plugin) AuthorizeReference

func (p *Plugin) AuthorizeReference(action string) func(http.Handler) http.Handler

AuthorizeReference returns a net/http middleware that executes the configured AuthorizeReference callback to verify if the session user is permitted to perform the given action on a referenceId.

func (*Plugin) CancelSubscription

func (p *Plugin) CancelSubscription(ctx context.Context, params CancelSubscriptionParams) (*Subscription, error)

CancelSubscription cancels a subscription either immediately or at period end.

func (*Plugin) Config

func (p *Plugin) Config() Config

Config returns a copy of the active plugin configuration.

func (*Plugin) CreateBillingPortalSession

func (p *Plugin) CreateBillingPortalSession(ctx context.Context, params BillingPortalParams) (string, error)

CreateBillingPortalSession creates a new Stripe Customer Billing Portal session URL.

func (*Plugin) CreateCheckoutSession

func (p *Plugin) CreateCheckoutSession(ctx context.Context, params CreateCheckoutParams) (string, error)

CreateCheckoutSession creates a new Stripe Checkout Session URL for subscription purchase.

func (*Plugin) GetSubscription

func (p *Plugin) GetSubscription(ctx context.Context, subID string) (*Subscription, error)

GetSubscription retrieves a local subscription record by ID.

func (*Plugin) HandleWebhook

func (p *Plugin) HandleWebhook(w http.ResponseWriter, r *http.Request)

HandleWebhook is a net/http handler function that reads the raw HTTP request body, extracts the Stripe-Signature header, and delegates processing to ProcessWebhook.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique string identifier for the plugin ("stripe").

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin with the shared execution context.

func (*Plugin) ListSubscriptions

func (p *Plugin) ListSubscriptions(ctx context.Context, referenceID string) ([]*Subscription, error)

ListSubscriptions retrieves all subscriptions linked to a referenceId.

func (*Plugin) OnUserCreated added in v0.26.0

func (p *Plugin) OnUserCreated(ctx context.Context, user *entity.User) error

OnUserCreated triggers customer creation in Stripe for a newly registered user and persists the stripeCustomerID.

func (*Plugin) ProcessWebhook

func (p *Plugin) ProcessWebhook(ctx context.Context, payload []byte, signature string) error

ProcessWebhook parses raw body bytes, verifies the Stripe-Signature cryptographic header, and processes supported event types (Checkout sessions, Subscriptions, Invoices).

func (*Plugin) RequireActiveSubscription

func (p *Plugin) RequireActiveSubscription(allowedPlans ...string) func(http.Handler) http.Handler

RequireActiveSubscription returns a net/http middleware that enforces that the requesting entity (user or organization referenceId) possesses an active or trialing subscription. Optional allowedPlans filter restricts access strictly to specified plan IDs.

func (*Plugin) RestoreSubscription

func (p *Plugin) RestoreSubscription(ctx context.Context, subID string) (*Subscription, error)

RestoreSubscription revokes a scheduled cancellation at period end.

func (*Plugin) SyncSeats

func (p *Plugin) SyncSeats(ctx context.Context, referenceID string, seats int) error

SyncSeats updates the seat count quantity in Stripe for an active subscription linked to a referenceId.

func (*Plugin) UpgradeSubscription

func (p *Plugin) UpgradeSubscription(ctx context.Context, params UpgradeSubscriptionParams) (*Subscription, error)

UpgradeSubscription updates an existing subscription to a new plan or seat count.

func (*Plugin) WebhookHandler

func (p *Plugin) WebhookHandler() http.Handler

WebhookHandler returns a net/http Handler ready for mounting in any standard Go HTTP router or server.

type Repository

type Repository interface {
	// CreateSubscription persists a new local subscription record linked to Stripe.
	//
	// Function:
	//   Called when a new subscription is provisioned via Checkout or Webhooks.
	//
	// Storage:
	//   Database (GORM / SQL) - Inserts a new row into stripe_subscriptions table.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - sub: Subscription entity to persist.
	//
	// Returns:
	//   - error: Nil on success, or database error on failure.
	//
	// Example SQL:
	//   INSERT INTO stripe_subscriptions (id, plan, reference_id, stripe_customer_id, stripe_subscription_id, status, period_start, period_end, cancel_at_period_end, seats, billing_interval, created_at, updated_at)
	//   VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);
	CreateSubscription(ctx context.Context, sub *Subscription) error

	// UpdateSubscription updates an existing local subscription record.
	//
	// Function:
	//   Called when subscription status, current period, or seats change via webhook or API.
	//
	// Storage:
	//   Database (GORM / SQL) - Updates fields matching subscription primary key ID.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - sub: Subscription entity with updated fields.
	//
	// Returns:
	//   - error: ErrSubscriptionNotFound if missing, or database error on failure.
	//
	// Example SQL:
	//   UPDATE stripe_subscriptions SET status = $1, period_end = $2, seats = $3, updated_at = NOW() WHERE id = $4;
	UpdateSubscription(ctx context.Context, sub *Subscription) error

	// DeleteSubscription removes a subscription record from storage by local ID.
	//
	// Function:
	//   Called when revoking or permanently deleting a subscription record.
	//
	// Storage:
	//   Database (GORM / SQL) - Deletes row matching local ID.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - id: Local subscription primary key ID.
	//
	// Returns:
	//   - error: ErrSubscriptionNotFound if missing, or database error.
	//
	// Example SQL:
	//   DELETE FROM stripe_subscriptions WHERE id = $1;
	DeleteSubscription(ctx context.Context, id string) error

	// FindSubscriptionByID retrieves a subscription by local primary key ID.
	//
	// Function:
	//   Used in subscription retrieval and cancellation operations.
	//
	// Storage:
	//   Database (GORM / SQL) - Primary key lookup on stripe_subscriptions.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - id: Local subscription primary key ID.
	//
	// Returns:
	//   - *Subscription: Matching subscription record if found.
	//   - error: ErrSubscriptionNotFound if missing, or database error.
	//
	// Example SQL:
	//   SELECT id, plan, reference_id, stripe_customer_id, stripe_subscription_id, status FROM stripe_subscriptions WHERE id = $1 LIMIT 1;
	FindSubscriptionByID(ctx context.Context, id string) (*Subscription, error)

	// FindSubscriptionByStripeID retrieves a subscription by its Stripe-assigned subscription ID.
	//
	// Function:
	//   Used in webhook processing to locate local subscription records matching incoming Stripe events.
	//
	// Storage:
	//   Database (GORM / SQL) - Query by stripe_subscription_id column index.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - stripeSubID: Remote Stripe subscription ID string (e.g. "sub_12345").
	//
	// Returns:
	//   - *Subscription: Matching subscription record if found.
	//   - error: ErrSubscriptionNotFound if missing, or database error.
	//
	// Example SQL:
	//   SELECT id, plan, reference_id, stripe_customer_id, stripe_subscription_id, status FROM stripe_subscriptions WHERE stripe_subscription_id = $1 LIMIT 1;
	FindSubscriptionByStripeID(ctx context.Context, stripeSubID string) (*Subscription, error)

	// ListSubscriptionsByReferenceID retrieves all subscriptions linked to a referenceId (user or organization).
	//
	// Function:
	//   Used by middlewares and service APIs to evaluate active access rights for a user or team.
	//
	// Storage:
	//   Database (GORM / SQL) - Query stripe_subscriptions by reference_id column.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - referenceID: User ID or Organization ID string.
	//
	// Returns:
	//   - []*Subscription: Slice of matching subscription records.
	//   - error: Nil on success, or database error.
	//
	// Example SQL:
	//   SELECT id, plan, reference_id, stripe_customer_id, stripe_subscription_id, status FROM stripe_subscriptions WHERE reference_id = $1;
	ListSubscriptionsByReferenceID(ctx context.Context, referenceID string) ([]*Subscription, error)

	// GetCustomerStripeID retrieves the Stripe Customer ID linked to an entity.
	//
	// Function:
	//   Used during customer billing portal session creation or customer lookup.
	//
	// Storage:
	//   Database (GORM / SQL) - Query stripe_customers by entity_type and entity_id.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - entityType: "user" or "organization".
	//   - entityID: Target user or organization primary key ID.
	//
	// Returns:
	//   - string: Remote Stripe Customer ID (e.g. "cus_12345").
	//   - error: ErrCustomerNotFound if missing, or database error.
	//
	// Example SQL:
	//   SELECT stripe_customer_id FROM stripe_customers WHERE entity_type = $1 AND entity_id = $2 LIMIT 1;
	GetCustomerStripeID(ctx context.Context, entityType, entityID string) (string, error)

	// SaveCustomerStripeID persists the mapping between a local entity and a Stripe Customer ID.
	//
	// Function:
	//   Called after creating a new Customer in Stripe during sign-up or onboarding.
	//
	// Storage:
	//   Database (GORM / SQL) - Upsert row into stripe_customers mapping table.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - entityType: "user" or "organization".
	//   - entityID: Local entity ID string.
	//   - stripeCustomerID: Remote Stripe Customer ID string.
	//
	// Returns:
	//   - error: Nil on success, or database error.
	//
	// Example SQL:
	//   INSERT INTO stripe_customers (entity_type, entity_id, stripe_customer_id, created_at) VALUES ($1, $2, $3, NOW())
	//   ON CONFLICT (entity_type, entity_id) DO UPDATE SET stripe_customer_id = EXCLUDED.stripe_customer_id;
	SaveCustomerStripeID(ctx context.Context, entityType, entityID, stripeCustomerID string) error
}

Repository defines the persistent storage contract required by the Stripe plugin. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM).

Implementation Example (GORM / database/sql):

type GormStripeRepository struct {
	db *gorm.DB
}

func (r *GormStripeRepository) CreateSubscription(ctx context.Context, sub *stripe.Subscription) error {
	return r.db.WithContext(ctx).Create(sub).Error
}

type StripePlan

type StripePlan struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	LookupKey   string `json:"lookup_key,omitempty"`
	PriceID     string `json:"price_id"`
	SeatPriceID string `json:"seat_price_id,omitempty"`
	Currency    string `json:"currency,omitempty"`
	Seats       int    `json:"seats,omitempty"`
	Interval    string `json:"interval,omitempty"` // "month" or "year"
}

StripePlan represents a configured pricing plan mapped to Stripe Price IDs and lookup keys.

func GetPlanByID

func GetPlanByID(cfg Config, planID string) (*StripePlan, bool)

GetPlanByID resolves a configured plan matching the given plan ID.

func GetPlanByLookupKey

func GetPlanByLookupKey(cfg Config, lookupKey string) (*StripePlan, bool)

GetPlanByLookupKey resolves a configured plan matching the given Stripe lookup key.

func GetPlanByPriceID

func GetPlanByPriceID(cfg Config, priceID string) (*StripePlan, bool)

GetPlanByPriceID resolves a configured plan matching the given Stripe Price ID.

type Subscription

type Subscription struct {
	ID                   string             `json:"id"`
	Plan                 string             `json:"plan"`
	ReferenceID          string             `json:"reference_id"`
	StripeCustomerID     string             `json:"stripe_customer_id"`
	StripeSubscriptionID string             `json:"stripe_subscription_id"`
	Status               SubscriptionStatus `json:"status"`
	PeriodStart          time.Time          `json:"period_start"`
	PeriodEnd            time.Time          `json:"period_end"`
	TrialStart           *time.Time         `json:"trial_start,omitempty"`
	TrialEnd             *time.Time         `json:"trial_end,omitempty"`
	CancelAtPeriodEnd    bool               `json:"cancel_at_period_end"`
	CancelAt             *time.Time         `json:"cancel_at,omitempty"`
	CanceledAt           *time.Time         `json:"canceled_at,omitempty"`
	EndedAt              *time.Time         `json:"ended_at,omitempty"`
	Seats                int                `json:"seats"`
	BillingInterval      string             `json:"billing_interval"`
	StripeScheduleID     string             `json:"stripe_schedule_id,omitempty"`
	CreatedAt            time.Time          `json:"created_at"`
	UpdatedAt            time.Time          `json:"updated_at"`
}

Subscription represents a persistent local record of a Stripe subscription associated with a referenceId.

func SubscriptionFromContext

func SubscriptionFromContext(ctx context.Context) (*Subscription, bool)

SubscriptionFromContext retrieves the active Subscription injected into the request Context by middleware.

type SubscriptionCallbackFunc

type SubscriptionCallbackFunc func(ctx context.Context, sub *Subscription) error

type SubscriptionEventPayload

type SubscriptionEventPayload struct {
	Subscription  *Subscription `json:"subscription"`
	StripeEventID string        `json:"stripe_event_id,omitempty"`
	EventType     string        `json:"event_type"`
}

SubscriptionEventPayload represents the EventBus payload for subscription events.

type SubscriptionOptions

type SubscriptionOptions struct {
	Plans                     []StripePlan
	PlansFunc                 PlansFunc
	RequireEmailVerification  bool
	AuthorizeReference        AuthorizeReferenceFunc
	OnSubscriptionCompleted   SubscriptionCallbackFunc
	OnSubscriptionCreated     SubscriptionCallbackFunc
	OnSubscriptionUpdated     SubscriptionCallbackFunc
	OnSubscriptionCanceled    SubscriptionCallbackFunc
	OnSubscriptionDeleted     SubscriptionCallbackFunc
	OnInvoicePaymentSucceeded InvoiceCallbackFunc
	OnInvoicePaymentFailed    InvoiceCallbackFunc
}

SubscriptionOptions holds detailed configuration rules for plans, authorization, and lifecycle callbacks.

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus represents the lifecycle state of a Stripe subscription.

const (
	StatusActive            SubscriptionStatus = "active"
	StatusCanceled          SubscriptionStatus = "canceled"
	StatusIncomplete        SubscriptionStatus = "incomplete"
	StatusIncompleteExpired SubscriptionStatus = "incomplete_expired"
	StatusPastDue           SubscriptionStatus = "past_due"
	StatusPaused            SubscriptionStatus = "paused"
	StatusTrialing          SubscriptionStatus = "trialing"
	StatusUnpaid            SubscriptionStatus = "unpaid"
)

type UpgradeSubscriptionParams

type UpgradeSubscriptionParams struct {
	SubscriptionID      string `json:"subscription_id"`
	NewPlanID           string `json:"new_plan_id"`
	Seats               int    `json:"seats,omitempty"`
	ScheduleAtPeriodEnd bool   `json:"schedule_at_period_end,omitempty"`
}

UpgradeSubscriptionParams holds parameters for upgrading or downgrading an existing subscription.

type WebhookReceivedPayload

type WebhookReceivedPayload struct {
	StripeEventID string `json:"stripe_event_id"`
	EventType     string `json:"event_type"`
	RawPayload    []byte `json:"-"`
}

WebhookReceivedPayload represents the EventBus payload for incoming validated Stripe webhooks.

Jump to

Keyboard shortcuts

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