#push data form webhook stripe

4 messages · Page 1 of 1 (latest)

wraith crater
#

I have the following server/api/stripe/webhook code

import { eventHandler, readRawBody, getHeader, createError, sendError } from 'h3'
import Stripe from 'stripe'
// import { firestore } from '~/server/utils/firebaseAdmin'
// import test from '~/services/webhook/index'
export default eventHandler(async (event: any) => {
const stripe = new Stripe(${process.env.STRIPE_SECRET_KEY})
const endpointSecret = ${process.env.STRIPE_WEBHOOK_SECRET}
let body
try {
body = await readRawBody(event, false)
} catch (err) {
throw createError({
statusCode: 400,
statusMessage: Cannot read body: ${err},
})
}
const signature = getHeader(event, 'stripe-signature')
if (!body) {
throw createError({
statusCode: 400,
statusMessage: 'Invalid request body',
})
}

if (!signature) {
    throw createError({
        statusCode: 400,
        statusMessage: 'Invalid stripe-signature',
    })
}
let stripeEvent
try {
    stripeEvent = stripe.webhooks.constructEvent(
        body,
        signature,
        endpointSecret
    )
} catch (err) {
    console.error('❌ ERROR: Webhook verification failed:', err)
    throw createError({
        statusCode: 400,
        statusMessage: Webhook error: ${err},
    })
}

// Handle the event
if (stripeEvent.type == 'payment_intent.succeeded') {
    const paymentIntent = stripeEvent.data.object
    const s3Url = paymentIntent?.metadata?.s3Url || ''
    if (!s3Url) {
        return { received: true }
    }
    // io.emit('newS3Url', s3Url);
}

return { received: true }

})
how to push s3url in webhook to client by socket?

soft geodeBOT
#

Hi @wraith crater. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, I can see that you're trying to implement WebSocket functionality in your Nuxt application to push data from a Stripe webhook to clients. H3, which is the HTTP server framework used by Nuxt, has built-in support for WebSockets through CrossWS.

To push the s3Url from your Stripe webhook to clients using WebSockets, you can follow these steps:

  1. First, set up a WebSocket handler in your Nuxt application using H3's WebSocket support:
// server/websocket.ts
import { defineWebSocketHandler } from 'h3'

export default defineWebSocketHandler({
  open(peer) {
    // When a client connects
    peer.subscribe("s3updates"); // Subscribe the client to the s3updates channel
  },
  message(peer, message) {
    // Handle incoming messages if needed
  },
  close(peer) {
    // Handle disconnection
  }
})
  1. Then, modify your webhook handler to publish the s3Url to connected clients:
// server/api/stripe/webhook.ts
import { eventHandler, readRawBody, getHeader, createError } from 'h3'
import Stripe from 'stripe'
import { getWebSocketServer } from 'h3'

export default eventHandler(async (event: any) => {
    // Your existing code...
    
    // Handle the event
    if (stripeEvent.type == 'payment_intent.succeeded') {
        const paymentIntent = stripeEvent.data.object
        const s3Url = paymentIntent?.metadata?.s3Url || ''
        if (!s3Url) {
            return { received: true }
        }
        
        // Get the WebSocket server and publish the s3Url to the s3updates channel
        const wss = getWebSocketServer(event)
        if (wss) {
            wss.publish("s3updates", { s3Url })
        }
    }

    return { received: true }
})
  1. On the client side, you'll need to connect to the WebSocket and listen for messages:
#
// In your client component
const socket = new WebSocket(`ws://${window.location.host}/_ws`)

socket.onopen = () => {
  console.log('Connected to WebSocket server')
}

socket.onmessage = (event) => {
  const data = JSON.parse(event.data)
  if (data.s3Url) {
    // Handle the s3Url update
    console.log('Received new s3Url:', data.s3Url)
    // Update your UI or state as needed
  }
}

Note that WebSocket support in H3 is currently experimental and available in the nightly channel as mentioned in the knowledge sources: WebSockets - H3.

Alternatively, you could use Server-Sent Events (SSE) which is also supported by H3:

// In your client code
const eventSource = new EventSource('/api/s3updates')
eventSource.onmessage = (event) => {
  const s3Url = event.data
  console.log('Received new s3Url:', s3Url)
  // Handle the update
}

And on the server side:

// server/api/s3updates.ts
import { eventHandler, createEventStream } from 'h3'

export default eventHandler((event) => {
  const eventStream = createEventStream(event)
  
  // You would need a way to push updates to this stream when the webhook is called
  // This could be through a shared state, a message queue, or other mechanisms
  
  return eventStream.send()
})

Remember that you'll need to implement a mechanism to connect your webhook handler with the SSE stream, such as using a pub/sub system or a shared state.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: