Top-level API for AshBilling.
Provides functions for managing billing customers, checkout sessions,
customer portals, and subscriptions. Customer and subscription records use
their resource's configured provider; explicit :provider takes precedence.
Raw IDs/maps without resource configuration default to Stripe.
Summary
Functions
Cancels a subscription.
Checks if a subscription is scheduled for cancellation (either via cancel_at_period_end: true
or an unexpired future cancel_at timestamp).
Performs structural (and optionally PostgreSQL / provider) configuration diagnostics.
Creates a checkout session for a customer.
Creates a billing customer in the configured provider.
Creates a billing portal session for a customer to manage subscriptions and payment methods.
Extracts the customer ID from a record configured with AshBilling.Resource.
Retrieves a subscription from the billing provider.
Reconciles a subscription against the authoritative provider state and persists updates.
Resumes a subscription that was scheduled to cancel at period end.
Checks if a record has an active subscription.
Returns the active subscription record for a customer, or nil if none is active.
Swaps a subscription to a new price/plan in the billing provider.
Updates the quantity of a subscription (e.g. per-seat billing).
Same as check_configuration/1, but raises ArgumentError if any misconfiguration is found.
Ideal for calling in Application.start/2 or config/runtime.exs.
Functions
Cancels a subscription.
Options
:at_period_end- Iftrue(default), cancels at the end of the current billing cycle.:provider- The billing provider module.
Checks if a subscription is scheduled for cancellation (either via cancel_at_period_end: true
or an unexpired future cancel_at timestamp).
Terminal subscriptions (:canceled or :incomplete_expired, including string statuses)
always return false, even if cancellation fields are still set.
For non-terminal subscriptions, cancel_at_period_end: true takes precedence over
a past cancel_at; this helper uses the supplied state and does not fetch provider updates.
Performs structural (and optionally PostgreSQL / provider) configuration diagnostics.
Preserves backwards compatibility with earlier releases: returns
{:ok, %{status: :valid, production_ready: boolean(), warnings: [...], summary: ..., checks: ...}}
when no failure checks occur, or {:error, [reasons]} when one or more checks fail.
Absent credentials remain accepted for compatibility. Notice that status: :valid
indicates structural/requested checks did not fail and does not imply
production_ready: true (check production_ready or run AshBilling.Diagnostics.run/1 /
mix ash_billing.doctor for full production readiness evaluation).
Options
:customer_resource- The Ash resource representing billing customers.:subscription_resource- The Ash resource representing subscriptions.:deduplication_resource/:webhook_event_resource- Optional Ash webhook event resource.:deduplication_strategy-:resourceor:memory.:api_key- Stripe API key to validate format (never echoed; defaults to application env).:webhook_secret- Stripe webhook secret to validate format (never echoed; defaults to application env).:expected_livemode- Optional boolean (true/false) for Stripe livemode binding.:stripe_account- Optional Stripe Connect account ID.:req_opts- OptionalReqHTTP timeout/retry options to verify.:check_database?- Whentrue, performs read-only PostgreSQL connectivity, column, and index verification. Defaults tofalse.:check_provider?- Whentrue, performs an optional read-only provider probe. Defaults tofalse.
@spec create_checkout_session(struct() | String.t(), keyword()) :: {:ok, %{url: String.t(), id: String.t()}} | {:error, term()}
Creates a checkout session for a customer.
Recurring Checkout requires an existing customer ID and exactly one line item.
Create and persist the customer first with create_customer/2, then reload
the record (or pass the returned ID with trusted ownership metadata). Missing
customer IDs return {:error, :no_customer_id} before any provider call.
Multiple subscription lines return {:error, :unsupported_subscription_items}.
Payment Checkout can have several lines and no Customer; it does not itself
confirm payment or fulfill an order. Record ownership metadata and client
references are bound to that record and cannot be replaced by options.
Options
:price- The price ID to subscribe to or purchase (shortcut for:line_items).:quantity- The quantity of the price (defaults to 1).:line_items- Explicit list of line items (e.g.[%{price: "price_123", quantity: 1}]).:success_url- The URL to redirect to upon success (required).:cancel_url- The URL to redirect to if the user cancels (required).:mode-"subscription"(default) or"payment".:provider- The billing provider module.
Creates a billing customer in the configured provider.
If the record already has a customer ID, returns {:ok, existing_customer_id} without calling the provider.
Automatic idempotency keys include the resource, canonical tenant and record ID.
An explicit :idempotency_key is preserved. Callers must authorize the record
and supply tenant/actor options for persistence as appropriate to their application.
persist: true requires a loaded Ash record and an update action; missing
prerequisites return an error before contacting the provider. A later write
failure returns {:error, {:persistence_failed, customer_id, reason}} so the
remote identity can be reconciled. persist: false only creates remotely.
Reload the record before using it for recurring Checkout. Existing IDs are
returned without a provider call; callers remain responsible for authorization.
@spec create_portal_session(struct() | String.t(), keyword()) :: {:ok, %{url: String.t()}} | {:error, term()}
Creates a billing portal session for a customer to manage subscriptions and payment methods.
Options
:return_url- The URL to return to after leaving the portal (required).:provider- The billing provider module.
Extracts the customer ID from a record configured with AshBilling.Resource.
Retrieves a subscription from the billing provider.
@spec reconcile_subscription(struct() | String.t(), keyword()) :: {:ok, struct() | :ignored} | {:error, term()}
Reconciles a subscription against the authoritative provider state and persists updates.
Unlike get_subscription/2 which only queries the provider without modifying local
data, reconcile_subscription/2 fetches the live subscription from the provider and
passes it to AshBilling.WebhookSync.sync_event/2 as a synthetic event. This ensures
that any status, plan, period, or cancellation changes are safely persisted to
PostgreSQL inside advisory locks and transaction boundaries.
This provides a safe, on-demand or periodic reconciliation procedure to heal local database drift when webhooks are permanently lost or delayed, without requiring an in-library background daemon.
Options
Requires the synchronization options needed by AshBilling.WebhookSync.sync_event/2:
:subscription_resource- Ash resource for subscriptions (inferred automatically ifsubscription_or_idis a record).:customer_resource- Ash resource for customers (e.g.MyApp.Accounts.User). Inferred fromsubscription_resourcerelationship if available.:domain- The Ash domain module to execute actions with.:tenant- Optional tenant identifier for multitenant deployments.:actor- Optional system actor to run actions on behalf of.:authorize?- Whether to perform authorization checks. Defaults tofalse.:provider- Billing provider module (defaults to configured provider).:reset_event_cursor?- Whentrue, clearslast_event_created_attonilatomically while persistinglast_reconciled_at. Useful when upgrading from0.5.xin environments where both application and PostgreSQL clocks may have been ahead of Stripe. Even when omitted (false), any existinglast_event_created_atstrictly greater than PostgreSQL'sclock_timestamp()is automatically cleared tonilso subsequent real webhooks are not dropped.:req_opts- OptionalReqHTTP client options forwarded to the provider (recommended: bounded timeouts andretry: falsewhile inside the PostgreSQLFOR UPDATEtransaction).
Note: AshBilling.Subscription synchronizes status, price_id, quantity,
provider_subscription_item_id, current_period_end, trial_ends_at,
cancel_at_period_end, cancel_at, last_event_created_at, and last_reconciled_at.
quantity and provider_subscription_item_id remain nil when a subscription is metered,
historical (pre-0.7.0), or returned by a custom provider without item quantity metadata.
Example
# In an Oban worker or scheduled task:
{:ok, updated_sub} =
AshBilling.reconcile_subscription(subscription,
domain: MyApp.Billing
)
Resumes a subscription that was scheduled to cancel at period end.
Sets cancel_at_period_end to false in the billing provider.
Checks if a record has an active subscription.
Checks loaded subscriptions associated with the record for :active or valid :trialing status.
If a price_id is passed as the second argument, verifies that the subscription matches the price.
Returns the active subscription record for a customer, or nil if none is active.
If a price_id is passed as the second argument, returns the active subscription matching that price.
Expects the :subscriptions relationship to be loaded on the record.
Swaps a subscription to a new price/plan in the billing provider.
Stripe preserves the current quantity unless an explicit positive integer is supplied. Multiple items require an explicit item ID; missing quantities and ambiguous or truncated item collections return errors instead of guessing.
Options
:proration_behavior-"create_prorations"(default),"none", or"always_invoice".:subscription_item_id- Explicit Stripe item ID. Avoids GET only with an explicit quantity.:quantity- Positive integer override; otherwise the current quantity is fetched and preserved.:proration_date- Unix timestamp to use for calculating prorations.:provider- The billing provider module.
@spec update_quantity(struct() | String.t(), pos_integer(), keyword()) :: {:ok, map()} | {:error, term()}
Updates the quantity of a subscription (e.g. per-seat billing).
Provider Implementation Note & Legacy Fallback
Stripe Provider (
AshBilling.Providers.Stripe): Implements@callback update_quantity/3natively. The HTTP request to Stripe sends onlyitems[0][id]anditems[0][quantity], omittingitems[0][price]entirely. This guarantees at the provider level that Stripe cannot accidentally change the plan price during a quantity update, avoiding race conditions with concurrent plan changes. If:price_idis supplied, it acts as an optimistic assertion against the live price; if the remote price differs, the update is safely aborted with{:error, {:price_mismatch, actual_price_id}}.Legacy / Custom Providers: If a custom provider does not implement
@callback update_quantity/3,AshBillingfalls back toswap_plan/3. If:price_idis provided,swap_plan/3is called directly with that price ID; if the caller passes a stale price ID, the legacy provider will unintentionally execute a plan swap to that stale price. If:price_idis omitted, the fallback retrieves the active price viaget_subscription/2before swapping, which carries a theoretical race window under concurrent plan modifications. Custom providers must implement@callback update_quantity/3to achieve the same price isolation and atomicity guarantees as Stripe.Local Synchronization & Consistency Model:
update_quantity/3mutates the subscription item's quantity directly in the provider and returns{:ok, remote_subscription}. Local PostgreSQL projection (quantityandprovider_subscription_item_idonAshBilling.Subscription) is eventually consistent via the signedcustomer.subscription.updatedwebhook. If immediate local read-after-write convergence is required (or if webhooks are missed), callAshBilling.reconcile_subscription/2explicitly.
Options
:proration_behavior-"create_prorations"(default),"none", or"always_invoice".:subscription_item_id- Explicit subscription item ID (avoids an extra GET call if known).:price_id- Expected active price ID assertion (aborts if Stripe has a different price).:proration_date- Unix timestamp to use for calculating prorations.:provider- The billing provider module.
@spec verify_configuration!(keyword()) :: :ok
Same as check_configuration/1, but raises ArgumentError if any misconfiguration is found.
Ideal for calling in Application.start/2 or config/runtime.exs.