@polar-sh/better-auth
A Better Auth plugin for integrating Polar payments and subscriptions into your authentication flow.Features
- Automatic Customer creation on signup
- Sync customer deletion
- 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:
Integrate Polar with BetterAuth
1
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.
.env
2
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
BetterAuth Server with Polar Example
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)
3
Configure BetterAuth Client
You will be using the BetterAuth Client to interact with the Polar functionalities.
BetterAuth Client with Polar Example
Automatic Customer creation on signup
Enable thecreateCustomerOnSignUp
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.
Sync Customer deletion
To add user deletion logic with external Polar customer deletion in BetterAuth, extend the user config of your betterAuth setup with the deleteUser option and an afterDelete hook. Here’s how to integrate this alongside your Polar plugin and automatic customer creation:Customer Deletion Example
Checkout Plugin
Source code To support checkouts in your app, you would pass thecheckout
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.theme
(optional): A string that can be used to enforce the theme of the checkout page. Can be eitherlight
ordark
.
1
Use Checkout Plugin
Update the
use
property of the Polar plugin for BetterAuth client to have the checkout
plugin.Checkout Plugin Example
2
Create checkouts using BetterAuth client
When the 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.
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
BetterAuth Checkout with Polar Example
BetterAuth Checkout with Polar Organization Example
Usage Plugin
Source code 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 theusage
plugin in the use
property.
Usage Plugin Example
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. Theingestion
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.
Event Ingestion with Usage Plugin Example
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. Themeters
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.
Customer Meters with Usage Plugin Example
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
Source code Thewebhooks
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:
1
Configure Webhook Endpoints in Polar
Configure a Webhook endpoint in your Polar Organization Settings page by following this guide. Webhook endpoint is configured at
/api/auth/polar/webhooks
.2
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
):.env
3
Use Webhooks Plugin in BetterAuth client
Pass the
webhooks
plugin in the use
property.Webhooks Plugin Example
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 state changes
Portal Plugin
Source code A plugin which enables customer management of their purchases, orders and subscriptions.Portal Plugin Example
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.Open Customer Portal Example
2. Customer State
The portal plugin also adds a convenient method to retrieve the Customer State.Retrieve Customer State Example
- 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.
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.List User Benefits Example
3.2 Orders
This method lists orders like purchases and subscription renewals for the authenticated user/customer.List User Orders Example
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.
List Organization Subscriptions Example
3.3 Subscriptions
This method lists the subscriptions associated with authenticated user/customer.List User Subscriptions Example
This will not return subscriptions made by a parent organization to the
authenticated user.