|
| 1 | +import { api } from 'encore.dev/api' |
| 2 | +import { Webhook } from 'standardwebhooks' |
| 3 | +import { polar, POLAR_ACCESS_TOKEN, POLAR_WEBHOOK_SECRET } from './polar' |
| 4 | + |
| 5 | +// Home route - list products |
| 6 | +export const home = api.raw({ expose: true, path: '/', method: 'GET' }, async (req, resp) => { |
| 7 | + const products = await polar.products.list({ isArchived: false }) |
| 8 | + resp.writeHead(200, { 'Content-Type': 'text/html' }) |
| 9 | + resp.end(`<html><body> |
| 10 | + <form action="/portal" method="get"> |
| 11 | + <input type="email" name="email" placeholder="Email" required /> |
| 12 | + <button type="submit">Open Customer Portal</button> |
| 13 | + </form> |
| 14 | + ${products.result.items.map((product) => `<div><a target="_blank" href="/checkout?products=${product.id}">${product.name}</a></div>`).join('')} |
| 15 | + </body></html>`) |
| 16 | +}) |
| 17 | + |
| 18 | +// Checkout route - create a checkout session and redirect |
| 19 | +export const checkout = api.raw({ expose: true, path: '/checkout', method: 'GET' }, async (req, resp) => { |
| 20 | + const url = new URL(req.url!, `http://${req.headers.host}`) |
| 21 | + const productIds = url.searchParams.get('products') |
| 22 | + |
| 23 | + if (!productIds) { |
| 24 | + resp.writeHead(400) |
| 25 | + resp.end('Missing products parameter') |
| 26 | + return |
| 27 | + } |
| 28 | + |
| 29 | + const checkoutSession = await polar.checkouts.create({ |
| 30 | + products: typeof productIds === 'string' ? [productIds] : productIds, |
| 31 | + successUrl: `http://${req.headers.host}/`, |
| 32 | + }) |
| 33 | + |
| 34 | + resp.writeHead(302, { Location: checkoutSession.url }) |
| 35 | + resp.end() |
| 36 | +}) |
| 37 | + |
| 38 | +// Customer portal route - redirect to Polar customer portal |
| 39 | +export const portal = api.raw({ expose: true, path: '/portal', method: 'GET' }, async (req, resp) => { |
| 40 | + const url = new URL(req.url!, `http://${req.headers.host}`) |
| 41 | + const email = url.searchParams.get('email') |
| 42 | + |
| 43 | + if (!email) { |
| 44 | + resp.writeHead(400) |
| 45 | + resp.end('Missing email parameter') |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + const customer = await polar.customers.list({ email }) |
| 50 | + |
| 51 | + if (!customer.result.items.length) { |
| 52 | + resp.writeHead(404) |
| 53 | + resp.end('Customer not found') |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + const session = await polar.customerSessions.create({ |
| 58 | + customerId: customer.result.items[0].id, |
| 59 | + }) |
| 60 | + |
| 61 | + resp.writeHead(302, { Location: session.customerPortalUrl }) |
| 62 | + resp.end() |
| 63 | +}) |
| 64 | + |
| 65 | +// Webhook route - verify and handle Polar webhook events |
| 66 | +export const webhooks = api.raw({ expose: true, path: '/polar/webhooks', method: 'POST' }, async (req, resp) => { |
| 67 | + const chunks: Buffer[] = [] |
| 68 | + for await (const chunk of req) { |
| 69 | + chunks.push(chunk) |
| 70 | + } |
| 71 | + const body = Buffer.concat(chunks).toString('utf-8') |
| 72 | + |
| 73 | + const headers: Record<string, string> = {} |
| 74 | + for (const [key, value] of Object.entries(req.headers)) { |
| 75 | + headers[key] = Array.isArray(value) ? value[0] : (value || '') |
| 76 | + } |
| 77 | + |
| 78 | + try { |
| 79 | + const base64Secret = Buffer.from(POLAR_WEBHOOK_SECRET().trim(), 'utf-8').toString('base64') |
| 80 | + const wh = new Webhook(base64Secret) |
| 81 | + const payload = wh.verify(body, headers) as any |
| 82 | + |
| 83 | + console.log(`[Polar] Received event: ${payload.type}`, payload.data.id) |
| 84 | + |
| 85 | + resp.writeHead(200, { 'Content-Type': 'application/json' }) |
| 86 | + resp.end(JSON.stringify({ received: true })) |
| 87 | + } catch (error: any) { |
| 88 | + console.error('[Polar] Invalid webhook signature:', error?.message) |
| 89 | + resp.writeHead(403) |
| 90 | + resp.end(JSON.stringify({ error: 'Invalid signature' })) |
| 91 | + } |
| 92 | +}) |
0 commit comments