Get the api key

After you have created your account for Polar, you will need to get the API key. You can do this by going to the API page in the dashboard. Under the Settings, scroll to Developers and click New token. Enter a name for the token, set the expiration duration and select the scopes you want the token to have. To keep it simple, you can select all scopes.

Add environment variables

To use the Polar integration, you need to define the following environment variables to your .env.local as well as your production environment:
.env.local
POLAR_ACCESS_TOKEN=""
POLAR_WEBHOOK_SECRET=""
POLAR_ENV="" // Use 'sandbox' if you're using the sandbox environment - else use 'production' or omit the parameter

In-App Purchases

You can use Polar anywhere in your application by importing a polar object:
page.tsx
import { polar } from '@repo/payments';

Creating a Checkout Session

We need to create a checkout session to charge your users , and you only need modify some code. It consists of two parts:
  • Client
It sends a request to create a session to the /api/polar/checkout endpoint.
apps/web/[locale]/components/payment/price-form.tsx
      const response = await fetch('/api/polar/checkout', { // change to `/api/polar/checkout`
        method: 'POST',
        body: JSON.stringify({
          priceId: item.priceId,
          interval: item.interval,
        }),
      });
  • Server
Implementing business logic in apps/web/api/polar/checkout/route.ts.

Webhooks

Create a webhook

To configure a new webhook, go to the Webhooks page in the polar dashboard. Click the Add endpoint button and select at least the following events: For subscriptions:
  • subscription.created
  • subscription.updated
  • subscription.canceled
For one-off payments:
  • order.created

Webhook Handler

Stripe webhooks are handled in the POST /webhooks/polar route in the apps/api app. This route constructs the event and then switches on the event type to determine how to process the event.
We have implemented the basic structure of the Webhook handler for you. You can modify it as needed.