---
title: "Accepting Payments with Creem"
description: "How to accept payments with Creem in LaunchFast starter kits?"
source: "https://www.launchfa.st/documentation/payments/creem"
---

> **Site index for agents**
> Fetch https://www.launchfa.st/llms.txt to discover every page on this site.
> Every page is also available as Markdown by appending `.md` to its URL.

> Browse the source code [here](https://github.com/LaunchFast-Boilerplates/launchfa.st-astro/tree/master/src/pages/api/creem).

import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'

LaunchFast ships with a built-in [Creem](https://www.creem.io) integration. Creem is a merchant of record for SaaS and digital products: 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 Creem 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 Creem to use it with LaunchFast:

<Steps>
  1. Create a [Creem](https://www.creem.io) account and set up your store.
  2. Copy your API key from **Developers** in the Creem dashboard.
  3. Add a product and copy its product ID.
  4. In **Developers > Webhooks**, add a webhook pointing to `https://<your-domain>/api/creem/webhook`, then copy its secret.
  5. Make sure to update the environment variable(s) of your application per the following instruction:

      <Tabs>
        <TabItem label="Astro">
            [https://github.com/LaunchFast-Boilerplates/launchfa.st-astro#payments](https://github.com/LaunchFast-Boilerplates/launchfa.st-astro#payments)
        </TabItem>
        <TabItem label="SvelteKit">
            [https://github.com/LaunchFast-Boilerplates/launchfa.st-sveltekit#payments](https://github.com/LaunchFast-Boilerplates/launchfa.st-sveltekit#payments)
        </TabItem>
        <TabItem label="Next.js">
            [https://github.com/LaunchFast-Boilerplates/launchfa.st-nextjs#payments](https://github.com/LaunchFast-Boilerplates/launchfa.st-nextjs#payments)
        </TabItem>
      </Tabs>
</Steps>

```bash
## Creem Environment Variables
CREEM_API_KEY="creem_..."
CREEM_WEBHOOK_SECRET="whsec_..."
CREEM_PRODUCT_ID="prod_..." # Default product used by the Buttons/Creem component
```

## Adding a Checkout Button

Import the Creem checkout button anywhere in your app. Clicking it posts to the `/api/creem/checkout` route, which creates a Creem checkout session and redirects the user to it:

```astro
---
import ButtonCreemCheckout from '@/components/Buttons/Creem.astro'
---

<ButtonCreemCheckout brand_name="ACME" />

<!-- or checkout a specific product -->
<ButtonCreemCheckout brand_name="ACME Pro" product_id="prod_..." />
```

Leave out `product_id` to sell the product set in `CREEM_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:

```typescript
// File: src/pages/api/creem/checkout.ts

// Use the product picked by the button, else fall back to CREEM_PRODUCT_ID
const productId = await getProductId(request, getSecret('CREEM_PRODUCT_ID'))
// Test mode API keys (creem_test_...) only work against the test API
const baseUrl = apiKey.startsWith('creem_test_') ? 'https://test-api.creem.io' : 'https://api.creem.io'
// Create a Creem checkout session
const response = await fetch(`${baseUrl}/v1/checkouts`, {
  method: 'POST',
  headers: { 'x-api-key': apiKey, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    product_id: productId,
    metadata: getReflioMetadata(cookies),
    success_url: new URL('/api/creem/success', site).toString(),
  }),
})
const session = (await response.json()) as { checkout_url?: string }
// Redirect the user to the Creem hosted checkout created above
if (response.ok && session.checkout_url) return webRedirect(session.checkout_url)
```

## Handling the Webhook

Creem signs every webhook with HMAC-SHA256 and sends the signature in the `creem-signature` header. The starter kit recomputes it from the raw request body, compares the two in constant time, and gives the customer access in the database:

```typescript
// File: src/pages/api/creem/webhook.ts

// Obtain the raw body of the request to be used for verification
const rawBody = await request.text()
// Creem signs the raw body with HMAC-SHA256 (hex) using the webhook secret
const expected = toHex(await hmacSha256(secret, rawBody))
if (!safeEqual(expected, sig.trim().toLowerCase())) {
  return webResponse('Webhook Error: invalid signature', 400)
}
const event = JSON.parse(rawBody)
// A completed checkout (one-time or the first subscription payment) and a paid subscription point to a succesful payment
if (event.eventType === 'checkout.completed' || event.eventType === 'subscription.paid') {
  const customer = event.object?.customer
  const customerEmail = typeof customer === 'object' ? customer?.email : undefined
  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 Creem does not retry them
return webJson({ received: event.eventType }, 200)
```

Creem retries failed deliveries and can send the same event more than once. Setting a flag, as `setAccess` does, is safe to repeat, so keep any logic you add here safe to run twice as well.

## Testing

Turn on [test mode](https://docs.creem.io/getting-started/test-mode) in the Creem dashboard and use a test API key (`creem_test_...`). The starter kit detects the prefix and calls Creem's test API automatically. Test and live mode use separate products and webhook secrets, so swap them when you go live.
