Documentation
¶
Index ¶
- Constants
- Variables
- func IsActiveOrTrialing(sub *Subscription) bool
- func ReferenceIDFromContext(ctx context.Context) (string, bool)
- type AuthorizeReferenceData
- type AuthorizeReferenceFunc
- type BenefitCallbackFunc
- type BenefitEventPayload
- type CancelSubscriptionParams
- type Client
- type Config
- type CreateCheckoutParams
- type CustomerBenefit
- type CustomerCreatedPayload
- type CustomerMeter
- type CustomerOrder
- type CustomerPortalParams
- type CustomerState
- type CustomerStateCallbackFunc
- type CustomerStateEventPayload
- type IngestEventParams
- type IngestEventResult
- type MemoryRepository
- func (r *MemoryRepository) CreateSubscription(_ context.Context, sub *Subscription) error
- func (r *MemoryRepository) DeleteSubscription(_ context.Context, id string) error
- func (r *MemoryRepository) FindSubscriptionByID(_ context.Context, id string) (*Subscription, error)
- func (r *MemoryRepository) FindSubscriptionByPolarID(_ context.Context, polarSubID string) (*Subscription, error)
- func (r *MemoryRepository) GetCustomerPolarID(_ context.Context, entityType, entityID string) (string, error)
- func (r *MemoryRepository) ListSubscriptionsByReferenceID(_ context.Context, referenceID string) ([]*Subscription, error)
- func (r *MemoryRepository) SaveCustomerPolarID(_ context.Context, entityType, entityID, polarCustomerID string) error
- func (r *MemoryRepository) UpdateSubscription(_ context.Context, sub *Subscription) error
- type Option
- func WithAccessToken(token string) Option
- func WithAuthorizeReference(fn AuthorizeReferenceFunc) Option
- func WithCreateCustomerOnSignUp(enable bool) Option
- func WithOnBenefitGranted(fn BenefitCallbackFunc) Option
- func WithOnBenefitRevoked(fn BenefitCallbackFunc) Option
- func WithOnCustomerStateChanged(fn CustomerStateCallbackFunc) Option
- func WithOnOrderPaid(fn OrderCallbackFunc) Option
- func WithOnSubscriptionCanceled(fn SubscriptionCallbackFunc) Option
- func WithOnSubscriptionCreated(fn SubscriptionCallbackFunc) Option
- func WithOnSubscriptionUpdated(fn SubscriptionCallbackFunc) Option
- func WithPlans(plans ...PolarPlan) Option
- func WithPlansFunc(fn PlansFunc) Option
- func WithServer(server string) Option
- func WithWebhookSecret(secret string) Option
- type OrderCallbackFunc
- type OrderEventPayload
- type OrganizationOptions
- type PlansFunc
- type Plugin
- func (p *Plugin) AuthorizeReference(action string) func(http.Handler) http.Handler
- func (p *Plugin) CancelSubscription(ctx context.Context, params CancelSubscriptionParams) (*Subscription, error)
- func (p *Plugin) Config() Config
- func (p *Plugin) CreateCheckoutSession(ctx context.Context, params CreateCheckoutParams) (string, error)
- func (p *Plugin) CreateCustomerPortalSession(ctx context.Context, params CustomerPortalParams) (string, error)
- func (p *Plugin) GetCustomerState(ctx context.Context, referenceID string) (*CustomerState, error)
- func (p *Plugin) GetSubscription(ctx context.Context, subID string) (*Subscription, error)
- func (p *Plugin) HandleWebhook(w http.ResponseWriter, r *http.Request)
- func (p *Plugin) ID() string
- func (p *Plugin) IngestEvent(ctx context.Context, params IngestEventParams) (*IngestEventResult, error)
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) ListMeters(ctx context.Context, referenceID string) ([]*CustomerMeter, error)
- func (p *Plugin) ListSubscriptions(ctx context.Context, referenceID string) ([]*Subscription, error)
- func (p *Plugin) OnUserCreated(ctx context.Context, user *entity.User) error
- func (p *Plugin) ProcessWebhook(ctx context.Context, payload []byte, signature string) error
- func (p *Plugin) RequireActiveSubscription(allowedPlans ...string) func(http.Handler) http.Handler
- func (p *Plugin) RequireBenefit(benefitID string) func(http.Handler) http.Handler
- func (p *Plugin) SetClient(c Client)
- func (p *Plugin) SyncSeats(ctx context.Context, referenceID string, seats int) error
- func (p *Plugin) WebhookHandler() http.Handler
- type PolarPlan
- type PortalOptions
- type Repository
- type Subscription
- type SubscriptionCallbackFunc
- type SubscriptionEventPayload
- type SubscriptionOptions
- type UsageOptions
- type WebhookReceivedPayload
Constants ¶
const ( // EventUserCreated is published when a new user is created in the application. EventUserCreated = "auth:user:created" // EventPolarCustomerCreated is published when a new Polar customer is created and linked to a local entity. EventPolarCustomerCreated = "polar:customer:created" // EventPolarSubscriptionCreated is published when a subscription is created in Polar. EventPolarSubscriptionCreated = "polar:subscription:created" // EventPolarSubscriptionUpdated is published when a subscription state or period updates. EventPolarSubscriptionUpdated = "polar:subscription:updated" // EventPolarSubscriptionCanceled is published when a subscription is canceled or revoked. EventPolarSubscriptionCanceled = "polar:subscription:canceled" // EventPolarCustomerStateChanged is published when a customer's billing or benefit state changes in Polar. EventPolarCustomerStateChanged = "polar:customer:state_changed" // EventPolarOrderPaid is published when an order payment succeeds in Polar. EventPolarOrderPaid = "polar:order:paid" // EventPolarBenefitGranted is published when a benefit is granted to a customer in Polar. EventPolarBenefitGranted = "polar:benefit:granted" // EventPolarBenefitRevoked is published when a benefit is revoked from a customer in Polar. EventPolarBenefitRevoked = "polar:benefit:revoked" // EventPolarWebhookReceived is published upon successfully receiving and verifying a webhook event. EventPolarWebhookReceived = "polar:webhook:received" )
const ( ReferenceIDContextKey contextKey = "polar:reference_id" SubscriptionContextKey contextKey = "polar:subscription" CustomerStateContextKey contextKey = "polar:customer_state" )
const PluginID = "polar"
PluginID is the unique string identifier for the Polar plugin ("polar").
Variables ¶
var ( // ErrRepositoryRequired is returned when no Repository implementation is provided. ErrRepositoryRequired = errors.New("polar: repository is required") // ErrAccessTokenRequired is returned when no Polar Bearer access token is configured. ErrAccessTokenRequired = errors.New("polar: access token is required") // ErrSubscriptionNotFound is returned when a subscription record cannot be located. ErrSubscriptionNotFound = errors.New("polar: subscription not found") // ErrCustomerNotFound is returned when no Polar Customer ID is linked to an entity. ErrCustomerNotFound = errors.New("polar: customer not found") // ErrInvalidWebhookSignature is returned when a Polar webhook signature fails verification. ErrInvalidWebhookSignature = errors.New("polar: invalid webhook signature") ErrUnauthorizedReference = errors.New("polar: unauthorized reference access") // ErrInvalidPlan is returned when an unrecognized or missing plan ID is specified. ErrInvalidPlan = errors.New("polar: invalid plan specified") )
Functions ¶
func IsActiveOrTrialing ¶
func IsActiveOrTrialing(sub *Subscription) bool
IsActiveOrTrialing returns true if a subscription is currently active or trialing.
Types ¶
type AuthorizeReferenceData ¶
AuthorizeReferenceData holds parameters passed to the AuthorizeReference callback function.
type AuthorizeReferenceFunc ¶
type AuthorizeReferenceFunc func(ctx context.Context, data AuthorizeReferenceData) (bool, error)
AuthorizeReferenceFunc is a callback that determines whether a user is authorized to perform an action on a referenceId.
type BenefitCallbackFunc ¶
type BenefitCallbackFunc func(ctx context.Context, benefit *CustomerBenefit) error
BenefitCallbackFunc is a callback invoked when a benefit is granted or revoked.
type BenefitEventPayload ¶
type BenefitEventPayload struct {
Benefit *CustomerBenefit `json:"benefit"`
PolarEventID string `json:"polar_event_id,omitempty"`
EventType string `json:"event_type"`
}
BenefitEventPayload represents the EventBus payload for benefit entitlement events in Polar.
type CancelSubscriptionParams ¶
type CancelSubscriptionParams struct {
SubscriptionID string `json:"subscription_id"`
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
}
CancelSubscriptionParams options for canceling an active subscription.
type Client ¶
type Client interface {
CreateCustomer(ctx context.Context, email, name, externalID string) (string, error)
CreateCheckout(ctx context.Context, params CreateCheckoutParams) (string, error)
CreateCustomerSession(ctx context.Context, polarCustomerID string) (string, error)
IngestEvent(ctx context.Context, params IngestEventParams) (*IngestEventResult, error)
GetCustomerState(ctx context.Context, polarCustomerID string) (*CustomerState, error)
}
Client defines the contract for interacting with the Polar API.
type Config ¶
type Config struct {
// AccessToken is the Polar Bearer access token used to authenticate API requests.
AccessToken string
// WebhookSecret is the secret used to cryptographically verify incoming Polar webhook signatures.
WebhookSecret string
// Server environment URL or environment identifier (e.g. "sandbox", "production").
Server string
// CreateCustomerOnSignUp automatically creates a Polar Customer record when a new user registers.
CreateCustomerOnSignUp bool
// Subscription contains configuration options for subscription billing.
Subscription *SubscriptionOptions
// Portal contains options for Customer Portal sessions.
Portal *PortalOptions
// Usage contains options for usage event ingestion.
Usage *UsageOptions
// Organization contains configuration options for organization seat-based billing.
Organization *OrganizationOptions
}
Config holds operational settings and options for the Polar plugin.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns recommended production default settings for the Polar plugin.
type CreateCheckoutParams ¶
type CreateCheckoutParams struct {
ProductPriceID string `json:"product_price_id"`
ProductSlug string `json:"product_slug,omitempty"`
SuccessURL string `json:"success_url"`
CancelURL string `json:"cancel_url,omitempty"`
ReferenceID string `json:"reference_id"`
CustomerEmail string `json:"customer_email,omitempty"`
CustomerName string `json:"customer_name,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
AuthenticatedUsersOnly bool `json:"authenticated_users_only,omitempty"`
AllowDiscountCodes bool `json:"allow_discount_codes,omitempty"`
TrialDays int `json:"trial_days,omitempty"`
}
CreateCheckoutParams contains request inputs for initializing a Polar Checkout session.
type CustomerBenefit ¶
type CustomerBenefit struct {
ID string `json:"id"`
PolarBenefitID string `json:"polar_benefit_id"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
GrantedAt time.Time `json:"granted_at"`
}
CustomerBenefit represents an entitled benefit granted by Polar.
type CustomerCreatedPayload ¶
type CustomerCreatedPayload struct {
EntityType string `json:"entity_type"` // "user" or "organization"
EntityID string `json:"entity_id"`
PolarCustomerID string `json:"polar_customer_id"`
Email string `json:"email,omitempty"`
}
CustomerCreatedPayload represents the EventBus payload for EventPolarCustomerCreated.
type CustomerMeter ¶
type CustomerMeter struct {
MeterID string `json:"meter_id"`
Name string `json:"name"`
Consumed float64 `json:"consumed"`
Balance float64 `json:"balance"`
}
CustomerMeter represents a usage meter balance in Polar.
type CustomerOrder ¶
type CustomerOrder struct {
ID string `json:"id"`
PolarOrderID string `json:"polar_order_id"`
Amount int64 `json:"amount"`
Currency string `json:"currency"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
CustomerOrder represents an order or payment record in Polar.
type CustomerPortalParams ¶
type CustomerPortalParams struct {
PolarCustomerID string `json:"polar_customer_id,omitempty"`
ReferenceID string `json:"reference_id"`
ReturnURL string `json:"return_url,omitempty"`
}
CustomerPortalParams contains options for creating a Polar Customer Portal session.
type CustomerState ¶
type CustomerState struct {
PolarCustomerID string `json:"polar_customer_id"`
ReferenceID string `json:"reference_id"`
ActiveSubscriptions []*Subscription `json:"active_subscriptions"`
GrantedBenefits []*CustomerBenefit `json:"granted_benefits"`
MeterBalances []*CustomerMeter `json:"meter_balances"`
}
CustomerState summarizes the active billing state of a customer in Polar.
func CustomerStateFromContext ¶
func CustomerStateFromContext(ctx context.Context) (*CustomerState, bool)
CustomerStateFromContext retrieves CustomerState injected into request Context by middleware.
type CustomerStateCallbackFunc ¶
type CustomerStateCallbackFunc func(ctx context.Context, state *CustomerState) error
CustomerStateCallbackFunc is a callback invoked when a customer's state changes.
type CustomerStateEventPayload ¶
type CustomerStateEventPayload struct {
CustomerState *CustomerState `json:"customer_state"`
PolarEventID string `json:"polar_event_id,omitempty"`
EventType string `json:"event_type"`
}
CustomerStateEventPayload represents the EventBus payload for EventPolarCustomerStateChanged.
type IngestEventParams ¶
type IngestEventParams struct {
EventName string `json:"event_name"`
CustomerExternalID string `json:"customer_external_id,omitempty"`
PolarCustomerID string `json:"polar_customer_id,omitempty"`
Timestamp time.Time `json:"timestamp,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
}
IngestEventParams represents a request to report usage event ingestion to Polar.
type IngestEventResult ¶
type IngestEventResult struct {
IngestID string `json:"ingest_id"`
RecordedAt time.Time `json:"recorded_at"`
}
IngestEventResult represents the response from Polar usage event ingestion.
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) FindSubscriptionByPolarID ¶
func (r *MemoryRepository) FindSubscriptionByPolarID(_ context.Context, polarSubID string) (*Subscription, error)
FindSubscriptionByPolarID retrieves an in-memory subscription by remote Polar ID.
func (*MemoryRepository) GetCustomerPolarID ¶
func (r *MemoryRepository) GetCustomerPolarID(_ context.Context, entityType, entityID string) (string, error)
GetCustomerPolarID retrieves the Polar 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) SaveCustomerPolarID ¶
func (r *MemoryRepository) SaveCustomerPolarID(_ context.Context, entityType, entityID, polarCustomerID string) error
SaveCustomerPolarID persists the entity-to-Polar 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 Polar plugin.
func WithAccessToken ¶
WithAccessToken sets the Polar API access token.
func WithAuthorizeReference ¶
func WithAuthorizeReference(fn AuthorizeReferenceFunc) Option
WithAuthorizeReference configures a callback to authorize referenceId access during subscription actions.
func WithCreateCustomerOnSignUp ¶
WithCreateCustomerOnSignUp toggles automatic creation of a Polar customer record during sign-up.
func WithOnBenefitGranted ¶
func WithOnBenefitGranted(fn BenefitCallbackFunc) Option
WithOnBenefitGranted sets a callback triggered when a benefit is granted.
func WithOnBenefitRevoked ¶
func WithOnBenefitRevoked(fn BenefitCallbackFunc) Option
WithOnBenefitRevoked sets a callback triggered when a benefit is revoked.
func WithOnCustomerStateChanged ¶
func WithOnCustomerStateChanged(fn CustomerStateCallbackFunc) Option
WithOnCustomerStateChanged sets a callback triggered when customer state changes.
func WithOnOrderPaid ¶
func WithOnOrderPaid(fn OrderCallbackFunc) Option
WithOnOrderPaid sets a callback triggered when an order is paid.
func WithOnSubscriptionCanceled ¶
func WithOnSubscriptionCanceled(fn SubscriptionCallbackFunc) Option
WithOnSubscriptionCanceled sets a callback triggered when a subscription is canceled.
func WithOnSubscriptionCreated ¶
func WithOnSubscriptionCreated(fn SubscriptionCallbackFunc) Option
WithOnSubscriptionCreated sets a callback triggered when a subscription is created.
func WithOnSubscriptionUpdated ¶
func WithOnSubscriptionUpdated(fn SubscriptionCallbackFunc) Option
WithOnSubscriptionUpdated sets a callback triggered when a subscription is updated.
func WithPlansFunc ¶
WithPlansFunc sets a dynamic function for resolving available subscription plans.
func WithServer ¶
WithServer sets the server environment (e.g. "sandbox" or "production").
func WithWebhookSecret ¶
WithWebhookSecret sets the webhook secret key for verifying Polar webhook signatures.
type OrderCallbackFunc ¶
type OrderCallbackFunc func(ctx context.Context, order *CustomerOrder) error
OrderCallbackFunc is a callback invoked when an order is paid.
type OrderEventPayload ¶
type OrderEventPayload struct {
Order *CustomerOrder `json:"order"`
PolarEventID string `json:"polar_event_id,omitempty"`
EventType string `json:"event_type"`
}
OrderEventPayload represents the EventBus payload for order payment events in Polar.
type OrganizationOptions ¶
OrganizationOptions holds options for organization-level seat-based billing.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements the Polar billing, customer portal, usage metering, and webhook integration plugin for go-modular-auth.
func New ¶
func New(repo Repository, opts ...Option) (*Plugin, error)
New instantiates a new Polar plugin configured with a mandatory Repository implementation and functional options.
func (*Plugin) AuthorizeReference ¶
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 an active subscription either immediately or at period end.
func (*Plugin) CreateCheckoutSession ¶
func (p *Plugin) CreateCheckoutSession(ctx context.Context, params CreateCheckoutParams) (string, error)
CreateCheckoutSession creates a new Polar Checkout session URL for product or subscription purchase.
func (*Plugin) CreateCustomerPortalSession ¶
func (p *Plugin) CreateCustomerPortalSession(ctx context.Context, params CustomerPortalParams) (string, error)
CreateCustomerPortalSession generates a Customer Portal session URL for a customer or referenceId.
func (*Plugin) GetCustomerState ¶
GetCustomerState fetches the comprehensive billing, benefit, and meter state for a customer.
func (*Plugin) GetSubscription ¶
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 webhook signature headers, and delegates processing to ProcessWebhook.
func (*Plugin) IngestEvent ¶
func (p *Plugin) IngestEvent(ctx context.Context, params IngestEventParams) (*IngestEventResult, error)
IngestEvent sends usage metrics or billing events to Polar for consumption tracking.
func (*Plugin) Init ¶
Init initializes the plugin with the shared execution context and registers event hooks.
func (*Plugin) ListMeters ¶
ListMeters retrieves active meter balances for a referenceId.
func (*Plugin) ListSubscriptions ¶
func (p *Plugin) ListSubscriptions(ctx context.Context, referenceID string) ([]*Subscription, error)
ListSubscriptions retrieves all local subscription records associated with a referenceId.
func (*Plugin) OnUserCreated ¶
OnUserCreated triggers customer creation in Polar for a newly registered user and persists the polarCustomerID.
func (*Plugin) ProcessWebhook ¶
ProcessWebhook parses raw body bytes, verifies the cryptographic signature header, and processes supported Polar webhook event types.
func (*Plugin) RequireActiveSubscription ¶
RequireActiveSubscription returns a net/http middleware that enforces that the requesting entity (user or organization referenceId) possesses an active or trialing subscription in Polar.
func (*Plugin) RequireBenefit ¶
RequireBenefit returns a net/http middleware that verifies if the entity possesses a granted benefit.
func (*Plugin) SetClient ¶
SetClient replaces the internal API client (useful for unit testing with mocks).
func (*Plugin) WebhookHandler ¶
WebhookHandler returns a net/http Handler ready for mounting in any standard Go HTTP router or server.
type PolarPlan ¶
type PolarPlan struct {
ID string `json:"id"`
Name string `json:"name"`
ProductID string `json:"product_id"`
PriceID string `json:"price_id"`
PriceAmount int64 `json:"price_amount"`
Currency string `json:"currency"`
Interval string `json:"interval"`
Metadata map[string]string `json:"metadata,omitempty"`
}
PolarPlan defines a subscription plan or product tier in Polar.
type PortalOptions ¶
type PortalOptions struct {
ReturnURL string
AuthorizeReference AuthorizeReferenceFunc
}
PortalOptions holds settings for Customer Portal generation.
type Repository ¶
type Repository interface {
// CreateSubscription persists a new local subscription record linked to Polar.
//
// Function:
// Called when a new subscription is provisioned via Checkout or Webhooks.
//
// Storage:
// Database (GORM / SQL) - Inserts a new row into polar_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 polar_subscriptions (id, plan_id, reference_id, polar_customer_id, polar_subscription_id, status, period_start, period_end, cancel_at_period_end, seats, created_at, updated_at)
// VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12);
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 polar_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 polar_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 polar_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_id, reference_id, polar_customer_id, polar_subscription_id, status FROM polar_subscriptions WHERE id = $1 LIMIT 1;
FindSubscriptionByID(ctx context.Context, id string) (*Subscription, error)
// FindSubscriptionByPolarID retrieves a subscription by its Polar-assigned subscription ID.
//
// Function:
// Used in webhook processing to locate local subscription records matching incoming Polar events.
//
// Storage:
// Database (GORM / SQL) - Query by polar_subscription_id column index.
//
// Arguments:
// - ctx: Request cancellation context.
// - polarSubID: Remote Polar subscription ID string.
//
// Returns:
// - *Subscription: Matching subscription record if found.
// - error: ErrSubscriptionNotFound if missing, or database error.
//
// Example SQL:
// SELECT id, plan_id, reference_id, polar_customer_id, polar_subscription_id, status FROM polar_subscriptions WHERE polar_subscription_id = $1 LIMIT 1;
FindSubscriptionByPolarID(ctx context.Context, polarSubID 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 polar_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_id, reference_id, polar_customer_id, polar_subscription_id, status FROM polar_subscriptions WHERE reference_id = $1;
ListSubscriptionsByReferenceID(ctx context.Context, referenceID string) ([]*Subscription, error)
// GetCustomerPolarID retrieves the Polar Customer ID linked to an entity.
//
// Function:
// Used during customer portal session creation or usage event ingestion.
//
// Storage:
// Database (GORM / SQL) - Query polar_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 Polar Customer ID.
// - error: ErrCustomerNotFound if missing, or database error.
//
// Example SQL:
// SELECT polar_customer_id FROM polar_customers WHERE entity_type = $1 AND entity_id = $2 LIMIT 1;
GetCustomerPolarID(ctx context.Context, entityType, entityID string) (string, error)
// SaveCustomerPolarID persists the mapping between a local entity and a Polar Customer ID.
//
// Function:
// Called after creating a new Customer in Polar during sign-up or onboarding.
//
// Storage:
// Database (GORM / SQL) - Upsert row into polar_customers mapping table.
//
// Arguments:
// - ctx: Request cancellation context.
// - entityType: "user" or "organization".
// - entityID: Local entity ID string.
// - polarCustomerID: Remote Polar Customer ID string.
//
// Returns:
// - error: Nil on success, or database error.
//
// Example SQL:
// INSERT INTO polar_customers (entity_type, entity_id, polar_customer_id, created_at) VALUES ($1, $2, $3, NOW())
// ON CONFLICT (entity_type, entity_id) DO UPDATE SET polar_customer_id = EXCLUDED.polar_customer_id;
SaveCustomerPolarID(ctx context.Context, entityType, entityID, polarCustomerID string) error
}
Repository defines the persistent storage contract required by the Polar plugin. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM).
Implementation Example (GORM / database/sql): ¶
type GormPolarRepository struct {
db *gorm.DB
}
func (r *GormPolarRepository) CreateSubscription(ctx context.Context, sub *polar.Subscription) error {
return r.db.WithContext(ctx).Create(sub).Error
}
type Subscription ¶
type Subscription struct {
ID string `json:"id"`
PolarSubscriptionID string `json:"polar_subscription_id"`
PolarCustomerID string `json:"polar_customer_id"`
ReferenceID string `json:"reference_id"`
Plan string `json:"plan"`
ProductID string `json:"product_id,omitempty"`
PriceID string `json:"price_id,omitempty"`
Status string `json:"status"` // "active", "trialing", "canceled", "past_due", "unpaid"
Amount int64 `json:"amount"`
Currency string `json:"currency"`
Interval string `json:"interval"` // "month", "year"
CurrentPeriodStart time.Time `json:"current_period_start"`
CurrentPeriodEnd time.Time `json:"current_period_end"`
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
Seats int `json:"seats,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Subscription represents a local subscription record linked to a Polar subscription.
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
SubscriptionCallbackFunc is a callback invoked when a subscription event occurs.
type SubscriptionEventPayload ¶
type SubscriptionEventPayload struct {
Subscription *Subscription `json:"subscription"`
PolarEventID string `json:"polar_event_id,omitempty"`
EventType string `json:"event_type"`
}
SubscriptionEventPayload represents the EventBus payload for Polar subscription events.
type SubscriptionOptions ¶
type SubscriptionOptions struct {
Plans []PolarPlan
PlansFunc PlansFunc
RequireEmailVerification bool
AuthorizeReference AuthorizeReferenceFunc
OnSubscriptionCreated SubscriptionCallbackFunc
OnSubscriptionUpdated SubscriptionCallbackFunc
OnSubscriptionCanceled SubscriptionCallbackFunc
OnCustomerStateChanged CustomerStateCallbackFunc
OnOrderPaid OrderCallbackFunc
OnBenefitGranted BenefitCallbackFunc
OnBenefitRevoked BenefitCallbackFunc
}
SubscriptionOptions holds detailed configuration rules for plans, authorization, and lifecycle callbacks.
type UsageOptions ¶
type UsageOptions struct {
DefaultEvents []string
}
UsageOptions holds settings for usage reporting.
type WebhookReceivedPayload ¶
type WebhookReceivedPayload struct {
PolarEventID string `json:"polar_event_id"`
EventType string `json:"event_type"`
RawPayload []byte `json:"-"`
}
WebhookReceivedPayload represents the EventBus payload for incoming validated Polar webhooks.