BetterAuth
Payments and Checkouts made dead simple with BetterAuth
@polar-sh/better-auth
A Better Auth plugin for integrating Polar payments and subscriptions into your authentication flow.
Features
- Automatic Customer creation on signup
- Reference System to associate purchases with organizations
- Checkout Integration
- Event Ingestion & Customer Meters for flexible Usage Based Billing
- Handle Polar Webhooks securely with signature verification
- Customer Portal
Installation
Install the BetterAuth and Polar required libraries using the following command:
Install the BetterAuth and Polar required libraries using the following command:
Install the BetterAuth and Polar required libraries using the following command:
Install the BetterAuth and Polar required libraries using the following command:
Integrate Polar with BetterAuth
Configure Polar Access Token
Go to your Polar Organization Settings, create an Organization Access Token, and add it to the environment variables of your application.
Configure BetterAuth Server
The Polar plugin comes with it’s own set of plugins to add functionality to your stack:
- checkout - Enable seamless checkout integration
- portal - Make it possible for your customers to manage their orders, subscriptions & benefits
- usage - List customer meters & ingest events for Usage Based Billing
- webhooks - Listen for relevant Polar webhooks
Polar Plugin Configuration Options
client
(required): Polar SDK client instancecreateCustomerOnSignUp
(optional): Automatically create a Polar customer when a user signs upgetCustomerCreateParams
(optional): Custom function to provide additional customer creation metadatause
(optional): Array of Polar plugins to enable specific functionality (checkout, portal, usage, and webhooks)
Configure BetterAuth Client
You will be using the BetterAuth Client to interact with the Polar functionalities.
Automatic Customer creation on signup
Enable the createCustomerOnSignUp
Polar plugin configuration option to automatically create a new Polar Customer when a new User is added in the BetterAuth database.
All new customers are created with an associated externalId
, i.e. the ID of your User in the Database. This skips any Polar to User mapping in your database.
Checkout Plugin
To support checkouts in your app, you would pass the checkout
plugin in the use
property.
The checkout plugin accepts the following configuration options:
-
products
(optional): An array of product mappings or a function that returns them asynchronously. Each mapping contains aproductId
and aslug
that allows you to reference products by a friendly slug instead of their full ID. -
successUrl
(optional): The relative URL where customers will be redirected after a successful checkout completion. You can use the{CHECKOUT_ID}
placeholder in the URL to include the checkout session ID in the redirect. -
authenticatedUsersOnly
(optional): A boolean flag that controls whether checkout sessions require user authentication. When set totrue
, only authenticated users can initiate checkouts and the customer information will be automatically associated with the authenticated user. Whenfalse
, anonymous checkouts are allowed.
Use Checkout Plugin
Update the use
property of the Polar plugin for BetterAuth client to have the checkout
plugin.
Create checkouts using BetterAuth client
When the checkout
plugin is passed, you are then able to initialize Checkout Sessions using the checkout
method on the BetterAuth client. This will redirect the user to the product’s checkout link.
The checkout
method accepts the following properties:
products
(optional): An array of Polar Product IDs.slug
(optional): A string that can be used as a reference to theproducts
defined in the Checkout configreferenceId
(optional): An identifier that will be saved in the metadata of the checkout, order & subscription object
This plugin supports the Organization plugin. If you pass the organization ID to the Checkout referenceId, you will be able to keep track of purchases made from organization members.
Usage Plugin
A plugin for Usage Based Billing that allows you to ingest events from your application and list the authenticated user’s Usage Meter.
To enable usage based billing in your app, you would pass the usage
plugin in the use
property.
1. Event Ingestion
Polar’s Usage Based Billing builds entirely on event ingestion. Ingest events from your application, create Meters to represent that usage, and add metered prices to Products to charge for it.
The ingestion
method of the usage
plugin accepts the following parameters:
-
event
(string): The name of the event to ingest. For example,ai_usage
,video_streamed
orfile_uploaded
. -
metadata
(object): A record containing key-value pairs that provide additional context about the event. Values can be strings, numbers, or booleans. This is useful for storing information that can be used to filter the events or compute the actual usage. For example, you can store the duration of the video streamed or the size of the file uploaded.
The authenticated user is automatically associated with the ingested event.
2. Customer Meters
A method to list the authenticated user’s Usage Meters (aka Customer Meters). A Customer Meter contains all the information about their consumption on your defined meters.
The meters
method of the usage
plugin accepts the following parameters:
-
page
(number): The page number for pagination (starts from 1). -
limit
(number): The maximum number of meters to return per page.
The meters
method returns the following fields in the response object:
- Customer Information: Details about the authenticated customer
- Meter Information: Configuration and settings of the usage meter
- Customer Meter Information:
- Consumed Units: Total units consumed by the customer
- Credited Units: Total units credited to the customer
- Balance: The balance of the meter, i.e. the difference between credited and consumed units.
Webhooks Plugin
The webhooks
plugin can be used to capture incoming events from your Polar organization.
To set up the Polar webhooks
plugin with the BetterAuth client, follow the steps below:
Configure Webhook Endpoints in Polar
Configure a Webhook endpoint in your Polar Organization Settings page by following this guide. Webhook endpoint is configured at /polar/webhooks.
Add the Webhook Secret
Add the obtained webhook secret to your application environment as an environment variable (to be used as process.env.POLAR_WEBHOOK_SECRET
):
Use Webhooks Plugin in BetterAuth client
Pass the webhooks
plugin in the use
property.
The webhooks
plugin allows you to invoke handlers for all Polar webhook events:
onPayload
- Catch-all handler for any incoming Webhook eventonCheckoutCreated
- Triggered when a checkout is createdonCheckoutUpdated
- Triggered when a checkout is updatedonOrderCreated
- Triggered when an order is createdonOrderPaid
- Triggered when an order is paidonOrderRefunded
- Triggered when an order is refundedonRefundCreated
- Triggered when a refund is createdonRefundUpdated
- Triggered when a refund is updatedonSubscriptionCreated
- Triggered when a subscription is createdonSubscriptionUpdated
- Triggered when a subscription is updatedonSubscriptionActive
- Triggered when a subscription becomes activeonSubscriptionCanceled
- Triggered when a subscription is canceledonSubscriptionRevoked
- Triggered when a subscription is revokedonSubscriptionUncanceled
- Triggered when a subscription cancellation is reversedonProductCreated
- Triggered when a product is createdonProductUpdated
- Triggered when a product is updatedonOrganizationUpdated
- Triggered when an organization is updatedonBenefitCreated
- Triggered when a benefit is createdonBenefitUpdated
- Triggered when a benefit is updatedonBenefitGrantCreated
- Triggered when a benefit grant is createdonBenefitGrantUpdated
- Triggered when a benefit grant is updatedonBenefitGrantRevoked
- Triggered when a benefit grant is revokedonCustomerCreated
- Triggered when a customer is createdonCustomerUpdated
- Triggered when a customer is updatedonCustomerDeleted
- Triggered when a customer is deletedonCustomerStateChanged
- Triggered when a customer is created
Portal Plugin
A plugin which enables customer management of their purchases, orders and subscriptions.
The portal
plugin gives the BetterAuth Client a set of customer management methods, scoped under authClient.customer
object.
1. Customer Portal Management
The following method will redirect the user to the Polar Customer Portal, where they can see their orders, purchases, subscriptions, benefits, etc.
2. Customer State
The portal plugin also adds a convenient method to retrieve the Customer State.
The customer state object contains:
- All the data about the customer.
- The list of their active subscriptions.
This does not include subscriptions done by a parent organization. See the subscription list-method below for more information.
- The list of their granted benefits.
- The list of their active meters, with their current balance.
Using the customer state object, you can determine whether to provision access for the user to your service.
Learn more about the Polar Customer State in the Polar Docs.
3. Benefits, Orders & Subscriptions
The portal plugin adds the following 3 convenient methods for listing benefits, orders & subscriptions relevant to the authenticated user/customer.
3.1 Benefits
This method only lists granted benefits for the authenticated user/customer.
3.2 Orders
This method lists orders like purchases and subscription renewals for the authenticated user/customer.
Using the Organization ID as the referenceId
you can retrieve all the subscriptions associated with that organization (instead of the user).
To figure out if a user should have access, pass the user’s organization ID to see if there is an active subscription for that organization.
3.3 Subscriptions
This method lists the subscriptions associated with authenticated user/customer.
This will not return subscriptions made by a parent organization to the authenticated user.