Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass custom data to Stripe webhook?

I am creating and processing a stripe payment like this:

    // Create payment intent
    const { data } = await axios.post('/api/payments/get-payment-intent', { slug: post.slug })

    // Use payment intent to charge the card
    const result = await stripe.confirmCardPayment(data.paymentIntentSecert, {
      payment_method: {
        card: elements.getElement(CardElement),
      },
    })

To be able to fulfill the order, I need to be able to pass some data (id of the product and username of the buyer) to the webhook that gets executed after the payment has been successfully completed (payment_intent.succeeded event).

How can I do that?

I've tried adding a metadata key to the confirmCardPayment() like this:

    const result = await stripe.confirmCardPayment(data.paymentIntentSecert, {
      payment_method: {
        card: elements.getElement(CardElement),
        metadata: {
          username: user.username,
          postId: post.id
        }
      },
    })

But the metadata doesn't show up on the object received by the webhook.

like image 682
lumenwrites Avatar asked Sep 11 '25 14:09

lumenwrites


2 Answers

This is how I do it for stripe.checkout.sessions.create. Here is the code...

const session = await stripe.checkout.sessions.create({
          line_items: [
            {
              price: 'price_example',
              quantity: 1,
            },
          ],
          mode: 'payment',
          success_url: `https://www.example.com/success?session_id={CHECKOUT_SESSION_ID}`,
          cancel_url: `https://www.example.com/?canceled=true`,
          automatic_tax: {enabled: true},
          metadata : {
            my_user: user,
            my_tokens: tokens,
          }
        });

To access the event data I did this in the webhook...

try {
...
    event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret);
}

then to get the metadata from event ...

  const gotTokens = event.data.object.metadata.my_tokens;
  const theUser = event.data.object.metadata.my_user;
like image 190
Graphics Factory Avatar answered Sep 13 '25 03:09

Graphics Factory


You can set the metadata under the key payment_intent_data when creating the checkout session. This metadata will be attached by stripe on every webhook call.

    const session = await stripe.checkout.sessions.create({
      line_items: [
        {
            price: 'price_1234567890',
            quantity: 1,
        },
      ],
      mode: 'payment',
      payment_intent_data:  {
          metadata: {
              userId: 123, // here you can set the metadata
          },
      },
      success_url: '',
      cancel_url: '',
    });
like image 36
Agu Dondo Avatar answered Sep 13 '25 04:09

Agu Dondo