Accepting Payments with Polar
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Browse the source code here.
LaunchFast ships with a built-in Polar integration. Polar is a merchant of record built for developers: it handles payments, sales tax, and compliance, and sells one-time products and subscriptions through a hosted checkout.
The integration has no extra dependencies. It calls the Polar API with fetch and verifies webhooks with the Web Crypto API, so it runs the same on Node.js, Vercel, Netlify, and Cloudflare Workers.
Here’s how you would set up Polar to use it with LaunchFast:
-
Create a Polar account and an organization.
-
Create an Organization Access Token in Settings > Developers.
-
Add a product and copy its product ID.
-
Add a webhook in Settings > Webhooks pointing to
https://<your-domain>/api/polar/webhookthat listens toorder.paidandsubscription.active, then copy its secret. -
Make sure to update the environment variable(s) of your application per the following instruction:
## Polar Environment VariablesPOLAR_ACCESS_TOKEN="polar_oat_..."POLAR_WEBHOOK_SECRET="whsec_..."POLAR_PRODUCT_ID="..." # Default product used by the Buttons/Polar componentPOLAR_ENVIRONMENT="sandbox" # "sandbox" or "production"Adding a Checkout Button
Import the Polar checkout button anywhere in your app. Clicking it posts to the /api/polar/checkout route, which creates a Polar checkout session and redirects the user to it:
---import ButtonPolarCheckout from '@/components/Buttons/Polar.astro'---
<ButtonPolarCheckout brand_name="ACME" />
<!-- or checkout a specific product --><ButtonPolarCheckout brand_name="ACME Pro" product_id="..." />Leave out product_id to sell the product set in POLAR_PRODUCT_ID. Pass it to sell several products, such as different plans on a pricing page, from the same route.
Here is what the checkout route does under the hood:
// Use the product picked by the button, else fall back to POLAR_PRODUCT_IDconst productId = await getProductId(request, getSecret('POLAR_PRODUCT_ID'))// Sandbox access tokens only work against the sandbox APIconst baseUrl = getSecret('POLAR_ENVIRONMENT') === 'sandbox' ? 'https://sandbox-api.polar.sh' : 'https://api.polar.sh'// Create a Polar checkout sessionconst response = await fetch(`${baseUrl}/v1/checkouts/`, { method: 'POST', headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ products: [productId], metadata: getReflioMetadata(cookies), success_url: new URL('/api/polar/success', site).toString(), }),})const session = (await response.json()) as { url?: string }// Redirect the user to the Polar hosted checkout created aboveif (response.ok && session.url) return webRedirect(session.url)Handling the Webhook
Polar signs webhooks with the Standard Webhooks spec. The starter kit checks the webhook-id, webhook-timestamp, and webhook-signature headers against the raw request body, rejects anything signed more than 5 minutes ago to block replays, and accepts both the newer base64 and the older plain-text secret formats:
// Obtain the raw body of the request to be used for verificationconst rawBody = await request.text()if (!(await verifyPolarWebhook(rawBody, request.headers, secret))) { return webResponse('Webhook Error: invalid signature', 403)}const event = JSON.parse(rawBody)// A paid order (one-time or any subscription payment) and an active subscription point to a succesful paymentif (event.type === 'order.paid' || event.type === 'subscription.active') { const customerEmail = event.data?.customer?.email if (customerEmail) { // Add the 'email' to the access list in the database await setAccess(customerEmail, '1') return webResponse('approved user access', 200) }}// Acknowledge the other events so that Polar does not retry themreturn webJson({ received: event.type }, 200)You can add your own logic in the webhook route, like sending a receipt with the sendEmail helper, or handling subscription.canceled to revoke access.
Testing
Set POLAR_ENVIRONMENT="sandbox" and use an access token, product, and webhook from the Polar sandbox, where no real money moves. Sandbox and production use separate tokens, products, and webhook secrets, so swap all of them and set POLAR_ENVIRONMENT="production" when you go live.