Polar.sh IntegrationPolar.sh SDK, Checkouts & Standard Webhooks

Tie Polar.sh orders and refunds straight back to the content that converted.

Attach window.trimstats.attribution() to @polar-sh/sdk checkout metadata and verify order.paid and order.refunded Standard Webhooks server-side in ClickHouse.

Imtiaz Rayhan
Imtiaz RayhanCo-Founder & Lead Engineer, DotCamp & TrimStats
Tested against Polar.sh & live TrimStats APIs
Seeded demo workspace
TrimStats Revenue Attribution dashboard showing net attributed revenue, orders, AOV, RPV, and channel breakdown for Polar, Stripe, and Paddle webhooksTrimStats Revenue Attribution dashboard showing net attributed revenue, orders, AOV, RPV, and channel breakdown for Polar, Stripe, and Paddle webhooks
Attribute Polar.sh orders, subscription renewals, and refunds across referrers, UTM campaigns, landing pages, and countries with first-touch or last-touch toggling.
Direct answer

How does TrimStats attribute Polar.sh orders, renewals, and refunds?

TrimStats connects natively to Polar.sh via Standard Webhooks for order.paid and order.refunded events. Pass window.trimstats.attribution() into polar.checkouts.create() metadata.trimstats, and the Fastify collector verifies webhook-id, webhook-timestamp, and webhook-signature headers with timing-safe comparison before joining revenue across 90-day ClickHouse journeys.

Step-by-step setup for Polar.sh

Copy-paste implementation verified against the live TrimStats tracker and collector APIs.

  1. 1

    Capture window.trimstats.attribution() in your checkout trigger

    Before posting to your Polar checkout API route, read the flat attribution snapshot from window.trimstats?.attribution?.() so referrer, landing page, UTM parameters, and visitor ID reach your server.

    components/PolarBuyButton.tsxts
    1const attribution = window.trimstats?.attribution?.() ?? {};
    2
    3const res = await fetch('/api/polar-checkout', {
    4 method: 'POST',
    5 headers: { 'content-type': 'application/json' },
    6 body: JSON.stringify({ productId: 'prod_growth_monthly', attribution }),
    7});
    8const { url } = await res.json();
    9window.location.assign(url);
  2. 2

    Attach metadata.trimstats in @polar-sh/sdk checkouts.create()

    Forward the serialized attribution object (plus your authenticated database userId as uid) into metadata.trimstats when creating the Polar checkout session.

    app/api/polar-checkout/route.tsts
    1import { Polar } from '@polar-sh/sdk';
    2
    3const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN! });
    4
    5export async function POST(req: Request) {
    6 const { productId, userId, attribution } = await req.json();
    7
    8 const checkout = await polar.checkouts.create({
    9 products: [productId],
    10 metadata: {
    11 trimstats: JSON.stringify({
    12 ...(attribution ?? {}),
    13 uid: userId ?? attribution?.uid ?? '',
    14 }),
    15 },
    16 successUrl: 'https://acme.dev/dashboard?upgraded=1',
    17 });
    18
    19 return Response.json({ url: checkout.url });
    20}
  3. 3

    Register your Polar webhook endpoint for order.paid and order.refunded

    In Polar organization settings under Webhooks -> Add Endpoint, enter https://collect.trimstats.com/v1/webhooks/polar/{siteId} and subscribe to order.paid and order.refunded.

  4. 4

    Save your polar_whs_ signing secret in TrimStats Site settings

    Paste your Polar signing secret (polar_whs_... or whsec_...) under Site settings -> Revenue Attribution Webhooks (provider: Polar). TrimStats validates v1 Standard Webhooks signatures with a 5-minute replay tolerance.

Recommended taxonomy

High-signal custom events to track for Polar.sh

Fire any event with window.trimstats?.('event', name, props) and attach it to conversion goals or multi-step ClickHouse funnels.

Event nameWhen to fireSample properties
pricing_viewedDeveloper or founder lands on your pricing comparison page.{"plan_highlighted":"growth"}
polar_checkout_startedUser clicks Subscribe and redirects to a Polar.sh hosted checkout.{"product":"growth_monthly"}
github_repo_clickedVisitor clicks through to your GitHub repository or open-source README.{"location":"navbar"}
docs_quickstart_copiedDeveloper copies an SDK or CLI installation block from docs.{"sdk":"polar"}
customer_portal_openedPaying subscriber opens the Polar Customer Portal to change plans.{"source":"billing_page"}
Seeded demo workspace
TrimStats verified Polar Standard Webhooks configuration alongside a chronological buyer timeline linking discovery visits to paid revenueTrimStats verified Polar Standard Webhooks configuration alongside a chronological buyer timeline linking discovery visits to paid revenue
Every verified Polar.sh order.paid and order.refunded event reconciles idempotently on external_tx_id inside individual customer timelines.

TrimStats ClickHouse journey windows supporting Polar.sh SaaS billing cycles

Verified lookback duration in days across TrimStats reporting engines

days
Cookie-less daily salt
1 day
Multi-step funnel max window
30 days
Polar webhook ClickHouse join
90 days
Visitor timeline max history
730 days

Joining Polar order webhooks across a 90-day ClickHouse lookback captures long developer evaluation cycles from first blog read to paid subscription.

Methodology: Exact production lookback parameters read from packages/shared/src/schemas.ts and apps/web/lib/content/facts.ts.

View chart data table
LabelLookback window
Cookie-less daily salt1 day
Multi-step funnel max window30 days
Polar webhook ClickHouse join90 days
Visitor timeline max history730 days

Polar.sh analytics FAQ

Implementation details, privacy trade-offs, and event-quota answers.

How does TrimStats verify Polar.sh webhook signatures?
TrimStats implements the full Standard Webhooks specification used by Polar.sh, validating the webhook-id, webhook-timestamp, and webhook-signature (v1,<base64>) headers over "${webhookId}.${webhookTimestamp}.${rawBody}" with timing-safe comparison and a 5-minute replay window.
Which Polar webhook events should I subscribe to?
Subscribe to order.paid and order.refunded. TrimStats records new subscriptions, recurring subscription renewals, and one-time digital product orders from order.paid, and automatically subtracts refunds from net revenue on order.refunded.
Can I pass flat Polar metadata keys instead of a JSON trimstats string?
Yes. TrimStats accepts either a serialized JSON object inside metadata.trimstats or flat string metadata keys (vid, uid, ref, lp, utm_source, and utm_campaign) when creating Polar checkout sessions.
Does TrimStats itself run on Polar.sh billing?
Yes. TrimStats uses Polar.sh as its own Merchant of Record via @polar-sh/better-auth and @polar-sh/sdk, so the Polar webhook parser and Standard Webhooks verifier are dogfooded directly in production.
Are Polar webhook retries deduplicated automatically?
Yes. Every ingested order and refund is deduplicated by its Polar external_tx_id in ClickHouse so webhook retries never double-count orders or inflate net revenue.
Does Polar.sh attribution work in cookie-less mode or with multi-day SaaS journeys?
Yes. In default cookie-less mode, passing window.trimstats.attribution() into Polar checkout metadata attributes same-session buyers cleanly with zero browser cookies. Enabling optional first-party ID mode or identify() joins Polar orders to up to 90 days of ClickHouse visit history.
Imtiaz Rayhan
Integration guide verified by
Imtiaz Rayhan (Co-Founder & Lead Engineer, DotCamp & TrimStats)

Co-founder of DotCamp LLC in Brooklyn, NY and lead engineer of TrimStats. Ships privacy-first web analytics, ClickHouse pipelines, and WordPress plugins used on 115,000+ active sites.

  • • Architect of the TrimStats 1.96 KB gzipped browser tracker, Fastify collector, and ClickHouse MergeTree pipeline
  • • Co-founder of DotCamp LLC (est. 2019), creator of Ultimate Blocks (50,000+ installs), WP Table Builder (50,000+ installs), Tableberg, and OptimizeCamp
  • • WordPress.org plugin & theme developer since 2016 with 1,200+ community support replies and 5M+ cumulative plugin downloads

Verification standard: Code snippets, custom event payloads, and webhook contracts for Polar.sh are verified against the live TrimStats tracker (1.96 KB gzipped) and collector schema as of 2026-11-30.

Instrument Polar.sh in under 60 seconds

Start on Starter ($17/month for 100,000 monthly events), with cookie-less privacy defaults and full access to revenue webhooks, funnels, cohorts, and UI friction.

Verified against live TrimStats APIs and tracker bundle.