When using Stripe checkout, the database IDs are altered, causing issues when trying to delete or update stock in the database using a webhook

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.

Answer №1

By utilizing the metadata parameter during Checkout Session creation, you can conveniently store the original product IDs. Once the checkout.session.completed event is received, simply extract the IDs from the payload's metadata and update your database accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Expanding Image with HTML and CSS: A Guide

In the process of creating my website, I encountered an issue with the logo placement. I wanted the logo to be in the top left corner, similar to the one shown in this image. Initially, everything was working fine until I made some adjustments to move the ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...

Logging in using email, phone number, or username on Node.js platform

How can I implement a login system in node.js and MongoDB that allows users to log in with their email, phone number, or username along with a password? Similar to the login functionality seen on Instagram, users should be able to enter their email or u ...

Broadcasting events across the entire system

I'm trying to accomplish something specific in Angular2 - emitting a custom event globally and having multiple components listen to it, not just following the parent-child pattern. Within my event source component, I have: export class EventSourceCo ...

ActivatedRoute not receiving the parameter value

Having trouble retrieving the parameter from the route and passing it to a function within the component which then communicates with the service. Initially tried placing the parameter retrieval in the NgInit but moved it to the constructor, still no succ ...

Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to ...

Clicking on navigation does not close Bootstrap dropdown

When I use this code on my HTML page, the dropdown menu appears correctly. However, once I click a link, the menu does not close and remains open. How can I resolve this issue? <div class="col-lg-8 col-md-8 col-xs-2 accordion-menu"> <button t ...

Dealing with an issue where Next.js router is not properly handling query parameters and returning them as undefined

Within my Next.js application, I have a page that functions as a search feature. The path for this page is structured like so: /search?q=search+slug. This specific page loads data on the client side and it's crucial to access the value of router.query ...

Enhancing Bootstrap Carousel with various effects

My exploration of the web revealed two distinct effects that can be applied to Bootstrap Carousel: Slide and Fade. I'm curious if there are any other unique effects, such as splitting the picture into small 3D boxes that rotate to change the image? ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

The age calculator is failing to display the accurate age calculation

This code is designed to compute the age based on the selected value in the combo box, and display the result in the text box below. The age should update every time the user changes the selected value in the combo box. However, the computed age is not cur ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

Strategies for transferring retrieved data to the getServerSideProps function

I am currently utilizing the Context API to retrieve data and then pass that data to the getServerSideProps function, but encountering the following error: The React Hook "useContext" is being called in a function "getServerSideProps" that is neither a Re ...

Iterating through each ID in a table/cell using .NET MVC with the @

Whenever the table is loaded, I need to run a JavaScript function on each row for cell 4. This function will format the JSON string that is inserted into it. The current code I have only updates the first row/cell... I believe the issue may be related to ...