Advanced

Custom Webhook

Welcome to Nuxt Stripe.

Sometimes you need more control over the event handling, you can still use the build in stripeWebhookHandler with a custom Stripe instance.

You can now leverage this module to create the stripe event for you, than handle the rest of the webhook like you wish.

Starts by creating the file server/api/stripe/webhook.ts:

server/api/stripe/webhook.ts
import Stripe from 'stripe'

// Create your own stripe instance
const stripe = new Stripe(process.env.STRIPE_SECRET)

export default eventHandler(async (e) => {
  assertMethod(e, 'POST')

  // Create the stripe event
  const event = await createStripeEvent(e, {
    webhookSecret: `${process.env.STRIPE_WEBHOOK_SECRET}`,
    stripe,
  })

  switch (event.type) {
    case 'payment_intent.succeeded': {
      //
    }
  }

  // Don't forget to return a 200 response otherwise Stripe will retry
  return {
    ok: true
  }
})
Make sure you return something, otherwise Stripe will retry the webhook multiple times.

Construct the Stripe event manually

Sometimes you might need to fully create the event yourself:

server/api/stripe/webhook.ts
const stripe = new Stripe(process.env.SOME_API_SECRET)

export default defineEventHandler((e) => {
  // ...

  const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET
  const signature = getHeader(e, 'stripe-signature')
  const payload = await readRawBody(e)

  const event = stripe.webhooks.constructEvent(
    payload!,
    signature!,
    endpointSecret
  )

  // ...
})

You should really check the source code of this module to see how it's done.