Search code examples
javascriptnode.jsstripe-paymentsmern

How to fulfill orders after Stripe's checkout.session.completed event?


My problem is with Stripe's metadata object having a 500 character limit. I have a working checkout flow but my only restriction is the character limit for my cart. My cartItems object has extras and customer notes I want to include for each cart Item. With that being said, the metadata limit gets to 500 characters fast. I have read on another post here, implementing websockets into my app which would let me create the order using after listening to stripes event. How would I go about this? Any other workarounds?

let endpointSecret;
endpointSecret =
  "whsec_bd73383ed0fcf9cfb27bd4929af341605ad32577dfd8825e1143425b846bb3c3";

router.post("/webhook", (request, response) => {
  const sig = request.headers["stripe-signature"];

  let data;
  let eventType;

  if (endpointSecret) {
    let event;

    try {
      event = stripe.webhooks.constructEvent(
        request.rawBody,
        sig,
        endpointSecret
      ); 
    } catch (err) {
      response.status(400).send(`Webhook Error: ${err.message}`);
      return;
    }

    data = event.data.object;
    eventType = event.type;
  } else {
    data = request.body.data.object;
    eventType = request.body.type;
  }

  // Handle the event
  if (eventType === "checkout.session.completed") {
    stripe.customers
      .retrieve(data.customer)
      .then((customer) => {
        console.log("customer:", customer);
        console.log("data:", data);
        createOrder(customer, data);
      })
      .catch((err) => console.log(err.message));
  }


Solution

  • You don't typically pass all cart information in metadata, you would typically store that information in your own database and then retrieve the necessary information based on a UUID that corresponds with that data and the order ID that you set on the Checkout Session via metadata which then gets returned via the Webhook.

    To give an example of what I'm recommending above --

    In your database you would have something like:

    Order ID Cart Item1 Cart Item1 Description Cart Item2...
    123456 hat red scarf
    123457 sock blue

    Then when you create your Checkout Session you just pass your Order ID as metadata. When you receive your checkout.session.completed Webhook, that metadata will indicate the Order ID so now you have all your data necessary for fulfillment and reconciliation (and you can update your database accordingly).

    Also, to clear up a misconception, with Stripe's metadata you can have 50 keys each with values up to 500 characters long.