> ## Documentation Index
> Fetch the complete documentation index at: https://polar.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Sync customer state

> Listen to webhooks and read the customer state to grant access in your application.

> [!NOTE]
>
> **Why this matters:** Subscriptions renew, payments fail, customers upgrade and credits run out, often while the customer isn't in your app. One webhook and one object tell you everything that changed. See [Customer state](https://polar.sh/docs/integrate/customer-state.md).

In this step you'll listen for state changes, then gate your AI feature on the customer's subscription and credit balance.

The examples use the sandbox client from the [quickstart overview](https://polar.sh/docs/quickstart/overview.md#prerequisites), on API version `2026-10`.

## Forward webhooks to your machine

Use the [Polar CLI](https://polar.sh/docs/integrate/cli/webhooks.md) to receive your sandbox organization's webhooks on your local server:

```bash Terminal theme={null}
curl -fsSL https://polar.sh/install.sh | bash
polar auth login --sandbox
polar webhook listen http://localhost:3000/api/webhooks
```

The CLI prints a webhook secret. Put it in your environment as `POLAR_WEBHOOK_SECRET`.

## Handle `customer.state_changed`

Polar sends `customer.state_changed` whenever a customer's subscriptions, benefits or details change. The payload is the full customer state, so you don't need to fetch anything else.

```typescript TypeScript theme={null}
import { webhooks } from "@polar-sh/sdk/2026-10";

export async function POST(request: Request) {
  let event;
  try {
    event = await webhooks.validateEvent(
      await request.text(),
      {
        "webhook-id": request.headers.get("webhook-id") ?? "",
        "webhook-timestamp": request.headers.get("webhook-timestamp") ?? "",
        "webhook-signature": request.headers.get("webhook-signature") ?? "",
      },
      process.env.POLAR_WEBHOOK_SECRET!,
    );
  } catch (error) {
    if (error instanceof webhooks.PolarWebhookVerificationError) {
      return new Response(null, { status: 403 });
    }
    if (error instanceof webhooks.PolarWebhookUnknownTypeError) {
      return new Response(null, { status: 202 });
    }
    throw error;
  }

  if (event.type === "customer.state_changed") {
    const state = event.data;
    await saveAccess(state.external_id, {
      hasPro: state.active_subscriptions.length > 0,
    });
  }

  return new Response(null, { status: 202 });
}
```

```python Python theme={null}
import os

from flask import Flask, request
from polar.v2026_10.webhooks import (
    PolarWebhookUnknownTypeError,
    PolarWebhookVerificationError,
    validate_event,
)

app = Flask(__name__)


@app.post("/api/webhooks")
def webhook():
    try:
        event = validate_event(
            request.get_data(),
            dict(request.headers),
            os.environ["POLAR_WEBHOOK_SECRET"],
        )
    except PolarWebhookVerificationError:
        return "", 403
    except PolarWebhookUnknownTypeError:
        return "", 202

    if event.type == "customer.state_changed":
        state = event.data
        save_access(state.external_id, has_pro=len(state.active_subscriptions) > 0)

    return "", 202
```

`validateEvent` (`validate_event` in Python) throws if the signature is invalid, and the handler answers `403`. Event types your SDK version doesn't know yet get a `202`, so Polar doesn't retry them. Without an SDK, verify the signature with a [Standard Webhooks library](https://polar.sh/docs/integrate/webhooks/delivery.md#custom-validation). See [Webhook delivery](https://polar.sh/docs/integrate/webhooks/delivery.md) for error handling and retries. If you use Next.js, Nuxt or Better Auth, an [adapter](https://polar.sh/docs/integrate/sdk/adapters/introduction.md) gives you this handler in a few lines.

## Guard usage with the customer state

Before running an expensive action, read the customer state by your user ID and check the `balance` of the **AI tokens** meter in `active_meters`:

```typescript TypeScript theme={null}
const state = await polar.customers.getStateExternal("user_123");

const tokens = state.active_meters.find((m) => m.meter_id === meter.id);
if (!tokens || tokens.balance <= 0) {
  // Upsell, or block the request if you don't bill overage
}
```

```python Python theme={null}
state = polar.customers.get_state_external("user_123")

tokens = next((m for m in state.active_meters if m.meter_id == meter.id), None)
if tokens is None or tokens.balance <= 0:
    # Upsell, or block the request if you don't bill overage
    ...
```

```bash cURL theme={null}
curl https://sandbox-api.polar.sh/v1/customers/external/user_123/state \
  -H "Authorization: Bearer $POLAR_ACCESS_TOKEN" \
  -H "Polar-Version: 2026-10"
```

Polar never blocks events, so a guardrail like this lives in your application. Then [send the usage event](https://polar.sh/docs/quickstart/track-usage.md) for the action, and the loop is complete.

## Verify it works

With `polar webhook listen` running, cancel Jane's subscription immediately. From the CLI or API, its ID is in `active_subscriptions` of her customer state. The CLI logs a `customer.state_changed` delivery, and your handler records that Jane no longer has Pro.

> [tab] Dashboard
>
> * Open **Sales → Subscriptions**
> * Open Jane's **Pro** subscription
> * In the actions menu, click **Cancel Subscription**
> * Set **Cancellation Date** to **Immediately**
> * Click **Cancel Subscription**

> [tab] CLI
>
> ```bash theme={null}
> polar subscriptions revoke <subscription_id>
> ```

> [tab] Prompt
>
> ```text Prompt theme={null}
> Revoke user_123's Pro subscription in my Polar sandbox.
> ```
>
> Uses the `subscriptions_revoke` operation of the [Polar MCP server](https://polar.sh/docs/integrate/mcp.md).

Canceling immediately (a revoke in the API) ends the subscription now. A subscription canceled at **End of current period** stays active until then, so access correctly continues.

In the handler, return `403` when signature verification fails (`PolarWebhookVerificationError`) and `202` for event types the SDK doesn't know (`PolarWebhookUnknownTypeError`), so Polar doesn't retry them.

## You're done

You've built the full loop: usage flows into a meter, a plan bills and credits that usage, customers buy through checkout, and your application stays in sync.

> [card] [Next: Go live](https://polar.sh/docs/quickstart/go-live.md)
>
> Set up production, add a webhook endpoint and pass the account review.

> [card] [Customer portal](https://polar.sh/docs/features/customer-portal/introduction.md)
>
> Let customers change plans, update payment methods and download invoices.

> [card] [Webhook events](https://polar.sh/docs/integrate/webhooks/events.md)
>
> Every event Polar sends, and when.

> [card] [How Polar works](https://polar.sh/docs/concepts/overview.md)
>
> The concepts behind everything you just built.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.