You just built a stunning web app using AI.
The frontend looks incredible. Users are actually signing up. You are finally ready to launch.
There is just one thing missing.
You need a way to get paid.
And that means setting up Stripe.
If you are building a micro-SaaS, simply putting a checkout button on your pricing page isn’t enough. When a user pays, Stripe needs a secure way to talk to your database to upgrade their account instantly.
If that communication fails, your user gets charged, but they don’t get access to your product.
This communication happens through Webhooks.
Today, I am going to show you exactly how to set up rock-solid Stripe webhooks for your AI-generated app. I’ll give you the exact, copy-paste code you need to securely process payments and automatically upgrade your users.
Let’s dive right in.

Why You Can’t Trust AI with Webhook Logic
Here is a hard truth about AI code generators like Cursor, Lovable, or v0:
They are incredible at writing React components and Tailwind CSS. But they are notoriously bad at writing secure, asynchronous backend logic.
If you ask an AI to “write a Stripe webhook,” it will usually give you a very basic, naive implementation.
It might process the event, but it will almost always forget one critical step: Signature Verification.
Without signature verification, anyone on the internet can send a fake HTTP request to your backend, pretending to be Stripe. They can tell your database that they just paid $1,000. And if your AI-generated webhook doesn’t verify the signature, your app will blindly upgrade their account for free.
To succeed in turning your AI UI into a Micro-SaaS, you need rock-solid event-driven architecture that doesn’t drop the ball when a user pays.
You cannot rely on AI hallucinations for your revenue pipeline. You have to write (or copy-paste) this logic manually.
Here is the exact step-by-step process to do it right.
Step 1: Creating the Stripe Webhook Endpoint
First, we need to create a secure endpoint on your server that Stripe can send data to.
Unlike a normal API route that returns JSON to your frontend, a webhook is a POST route designed specifically to receive payloads from external servers.
If you are using Next.js (the most common framework for AI builders right now), you need to create a dedicated route for this.
Create a file at app/api/webhook/route.ts (or .js).
Here is the foundational boilerplate you need to receive the raw text from Stripe:
TypeScript
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import Stripe from 'stripe';
// Initialize the Stripe server client
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2023-10-16', // Always hardcode your API version!
});
export async function POST(req: Request) {
// We must read the raw body text, not JSON, to verify the signature later
const body = await req.text();
// Grab the signature from the headers
const signature = headers().get('stripe-signature') as string;
let event: Stripe.Event;
// Step 2 will go here...
return NextResponse.json({ received: true });
}
Pro Tip: Notice how we are reading req.text() instead of req.json()? Stripe requires the raw, unparsed string body to cryptographically verify the signature. If your AI code generator tries to parse this as JSON first, the webhook will fail 100% of the time.
Step 2: The Critical Step: Verifying the Signature
Now we have the raw payload.
Next, we must prove that this payload actually came from Stripe, and not from a malicious hacker trying to get a free subscription.
To do this, we use a Webhook Secret.
You get this secret directly from your Stripe Developer Dashboard. Add it to your .env file as STRIPE_WEBHOOK_SECRET.
Now, let’s add the verification logic to our route:
TypeScript
try {
// This single function verifies the signature AND parses the JSON
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (error: any) {
// If the signature is invalid, we instantly reject the request
console.error(`Webhook Error: ${error.message}`);
return new NextResponse(`Webhook Error: ${error.message}`, { status: 400 });
}
This constructEvent function is the most important piece of code in your entire payment pipeline.
If the signature matches, it means Stripe sent it. The function will return a beautifully parsed event object. If it doesn’t match, the catch block intercepts it and returns a 400 error.
Your revenue is now mathematically secure.
Step 3: Handling checkout.session.completed
Stripe sends dozens of different events to your webhook.
Invoice created. Subscription updated. Payment failed.
But for a micro-SaaS, the only event you actually care about on day one is checkout.session.completed. This event fires the exact second a user successfully pays on your Stripe hosted checkout page.
Here is how you handle it and update your database:
TypeScript
// Listen for the successful checkout event
if (event.type === 'checkout.session.completed') {
const session = event.data.object as Stripe.Checkout.Session;
// Grab the customer ID and the email
const customerId = session.customer as string;
const customerEmail = session.customer_details?.email;
try {
// Example using Prisma ORM to update the user in your database
// You must attach the user's ID to the Stripe session metadata when creating the checkout!
const userId = session.metadata?.userId;
if (!userId) throw new Error("No user ID found in session metadata");
await prisma.user.update({
where: { id: userId },
data: {
stripeCustomerId: customerId,
isPro: true, // Upgrade the user!
},
});
console.log(`Successfully upgraded user: ${customerEmail}`);
} catch (dbError) {
console.error("Database update failed:", dbError);
return new NextResponse("Database Error", { status: 500 });
}
}
// Always return a 200 status to tell Stripe you received the event
return NextResponse.json({ status: 200, message: "Webhook processed" });
The Golden Rule of Webhooks: Always return a 200 status code at the very end of your function. If you don’t return a 200, Stripe thinks your server crashed. They will retry the webhook over and over again, which can cause duplicate database updates and a massive headache.
Testing Your Webhooks Locally
You wrote the code. But how do you test it before going live?
You can’t just send a test payment on your live website. And because your app is running on localhost:3000, Stripe’s servers cannot reach your computer.
The solution is the Stripe CLI (Command Line Interface).
The Stripe CLI creates a secure tunnel between Stripe’s servers and your local machine.
Here is how to use it:
-
Download and install the Stripe CLI.
-
Open your terminal and log in by typing:
stripe login -
Tell Stripe to forward all webhook events to your local API route:
stripe listen --forward-to localhost:3000/api/webhook
When you run that command, the terminal will print a temporary Webhook Secret. It will look like whsec_...
Copy that temporary secret and paste it into your local .env file as your STRIPE_WEBHOOK_SECRET.
Now, open a second terminal window and trigger a fake payment event:
Bash
stripe trigger checkout.session.completed
Instantly, you will see the event hit your first terminal window, get forwarded to your Next.js app, and update your local database.
It is basically magic.
Conclusion
Setting up payments is usually the most intimidating part of building a Micro-SaaS.
But once you understand how webhooks actually work, the mystery disappears.
Let’s recap the critical steps:
-
Do not let AI write your webhook logic blindly.
-
Always read the raw request body.
-
Cryptographically verify the
stripe-signatureusing your Webhook Secret. -
Catch the
checkout.session.completedevent to upgrade your users. -
Test everything locally using the Stripe CLI tunnel.
Once this pipeline is in place, you are officially in business. Your AI-generated UI is now a fully automated, scalable revenue machine. Monitor your logs in the Stripe Dashboard, keep iterating on your product, and watch the upgrades roll in.

