Accepting Payments with Stripe
Esta página aún no está disponible en tu idioma.
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:
-
Create a Stripe account and add a product.
-
Copy your secret key from Developers > API keys in the Stripe dashboard.
-
Add a webhook endpoint pointing to
https://<your-domain>/api/stripe/webhookthat listens tocheckout.session.completedandpayment_intent.succeeded, then copy its signing secret. -
Make sure to update the environment variable(s) of your application per the following instruction:
## Stripe Environment VariablesSTRIPE_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" /><script> import ButtonCheckout from '@/components/Button-Checkout.svelte'</script>
<ButtonCheckout />import ButtonCheckout from '@/components/Button/Checkout/Stripe'
export default function Page() { return <ButtonCheckout brandName="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:
// Obtain the raw body of the request to be used in Stripe for verificationconst rawBody = await request.text()const event = stripe.webhooks.constructEvent(rawBody, sig, `${getSecret('STRIPE_WEBHOOK_SIG')}`)
// Two events in Stripe point to succesful paymentif (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:
stripe listen --forward-to localhost:3000/api/stripe/webhook