How can you include extra information in your Stripe session?

Here is the code snippet for my session:

const stripe = require('stripe')(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);
export default async function handler(req, res) {
    if (req.method === 'POST') {
        try {
            const params = {
                submit_type: 'pay',
                mode: 'payment',
                payment_method_types: ['card'],
                billing_address_collection: 'auto',
                shipping_options: [{
                        shipping_rate: 'shr_1LdjWJA0PvM7uNfTBERqQFUg'
                    },
                    {
                        shipping_rate: 'shr_1LdjXUA0PvM7uNfTAg076Fc0'
                    },
                ],
                line_items: req.body.map((item) => {
                    const img = item.image[0].asset._ref;
                    const newImage = img.replace('image-', 'https://cdn.sanity.io/images/w1sxln47/dev/').replace('-jpg', '.jpg')
                    return {
                        price_data: {
                            currency: 'eur',
                            product_data: {
                                name: item.name,
                                images: [newImage],
                                description: item.details
                            },
                            unit_amount: item.price * 100,
                        },
                        adjustable_quantity: {
                            enabled: true,
                            minimum: 1,
                        },
                        quantity: item.quantity,
                    }
                }),
                success_url: `${req.headers.origin}/?success=true`,
                cancel_url: `${req.headers.origin}/?canceled=true`,
            }
            // Create Checkout Sessions from body params.
            const session = await stripe.checkout.sessions.create(params);
            res.status(200).json(session)
        } catch (err) {
            res.status(err.statusCode || 500).json(err.message);
        }
    } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method Not Allowed');
    }
}

I also have an object with a sub-object named "dress". The path to access dress would be item.dress.height/etc image link

Is there a way to pass additional parameters to stripe? I attempted to use metadata, but it does not work with dynamic data. I need to include my "dress" object in the stripe success payment page. Any suggestions are appreciated. Thank you.

Answer №1

insert it into the metadata section

const transaction = await stripe.checkout.sessions.create({
    payment_methods: ["card"],
    success_url: `paymentSuccessUrl`,
    // handle failed payment
    cancel_url: `fallbackPaymentUrl`,
    customer_email: req.user.email,
    client_reference_id: req.query.bookingId,
    // store extra details in session metadata
    metadata: { checkInDate, checkOutDate, durationOfStay },
   //....   
  });

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

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

Action Table Header Not Found in Material UI React Components

Currently incorporating material UI into my project and looking to add an action button in my material table. However, upon trying to include the table, the action header is not displaying as expected. https://i.stack.imgur.com/s6cjE.png https://i.stack. ...

Is it possible to run both a Spring Boot JAR and Next.js app on the same port within a packaged JAR

Is it possible to run NextJs code on a different port like 3000, and have it combined with Springboot in an executable Jar/WAR (with embedded Tomcat) running on default port 8080? Can the combined application jar/war be configured to run on a single port? ...

Adjust the width of the lower drawer component using React

After some extensive searching, I've hit a roadblock trying to tweak the width of an imported Material UI Drawer Swipeable edge. My aim was to make it Bottom-type without spanning the entire screen. I managed to adjust the top width using sx. However ...

Error encountered in React MUI: Element in array is missing the required 'key' prop react/jsx-key

{ field: 'deletedAt', headerName: 'DeleteAt', type: 'actions', width: 200, editable: false, getActions: () => [<GridActionsCellItem icon={<DeleteIcon />} label="Delete" />], } ...

Explore a personalized color scheme within MUI themes to enhance your design

I'm looking to customize the colors in my theme for specific categories within my application. I set up a theme and am utilizing it in my component like this: theme.tsx import { createTheme, Theme } from '@mui/material/styles' import { red ...

React hooks - Issue with updating state properties within sidebar display

When resizing the window, I have an event that will display either the desktop sidebar or the mobile sidebar. However, there are variables that are not immediately updated to show the sidebar correctly based on the window size. In a desktop window, this ca ...

Autocomplete feature in MaterialUI is not functioning properly as a controlled component

After creating the autocomplete component and setting the default value as my state this.state.quest.ansType, I encountered an error when trying to change this state: The component is changing the default value state of an uncontrolled Autocomplete after b ...

The challenge of integrating Strapi with React and Material UI data tables

Recently, I started working with React and set up a backend using Strapi. After testing the GraphQL query and confirming that it retrieves values for all nodes, I encountered an issue while populating a Material UI DataGrid component in React. Most of the ...

If you're using `react-router-dom` v6 and `useNavigate`, you may need to refresh the page

There is a page called /studentprofile where users can view their profile details. When the user clicks the 'edit profile' button, they are taken to /editprofile where they can update their profile using a form. After clicking the 'update&ap ...

Error No Entry is encountered when attempting to run the next start operation

Encountering an issue with the next start command showing an entry error. The configuration for my next project looks like this: Usually, I execute npm run dev and npm run build: /** @type {import('next').NextConfig} */ const nextConfig = { ...

How can you trigger useEffect using a context variable as a dependency in React?

Struggling to get a useEffect hook to trigger when its dependency is a useContext variable. The Context contains an "update" variable that changes, but the effect doesn't fire as expected. import { useEffect, useState, useContext } from "react" import ...

The onSubmit function in React JavaScript is failing to execute, it is not triggering and no error message is being displayed on the frontend console

As a newcomer to React.js, I recently came across an article detailing how to perform CRUD operations with React Express and MongoDB. However, after implementing the code, I encountered an issue when trying to add a user. Upon clicking the 'Save' ...

Retrieve next-i18next translations beyond the current page or component

Currently working on a project using Next.JS and Typescript, I am looking to incorporate next-i18next translations outside of the page/component. The goal is to localize validation messages within a separate utility class that defines the validation engi ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

Every time I try to utilize "useCallback," it results in a TypeError error popping up

I am struggling with an issue related to a const experience that involves creating 6 experiences with their respective popovers. I have been instructed to use useCallback, but every time I attempt to do so, I encounter an error message. This relates to my ...

Can reducers be nested within each other in a Redux store?

Consider an application with an initialStore = { users :{} }, where each user is stored inside the 'users' object by its id as a key. When a component displays a list of users, updating a single user within this object causes the entire list to r ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

Encountered a FirebaseError while trying to build a Docker image on Github Actions due to an error with the API key (auth/

My goal is to establish a streamlined CI/CD pipeline utilizing GitHub Actions. This process involves testing, docker image building, and deploying to Google Cloud Run. While everything functions correctly on my local environment due to access to the .env ...

Is there a way for me to customize the color of the sorting icon and menu icon in the MUI X

https://i.stack.imgur.com/0Yo9N.png After examining the properties filterIcon, menuIcon, and menuIconButton, I am unsure about how to implement them. <DataGrid rows={rows} columns={columns} rowsPerPageOptions={rowsPerPage} disableSelectionO ...