I have been working on developing an ecommerce platform using NextJs, Sanity as the CMS, and Stripe as the payment gateway. However, I have encountered an issue during the checkout process. When creating the checkout session, Stripe seems to alter the product IDs fetched from my CMS. Consequently, if I try to retrieve the data after a successful transaction through a webhook, I end up with new IDs generated by Stripe, rather than the original IDs from my CMS.
Below is a snippet of the code used to create the session. I am utilizing use-shopping-cart library to manage the products in the cart, ensuring data validation and transformation to meet Stripe's requirements.
/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";
// Initialize Stripe
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY, {
apiVersion: "2020-03-02",
});
// Handle POST request
export default async function handler(req, res) {
if (req.method === "POST") {
try {
// Validate the cart items sent by the client
const cartItems = req.body;
// Fetch data from Sanity CMS
let sanityData = await client.fetch(merchQuery);
// Validate the POST request against the data from Sanity
const line_items = validateCartItems(sanityData, cartItems);
// Create Checkout Sessions using body params
const params = {
submit_type: "pay",
mode: "payment",
payment_method_types: ["card"],
billing_address_collection: "auto",
shipping_address_collection: {
allowed_countries: ["US"],
},
line_items, // Insert validated cart 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"');
}
}
I am seeking guidance on how to retrieve the original IDs to alter the status of the products in the CMS. Despite successfully getting results in the webhook API provided by Stripe, the 'line_items' contain details transformed by Stripe. Am I approaching this issue correctly, or is there a better solution available?
My thought process involves handling a cart with products (IDs, details, etc.) and then proceeding to handle checkout, create a session, and upon success, trigger a webhook from Stripe to pause or delete those products in my CMS.
Any assistance on this matter would be highly appreciated. Thank you.