Search code examples
javascriptnext.jsstripe-paymentssanity

Stripe checkout modifies my db id's and then cannot proceed to delete or change stock in my db with a webhook


I'm building an ecommerce with NextJs, Sanity as CMS and stripe

the problem goes when creating the checkout session stripes transforms my data from my CMS and then if I retrieve that data after succesfull with a webhook I will not be able to get the same ids of the products, I will be getting new Ids mades from stripe not my cms.

here is an example of the code when creating the session, note that I am using use-shopping-cart to handle the products cart ( validates the data after sending and also transform de array to the one that Stripes accept)

/api/route.js

const { validateCartItems } = require('use-shopping-cart/utilities')
import Stripe from "stripe";
import { client } from "../../../lib/sanity/client";
import { merchQuery } from "../../../lib/sanity/merchQuery";

//
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY, {
  // https://github.com/stripe/stripe-node#configuration
  apiVersion: "2020-03-02",
});



export default async function handler(req, res) {


  if (req.method === "POST") {
    try {
      // Validate the cart details that were sent from the client.
      const cartItems = req.body;

      //Sanity client performs merchQuery
      let sanityData = await client.fetch(merchQuery);

   // The POST request is then validated against the data from Sanity.
      const line_items = validateCartItems(sanityData, cartItems);


      // Create Checkout Sessions from body params.
      const params = {
        submit_type: "pay",
        mode: "payment",
        payment_method_types: ["card"],
        billing_address_collection: "auto",
        shipping_address_collection: {
          allowed_countries: ["US"],
        },
    
      //The validated cart items are inserted.
        line_items,
        success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${req.headers.origin}`,
        expires_at: Math.floor(Date.now() / 1000) + 1800, // 
      };
      const checkoutSession = await stripe.checkout.sessions.create(params);
   
  
      res.status(200).json(checkoutSession);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  }
}

How can I get the original ID in order to change the status of those products in the CMS.

I've been dealing with this issue for a couple of days, I can get the successufll results in the webhook api made from stripe but I onle get the "line_items" with the details transformed by stripe.

Am I thinking this the right way? or maybe there is another solution.

My flow of thinking it is

cart with products(id, details, etc) --> handlecheckout --> createSession -->> if success apply webhook from stripe that with the products ids pause or delete those products from my CMS .

i'll really appreciate some help

thanks


Solution

  • When creating the Checkout Session, you could use the metadata parameter to store the original ID of the products being bought. Then when you receive the checkout.session.completed event, you check the metadata in the payload to get back the IDs and update your database accordingly.