Tomaz_
Tomaz_

Reputation: 469

Stripe webhooks automatically erases metadata after a few calls

I am creating a session and passing some metadata along with it. And then using webhooks I'm capturing it for provisioning the users.

Here is the webhook code I copied directly from Stripe doc.

app.post("/webhook", async (req, res) => {
  let data;
  let eventType;
  // Check if webhook signing is configured.
  const webhookSecret = {{'STRIPE_WEBHOOK_SECRET'}}
  if (webhookSecret) {
    // Retrieve the event by verifying the signature using the raw body and secret.
    let event;
    let signature = req.headers["stripe-signature"];

    try {
      event = stripe.webhooks.constructEvent(
        req.body,
        signature,
        webhookSecret
      );
    } catch (err) {
      console.log(`⚠️  Webhook signature verification failed.`);
      return res.sendStatus(400);
    }
    // Extract the object from the event.
    data = event.data;
    eventType = event.type;
  } else {
  
    data = req.body.data;
    eventType = req.body.type;
    console.log(data.object.metadata)// ----------------> This is the only line I have added.

  }

  switch (eventType) {
      case 'checkout.session.completed':
      
        break;
      case 'invoice.paid':
       
        break;
      case 'invoice.payment_failed':
       
        break;
      default:
      // Unhandled event type
    }

  res.sendStatus(200);
});

Output of data.object.metadata looks like this.

{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{
  userId: '61e1d34343223e6828ac3935a8',
  postNumber: '8',
  accountType: 'growth',
 
}
{}
{}
{}
{}
{}

I want to retain the metadata value so that i can use them for invoice completed event later. But its empty by the time i access it inside invoice completed event.

I'm new to programming. So appreciate any help

Upvotes: 1

Views: 361

Answers (1)

Brendan Moore
Brendan Moore

Reputation: 1306

You should log the event type along with the metadata. Mostly likely you are receiving and display events of several different types with different object payloads.

Where are you setting metadata, on the checkout session itself? That will only appear on the checkout session object & events then, not the invoice objects/events.

Please share the details of where you are setting metadata, and in which specific objects/events you expect to receive it.

Upvotes: 1

Related Questions