Back to blog

Polar Webhook Signature: Same whsec_ Prefix, Two HMAC Keys

Davron10 min read
Elysiatypescriptpolar

A Polar webhook secret maps to one of two HMAC keys, set by the date it was made. Verify both in TypeScript, keep the raw body, map cancel vs revoke.

Old or new, a Polar webhook secret starts with whsec_. Nothing in the string tells you which HMAC key Polar signs with. Polar's webhook delivery docs settle it by date: "Before 8 September 2026, 00:00 UTC: Polar HMAC. Key is the UTF-8 bytes of the full whsec_… string." From that instant on, a new secret follows Standard Webhooks, and for a Standard Webhooks library the docs say to "Pass the whsec_… secret to the library as-is."

The same page says "Polar sends one webhook-signature." So a hand-rolled verifier that derives only one of the two keys rejects every event signed with the other. After 10 consecutive failed deliveries, Polar disables the endpoint.

On 13 November 2026 the main branch of ShipKit, the paid kit our team builds, still had that gap: since 1 May 2026 its verifier had derived only the Standard Webhooks key from a whsec_ secret. That day we wrote a test that signs an event the pre-September way, and it failed against the May code. We changed the verifier to try both keys, as Polar's SDK does, on a branch that hadn't been merged when this was published.

Which HMAC key does a whsec_ secret stand for?

The generation date decides. A secret generated before 8 September 2026, 00:00 UTC is Polar HMAC, so its key is the UTF-8 bytes of the whole string, whsec_ included. For one generated on or after that instant, Polar uses Standard Webhooks, and the key is the base64-decoded part after whsec_.

Only the key differs. Polar's SDK checks both kinds with one routine, and the signed content follows the Standard Webhooks spec: "The content to be signed is therefore: msg_id.timestamp.payload." The header is "a space delimited list of signatures associated with this webhook", with symmetric entries shaped v1,<base64>. The spec also asks for "a constant time comparison function". For an old secret and a library that only speaks Standard Webhooks, Polar's advice is to "Base64-encode that string before you hand it to a Standard Webhooks library."

Polar's own SDKs skip the choice: "Polar SDKs 1.0.0-alpha.19 and later try both keys." In @polar-sh/sdk 1.1.0, the latest tag on 13 November 2026, the first candidate key is the UTF-8 bytes of the whole secret. The second, the base64-decoded part after whsec_ (or the whole secret, if unprefixed), joins only when it's non-empty and differs from the first. The SDK checks each v1 entry against each key with WebCrypto's crypto.subtle.verify("HMAC", …). If none match, it throws "No matching signature found". It also rejects a request missing webhook-id, webhook-timestamp or webhook-signature, and a timestamp outside webhookToleranceSeconds = 300.

A hand-rolled verifier should copy the SDK: compute both keys and accept a signature that matches either.

The test that failed against our May verifier

ShipKit's API has checked Polar signatures since 1 May 2026, in verify-webhook.ts under the checkout module. Its key function base64-decoded whatever followed whsec_, and it used UTF-8 bytes only for a secret without the prefix. So a whsec_ secret produced the Standard Webhooks key and nothing else:

function getSecretKey(secret: string): Buffer {
  if (secret.startsWith(SECRET_PREFIX)) {
    return Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
  }
  return Buffer.from(secret, "utf8");
}

The existing tests didn't catch it. They signed with the same derivation the verifier uses, signWithSecret(..., rawKey) for a whsec_ secret, so they could only prove the code agreed with itself.

Our new test signs the way Polar does for a pre-September secret, with the UTF-8 bytes of the whole whsec_ string as the key. Against the function above, bun test printed Expected: true and Received: false. We replaced it with a function that returns every key the secret could stand for:

function getSecretKeys(secret: string): Buffer[] {
  const utf8 = Buffer.from(secret, "utf8");
  if (!secret.startsWith(SECRET_PREFIX)) return [utf8];
  const decoded = Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
  return decoded.length > 0 ? [decoded, utf8] : [utf8];
}

The verify loop then accepts any v1 entry that matches one of them, compared with timingSafeEqual after a length check:

  const signedContent = `${id}.${timestamp}.${rawBody}`;
  const expected = getSecretKeys(secret).map((key) =>
    createHmac("sha256", key).update(signedContent).digest(),
  );

  for (const entry of signatureHeader.split(" ")) {
    const commaIdx = entry.indexOf(",");
    if (commaIdx === -1) continue;
    const version = entry.slice(0, commaIdx);
    const sig = entry.slice(commaIdx + 1);
    if (version !== "v1" || !sig) continue;

    const decoded = Buffer.from(sig, "base64");
    for (const candidate of expected) {
      if (
        decoded.length === candidate.length &&
        timingSafeEqual(decoded, candidate)
      ) {
        return { ok: true };
      }
    }
  }

With the fix, the new test passes, and the whole API suite reports 81 pass and 0 fail. tsc and eslint are clean. For a secret without the whsec_ prefix, the fixed verifier tries only the UTF-8 key, while the SDK also tries the base64-decoded one.

When this was published, the fix was on a branch that hadn't been merged, so ShipKit's main branch still had the May function. That function derives the right key for a secret generated on or after 8 September 2026, 00:00 UTC, and the wrong one for an older secret.

If you hand-roll yours, sign one test fixture with each key, and derive the keys from Polar's wording for the two schemes, not from your verifier's code.

What a rejected webhook costs on Polar

Polar counts any non-2xx answer as a failed delivery, and it keeps trying. The docs say "we'll retry to send the event up to 10 times with an exponential backoff". The endpoint has its own cutoff: "Webhook endpoints are automatically disabled after 10 consecutive failed deliveries (non-2xx responses)." A disabled endpoint "will no longer receive new events", and "All organization members will receive an email notification."

A key mismatch fails every delivery, whatever the event type, so nothing breaks the run before it reaches 10. ShipKit's route answers a bad signature with 401.

Polar also times out its requests after 10 seconds and strongly recommends answering "within 2 seconds to ensure reliable delivery." Redirects are failures too, because "Polar does not follow redirects for webhook deliveries", and the page names "hosting providers like Vercel that redirect between www and non-www domains" as a common cause. The troubleshooting section adds that "Often /foo is resolved to /foo/ by frameworks" and suggests a trailing / on the URL you give Polar.

Verify the bytes Polar signed

The signature covers the body exactly as Polar sent it. Polar's SDK puts that body last in the signed content, ${webhookId}.${Math.floor(timestamp)}.${body}. A body your framework has already parsed into an object no longer holds those bytes. The webhooks reference that ships inside the @polar-sh/sdk package (.agents/skills/polar-typescript-sdk/references/webhooks.md) opens its receiver checklist on this point: "Run the webhook raw-body parser before any middleware that consumes or transforms the request body."

Items further down add "Read the unmodified request body as a string or Uint8Array" and "Reject invalid signatures before parsing or processing the payload." The Express example in the same file puts it shortest: "never reserialize request.body".

In Elysia, one route option keeps the body as a string. ShipKit's Polar route sets parse: "text":

  .post(
    "/webhooks/polar",
    ({ body, headers }) =>
      CheckoutService.handleWebhook(
        typeof body === "string" ? body : "",
        headers,
      ),
    {
      parse: "text",

The handler receives the raw string, so the HMAC runs over the bytes Polar signed. Anything that isn't a string reaches the verifier as an empty body.

Where ShipKit stands on Polar's checklist

Past the signature, Polar's webhooks reference asks for deduplication, a fast acknowledgment, an idempotent worker and an answer for event types you don't recognize. ShipKit's handler doesn't deduplicate on webhook-id yet. It does acknowledge unknown types.

  • "Use the webhook-id header as a durable deduplication key." ShipKit's database writes are upserts keyed on the Polar subscription id, so a repeated subscription event lands on the same row.
  • On unknown types: "Acknowledging an unknown but correctly signed event avoids repeated delivery failures when the selected SDK version does not recognize a newer event type." ShipKit logs an unknown type and still answers { received: true }. The SDK's validateEvent verifies, parses the JSON and throws PolarWebhookUnknownTypeError for a type its version doesn't know. If you verify with the SDK, catch that error and send a 2xx.

Tying a Polar event to a Better Auth user

A verified event still has to land on the right account. Polar's webhooks reference, in its section on benefit grants, is specific about the key: "Correlate through event.data.customer.external_id when set, or a stored Polar customer ID otherwise; do not use email as the durable key." ShipKit reads two ids, in this order, and returns null when both are missing:

function resolveUserId(sub: any): string | null {
  return sub?.metadata?.userId ?? sub?.customer?.external_id ?? null;
}

resolveUserId departs from that advice in two ways: it checks metadata.userId first, and it has no fallback to a stored Polar customer ID. When ShipKit creates a checkout, it takes user?.id, the Better Auth user id, from the session and puts it into the checkout's metadata.userId. Polar's checkout reference says "Metadata set on the checkout will be copied to the resulting order and/or subscription". That's how metadata.userId comes back on subscription events. The function's doc comment says why email isn't a fallback: "Never falls back to email — an email in the userId column would never match a real user lookup."

Polar publishes a Better Auth plugin, @polar-sh/better-auth. In 2.1.4, the latest tag on 13 November 2026, its webhooks plugin registers the Better Auth endpoint /polar/webhooks and verifies with webhooks.validateEvent from @polar-sh/sdk/2026-10, so it gets the SDK's two-key check. An unknown but signed event type gets { received: true }, and a failed verification becomes APIError("FORBIDDEN", …). The plugin declares better-auth ^1.7.0 and @polar-sh/sdk ^1.0.2 as peer dependencies, and every SDK release that ^1.0.2 admits comes after 1.0.0-alpha.19.

If your app is on Better Auth 1.7 or a later 1.x release, the plugin is the shorter path. ShipKit's lockfile resolves better-auth to 1.3.34, below the plugin's peer range, so the plugin isn't an option for ShipKit until it upgrades, and we verify by hand.

When does access end after a Polar cancel?

When Polar revokes the subscription: at the end of the paid period after an ordinary cancel, or at once when a merchant revokes immediately. A cancel at period end sends subscription.canceled right away, so a handler that ends access on that event takes away time the customer has already paid for. Polar's webhook events page gives the order.

What happens Events Polar sends Status in the payload
Cancel at period end (sent immediately) subscription.updated, subscription.canceled still active, cancel_at_period_end true
That billing period ends subscription.updated, subscription.revoked canceled
Merchant cancels with immediate revocation subscription.updated, subscription.canceled, subscription.revoked canceled immediately

The events page calls subscription.updated "a catch-all event" for the narrower subscription events, subscription.revoked included, and points to it for handling cancellations.

ShipKit's handler keeps one row per Polar subscription id. subscription.created and subscription.updated upsert the status, cancelAtPeriodEnd and currentPeriodEnd. subscription.canceled sets cancelAtPeriodEnd to true and the period end but leaves the status alone, under a comment that reads "Polar: cancellation SCHEDULED. The subscription stays active until currentPeriodEnd — do NOT touch status." subscription.revoked sets the status to revoked. The access check in getStatus reads that row:

  const isPro =
    subscription.status === "active" &&
    (subscription.currentPeriodEnd === null ||
      new Date(subscription.currentPeriodEnd) > new Date());

During a scheduled cancel both conditions stay true, so access lasts until the period runs out. At revocation, subscription.updated writes canceled and subscription.revoked writes revoked, and whichever lands first ends access. If both are late, the date half of isPro still ends access once currentPeriodEnd passes.

ShipKit's docs had a gap here. The payments page and the setup comment in the controller listed only subscription.created, subscription.updated and subscription.canceled, while the handler already processed subscription.revoked. The branch with the verifier fix adds it to both.

Where this code lives

The Elysia webhook route, resolveUserId and the access check in this piece are the ones in ShipKit, our $149 one-time kit with a Bun and Elysia API, Next.js, Better Auth, Drizzle and Polar payments. The two-key verifier and the subscription.revoked docs line were still on a branch when this was published, so the kit on sale that day didn't include them.