How to Set Up Stripe Webhooks for Your SaaS Without Breaking Payments | Deployxa

Stripe webhooks are critical for SaaS payments, but they are easy to get wrong. Here is the founder's guide to reliable, secure, and tested webhook handling.

← Back to Dispatch Articles
Engineering Log

How to Set Up Stripe Webhooks for Your SaaS Without Breaking Payments

Stripe webhooks are critical for SaaS payments, but they are easy to get wrong. Here is the founder's guide to reliable, secure, and tested webhook handling.

How to Set Up Stripe Webhooks for Your SaaS Without Breaking Payments

Key Facts

  • Direct answer: The direct answer is that Stripe webhooks require four things: signature verification (confirm the webhook is from Stripe), idempotency (handle duplicate webhooks without double-processing), fast responses (respond within 30 seconds to avoid Stripe retries), and error handling (return 200 for permanent errors, 500 for temporary errors).

  • Why Stripe Webhooks Matter for SaaS: Stripe webhooks matter for three business reasons.

  • The Four Requirements for Reliable Stripe Webhooks: Stripe signs each webhook with a secret (the webhook signing secret).

  • How to Test Stripe Webhooks: Testing webhooks is essential.

Stripe webhooks are how your SaaS knows when a payment succeeds, a subscription is cancelled, or a refund is issued. They are critical for payment processing, but they are also easy to get wrong: without signature verification, an attacker can spoof webhooks; without idempotency, duplicate webhooks cause double charges; without proper error handling, failed webhooks cause missed payments. This article is the founder's guide to reliable, secure, and tested Stripe webhook handling.

The direct answer is that Stripe webhooks require four things: signature verification (confirm the webhook is from Stripe), idempotency (handle duplicate webhooks without double-processing), fast responses (respond within 30 seconds to avoid Stripe retries), and error handling (return 200 for permanent errors, 500 for temporary errors). For more on webhooks, see our article on the webhook reliability gap.

Why Stripe Webhooks Matter for SaaS

Stripe webhooks matter for three business reasons:

  • Payment accuracy. Without webhooks, your SaaS does not know when a payment succeeds (it only knows when the checkout is initiated). Webhooks update your database when the payment is completed, which ensures the customer gets access to the product.
  • Subscription management. Without webhooks, your SaaS does not know when a subscription is cancelled, upgraded, or past due. Webhooks update the subscription status, which ensures the customer's access is correctly managed.
  • Automated operations. Without webhooks, you would need to manually check Stripe for payment status, which is not scalable. Webhooks automate the process, which frees you to focus on the product.

The Four Requirements for Reliable Stripe Webhooks

Requirement 1: Signature Verification

Stripe signs each webhook with a secret (the webhook signing secret). Your webhook endpoint must verify the signature to confirm the webhook is from Stripe (not from an attacker). Without verification, an attacker can send a fake webhook and trigger actions (e.g., mark an invoice as paid without actually paying).

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Process the event
  // ...
});

For more on security, see our article on a practical security checklist for early-stage SaaS.

Requirement 2: Idempotency

Stripe retries webhooks if it does not receive a 200 response within 30 seconds. This means the same webhook can arrive multiple times. Without idempotency, duplicate webhooks cause duplicate actions (e.g., double charges, duplicate records).

// Check if the webhook has already been processed
const processed = await WebhookLog.findOne({ where: { eventId: event.id } });
if (processed) {
  return res.json({ received: true, duplicate: true });
}

// Log the webhook
await WebhookLog.create({ eventId: event.id, type: event.type });

// Process the webhook
// ...

Requirement 3: Fast Responses

Stripe has a 30-second timeout. If your webhook handler does not respond within 30 seconds, Stripe retries the webhook. If your handler does synchronous work (e.g., sends an email, generates a report), it might exceed the timeout.

The fix is to respond immediately (200) and process the webhook asynchronously (via a background job):

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  // Verify signature
  // Check idempotency
  // Log the webhook

  // Respond immediately
  res.json({ received: true });

  // Process asynchronously
  try {
    switch (event.type) {
      case 'checkout.session.completed':
        await jobQueue.add('process-payment', event.data.object);
        break;
      case 'customer.subscription.deleted':
        await jobQueue.add('cancel-subscription', event.data.object);
        break;
    }
  } catch (err) {
    console.error('Webhook processing error:', err);
  }
});

For more on background jobs, see our article on the SaaS founder's guide to background jobs and workers.

Requirement 4: Error Handling

Handle errors correctly:

  • Permanent errors (e.g., malformed payload): return 200 (to stop Stripe from retrying).
  • Temporary errors (e.g., database timeout): return 500 (to trigger Stripe retries).
  • Unhandled errors: log them and return 200 (to avoid infinite retries).

How to Test Stripe Webhooks

Testing webhooks is essential. Use Stripe CLI to send test webhook events to your local development server:

# Install Stripe CLI
# https://stripe.com/docs/stripe-cli

# Listen for webhooks and forward to your local server
stripe listen --forward-to localhost:3000/webhooks/stripe

# Trigger a test event
stripe trigger checkout.session.completed

Verify your webhook handler processes the event correctly, logs it, and responds with 200.

Common Pitfalls and Troubleshooting

The first pitfall is not verifying the signature. Without verification, an attacker can spoof webhooks. The fix is to always verify the signature.

The second pitfall is using express.json() for the webhook route. Stripe's signature verification requires the raw body, but express.json() parses it into a JavaScript object, which changes the body. The fix is to use express.raw({ type: 'application/json' }) for the webhook route.

The third pitfall is not handling duplicates. Stripe retries webhooks, which means the same event can arrive multiple times. The fix is to check if the event has already been processed (by storing the event ID in a database).

The fourth pitfall is slow responses. If the handler takes more than 30 seconds, Stripe retries. The fix is to respond immediately and process asynchronously.

The fifth pitfall is not testing. Webhooks that are not tested might fail in production. The fix is to test with Stripe CLI before launching.

Conclusion: Reliable Webhooks, Reliable Payments

Stripe webhooks are critical for SaaS payment processing, but they are easy to get wrong. By implementing signature verification, idempotency, fast responses, and proper error handling, you can ensure your webhooks are reliable, secure, and tested. Do not launch your SaaS without tested webhook handling — it is the backbone of your payment flow.

Ready to set up Stripe webhooks? Follow the four requirements above, test with Stripe CLI, and deploy with confidence. For more, see the webhook reliability gap and the practical security checklist for early-stage SaaS. Explore our free developer tools to speed up your workflow.

Ready to deploy with Deployxa?

Deploy your apps globally with automatic SSL and AI diagnostics.

Start Free Now