feat(payments): fix Polar webhook + pre-fill checkout email
Some checks failed
CI / Backend (pull_request) Successful in 26s
CI / UI (pull_request) Failing after 24s
CI / Backend (push) Successful in 26s
Release / Check ui (push) Failing after 16s
Release / Docker / ui (push) Has been skipped
CI / UI (push) Failing after 31s
Release / Test backend (push) Successful in 41s
Release / Docker / caddy (push) Successful in 33s
Release / Docker / runner (push) Successful in 2m58s
Release / Docker / backend (push) Successful in 3m43s
Release / Gitea Release (push) Has been skipped

- Fix customer email path: was data.customer_email, is actually
  data.customer.email per Polar v1 API schema
- Add resolveUser() helper: tries polar_customer_id → email → external_id
- Add subscription.active and subscription.canceled event handling
- Handle order.created for fast-path pro upgrade on purchase
- Profile page: fetch user email + polarCustomerId from PocketBase
- Profile page: pre-fill ?customer_email= on checkout links
- Profile page: link to polar.sh/purchases for existing customers
This commit is contained in:
Admin
2026-03-31 23:11:34 +05:00
parent 7b1df9b592
commit 68ea2d2808
4 changed files with 145 additions and 32 deletions

View File

@@ -1,12 +1,20 @@
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { verifyPolarWebhook, handleSubscriptionEvent } from '$lib/server/polar';
import { verifyPolarWebhook, handleSubscriptionEvent, handleOrderCreated } from '$lib/server/polar';
/**
* POST /api/webhooks/polar
*
* Receives Polar subscription lifecycle events and syncs user roles in PocketBase.
* Signature is verified via HMAC-SHA256 before any processing.
*
* Handled events:
* subscription.created — new subscription (status may be "active" or "trialing")
* subscription.active — subscription became active (e.g. after payment)
* subscription.updated — catch-all: cancellations, renewals, plan changes
* subscription.canceled — cancel_at_period_end=true, still active until period end
* subscription.revoked — access ended, downgrade to free
* order.created — purchase / subscription_create: fast-path upgrade
*/
export const POST: RequestHandler = async ({ request }) => {
const rawBody = await request.text();
@@ -30,14 +38,15 @@ export const POST: RequestHandler = async ({ request }) => {
try {
switch (type) {
case 'subscription.created':
case 'subscription.active':
case 'subscription.updated':
case 'subscription.canceled':
case 'subscription.revoked':
await handleSubscriptionEvent(type, data as unknown as Parameters<typeof handleSubscriptionEvent>[1]);
await handleSubscriptionEvent(type, data as Parameters<typeof handleSubscriptionEvent>[1]);
break;
case 'order.created':
// One-time purchases — no role change needed for now
log.info('polar', 'order.created (no action)', { orderId: data.id });
await handleOrderCreated(data as Parameters<typeof handleOrderCreated>[0]);
break;
default: