Skip to content

Accepting Payments with Stripe

Browse the source code here.

LaunchFast ships with a built-in Stripe integration: a checkout route that creates a Stripe Checkout session, and a webhook route that gives the customer access once they have paid.

Here’s how you would set up Stripe to use it with LaunchFast:

  1. Create a Stripe account and add a product.

  2. Copy your secret key from Developers > API keys in the Stripe dashboard.

  3. Add a webhook endpoint pointing to https://<your-domain>/api/stripe/webhook that listens to checkout.session.completed and payment_intent.succeeded, then copy its signing secret.

  4. Make sure to update the environment variable(s) of your application per the following instruction:

Terminal window
## Stripe Environment Variables
STRIPE_SECRET_KEY="sk_live_..."
STRIPE_WEBHOOK_SIG="whsec_..."

Adding a Checkout Button

Import the checkout button anywhere in your app. Clicking it calls the /api/stripe/checkout route, which creates a Stripe Checkout session and redirects the user to it.

---
import ButtonCheckout from '@/components/Buttons/Checkout.astro'
---
<ButtonCheckout brand_name="ACME" />

To change the product, price, discounts, or custom checkout fields, edit the stripe.checkout.sessions.create call in the checkout route.

Handling the Webhook

Once a payment goes through, Stripe calls your webhook route. The starter kit verifies the signature against the raw request body, reads the customer’s email, and gives them access in the database:

src/pages/api/stripe/webhook.ts
// Obtain the raw body of the request to be used in Stripe for verification
const rawBody = await request.text()
const event = stripe.webhooks.constructEvent(rawBody, sig, `${getSecret('STRIPE_WEBHOOK_SIG')}`)
// Two events in Stripe point to succesful payment
if (event.type === 'checkout.session.completed' || event.type === 'payment_intent.succeeded') {
const customerEmail = event.type === 'checkout.session.completed' ? event.data.object.customer_details?.email : event.data.object.receipt_email
if (customerEmail) {
// Add the 'email' to the access list in the database
await setAccess(customerEmail, '1')
return webResponse('approved user access', 200)
}
}

You can add your own logic in the webhook route, like sending a receipt with the sendEmail helper or storing the order in your database.

Testing

In Stripe test mode, pay with the card number 4242 4242 4242 4242, any future expiry date, and any CVC. To receive webhooks on your local machine, forward them with the Stripe CLI:

Terminal window
stripe listen --forward-to localhost:3000/api/stripe/webhook