polar

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 13 Imported by: 0

README

GoModularAuth Polar Billing Plugin

gomodularauth-polar provides subscription billing, automated customer provisioning, customer portal sessions, and license benefit checks integrated with Polar.sh for GoModularAuth.

Installation

go get github.com/BladiCreator/go-modular-auth/plugins/polar

Quick Start


Detailed guide: doc/plugins/polar.md.

Documentation

Overview

Package polar integrates Polar.sh monetization, licensing, and subscription synchronization.

Index

Constants

View Source
const (
	// ModelPolarCustomers is the registered model name for Polar customers.
	ModelPolarCustomers = "polar_customers"

	// ModelPolarSubscriptions is the registered model name for Polar subscriptions.
	ModelPolarSubscriptions = "polar_subscriptions"

	// ModelPolarBenefits is the registered model name for Polar benefits and entitlements.
	ModelPolarBenefits = "polar_benefits"
)
View Source
const PluginID = "polar"

PluginID identifies this plugin in the GoModularAuth runtime.

Variables

View Source
var (
	// ErrCustomerNotFound indicates that no matching customer was found for the target reference.
	ErrCustomerNotFound = errors.New("polar: customer not found")

	// ErrSubscriptionNotFound indicates that no active subscription was found.
	ErrSubscriptionNotFound = errors.New("polar: subscription not found")

	// ErrBenefitNotFound indicates that the requested benefit was not granted or found.
	ErrBenefitNotFound = errors.New("polar: benefit not found")

	// ErrInvalidWebhookSignature indicates the webhook signature header is invalid or failed verification.
	ErrInvalidWebhookSignature = errors.New("polar: invalid webhook signature")

	// ErrInvalidPayload indicates the webhook payload could not be parsed or decoded.
	ErrInvalidPayload = errors.New("polar: invalid webhook payload")

	// ErrInvalidReference indicates an empty or invalid target reference (ID or type).
	ErrInvalidReference = errors.New("polar: invalid target reference")

	// ErrMissingAccessToken indicates the Polar Access Token is missing or not configured.
	ErrMissingAccessToken = errors.New("polar: missing required polar access token")

	// ErrMissingWebhookSecret indicates the Polar webhook signing secret is not configured.
	ErrMissingWebhookSecret = errors.New("polar: missing required polar webhook secret")
)

Functions

func RegisterSchema added in v1.3.0

func RegisterSchema(s *schema.Schema) error

RegisterSchema contributes Polar models to the compiled engine schema.

Types

type Benefit added in v1.3.0

type Benefit struct {
	ID             string         `json:"id"`
	CustomerID     string         `json:"customer_id"`
	ReferenceID    string         `json:"reference_id"`
	PolarBenefitID string         `json:"polar_benefit_id"`
	Type           string         `json:"type"` // "license_keys", "discord", "github", "downloadables"
	IsGranted      bool           `json:"is_granted"`
	Properties     map[string]any `json:"properties,omitempty"`
	CreatedAt      time.Time      `json:"created_at"`
	UpdatedAt      time.Time      `json:"updated_at"`
}

Benefit represents an entitlement, license key, or resource benefit granted via Polar.

type CheckoutResult added in v1.3.0

type CheckoutResult struct {
	CheckoutID string `json:"checkout_id"`
	URL        string `json:"url"`
}

CheckoutResult represents the generated Polar Checkout Session.

type Config

type Config struct {
	// AccessToken is the Polar API bearer token (e.g. polar_at_...).
	AccessToken string

	// WebhookSecret is the secret used to verify webhook signatures.
	WebhookSecret string

	// ServerURL is the Polar API server URL (e.g. "https://api.polar.sh" or "https://sandbox-api.polar.sh").
	ServerURL string

	// AutoCreateCustomerOnSignUp automatically provisions a Polar Customer when a new user registers.
	AutoCreateCustomerOnSignUp bool

	// AutoCreateCustomerOnOrgCreation automatically provisions a Polar Customer when a new organization is created.
	AutoCreateCustomerOnOrgCreation bool
}

Config holds the configuration settings for the Polar plugin module.

type CreateCheckoutInput added in v1.3.0

type CreateCheckoutInput struct {
	Target     TargetReference `json:"target"`
	ProductID  string          `json:"product_id"`
	SuccessURL string          `json:"success_url"`
	Metadata   map[string]any  `json:"metadata,omitempty"`
}

CreateCheckoutInput contains parameters for generating a Polar checkout URL.

type Customer added in v1.3.0

type Customer struct {
	ID              string         `json:"id"`
	ReferenceID     string         `json:"reference_id"`
	ReferenceType   ReferenceType  `json:"reference_type"`
	PolarCustomerID string         `json:"polar_customer_id"`
	Email           string         `json:"email"`
	Metadata        map[string]any `json:"metadata,omitempty"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
}

Customer models a synchronized Polar customer mapped to a user or organization.

type Module added in v1.3.0

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

Module implements auth.PluginModule using plugin-sdk.

func New

func New(opts ...Option) *Module

New creates an installable Polar PluginModule with optional configurations.

func (*Module) ID added in v1.3.0

func (m *Module) ID() string

ID returns the module's unique identifier.

func (*Module) Init added in v1.3.0

func (m *Module) Init(h *auth.Host) error

Init configures infrastructure, registers hooks, and provides the typed Capability into GoModularAuth.

func (*Module) RegisterSchema added in v1.3.0

func (m *Module) RegisterSchema(s *schema.Schema) error

RegisterSchema contributes Polar models to the compiled schema.

type Option

type Option func(*Config)

Option configures a Polar Config.

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken sets the Polar API access token.

func WithAutoCreateCustomerOnOrgCreation added in v1.3.0

func WithAutoCreateCustomerOnOrgCreation(enabled bool) Option

WithAutoCreateCustomerOnOrgCreation controls automatic provisioning on organization creation.

func WithAutoCreateCustomerOnSignUp added in v1.3.0

func WithAutoCreateCustomerOnSignUp(enabled bool) Option

WithAutoCreateCustomerOnSignUp controls automatic provisioning on user registration.

func WithServerURL added in v1.3.0

func WithServerURL(url string) Option

WithServerURL sets the Polar API base server URL.

func WithWebhookSecret

func WithWebhookSecret(secret string) Option

WithWebhookSecret sets the Polar webhook signature verification secret.

type Polar added in v1.3.0

type Polar interface {
	// GetCustomer retrieves the Polar customer mapped to the target reference (user or organization).
	GetCustomer(ctx context.Context, target TargetReference) (*Customer, error)

	// CreateCustomer explicitly provisions a customer in Polar and saves the local mapping.
	CreateCustomer(ctx context.Context, target TargetReference) (*Customer, error)

	// CreateCheckout generates a Polar checkout URL for a product or subscription tier.
	CreateCheckout(ctx context.Context, in CreateCheckoutInput) (*CheckoutResult, error)

	// GetCustomerPortalURL generates a URL to the Polar customer portal for billing self-service.
	GetCustomerPortalURL(ctx context.Context, target TargetReference) (string, error)

	// GetActiveSubscription retrieves the current active subscription for the given target reference.
	GetActiveSubscription(ctx context.Context, target TargetReference) (*Subscription, error)

	// HasActiveSubscription reports whether the target has an active subscription to any of the given product IDs.
	HasActiveSubscription(ctx context.Context, target TargetReference, productIDs ...string) (bool, error)

	// HasBenefit reports whether the target identity has been granted a specific benefit or license key.
	HasBenefit(ctx context.Context, target TargetReference, benefitID string) (bool, error)

	// ListBenefits lists all benefits currently granted to the target identity.
	ListBenefits(ctx context.Context, target TargetReference) ([]Benefit, error)

	// HandleWebhook processes an incoming Polar webhook payload and verifies its signature in a transport-agnostic manner.
	HandleWebhook(ctx context.Context, payload []byte, signature string) (*WebhookEvent, error)
}

Polar defines the typed capability interface exported by the Polar plugin module. Applications retrieve this via auth.Get[polar.Polar](engine).

type ReferenceType added in v1.3.0

type ReferenceType string

ReferenceType specifies the entity type bound to a billing resource.

const (
	// ReferenceUser binds the resource to an individual core User.
	ReferenceUser ReferenceType = "user"

	// ReferenceOrganization binds the resource to a multi-tenant Organization.
	ReferenceOrganization ReferenceType = "organization"
)

type Subscription

type Subscription struct {
	ID                  string             `json:"id"`
	CustomerID          string             `json:"customer_id"`
	ReferenceID         string             `json:"reference_id"`
	ReferenceType       ReferenceType      `json:"reference_type"`
	PolarSubscriptionID string             `json:"polar_subscription_id"`
	PolarProductID      string             `json:"polar_product_id"`
	Status              SubscriptionStatus `json:"status"`
	CurrentPeriodEnd    *time.Time         `json:"current_period_end,omitempty"`
	CancelAtPeriodEnd   bool               `json:"cancel_at_period_end"`
	Metadata            map[string]any     `json:"metadata,omitempty"`
	CreatedAt           time.Time          `json:"created_at"`
	UpdatedAt           time.Time          `json:"updated_at"`
}

Subscription models a synchronized Polar subscription.

func (*Subscription) Active added in v1.3.0

func (s *Subscription) Active() bool

Active reports whether the subscription is active and within valid period.

type SubscriptionStatus added in v1.3.0

type SubscriptionStatus string

SubscriptionStatus represents the lifecycle state of a Polar subscription.

const (
	StatusActive     SubscriptionStatus = "active"
	StatusCanceled   SubscriptionStatus = "canceled"
	StatusPastDue    SubscriptionStatus = "past_due"
	StatusTrialing   SubscriptionStatus = "trialing"
	StatusIncomplete SubscriptionStatus = "incomplete"
)

type TargetReference added in v1.3.0

type TargetReference struct {
	Type ReferenceType `json:"type"`
	ID   string        `json:"id"`
}

TargetReference represents a polymorphic target identity (user or organization).

type WebhookEvent added in v1.3.0

type WebhookEvent struct {
	ID        string         `json:"id"`
	Type      string         `json:"type"`
	Data      map[string]any `json:"data"`
	HandledAt time.Time      `json:"handled_at"`
}

WebhookEvent represents a processed webhook event.

Jump to

Keyboard shortcuts

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