简体   繁体   中英

How to send metadata in stripe during checkout process?

const combineData = function (prod, pot, data) {
const newData = [...prod, ...pot];
const finalCheckout = [];

for (let i = 0; i < newData.length; i++) {
finalCheckout.push({
  name: newData[i].plantName || newData[i].potName,
  images: [newData[i].images[0]],
  amount: newData[i].price * 100,
  currency: "inr",
  quantity: data[i].quantity,
  
  metadata: { id: String(newData[i]._id) },// **Mongoose ID**
});
}
return finalCheckout;
};

exports.getCheckOutSession = catchAsync(async (req, res, next) => {
   const [product, pot] = filterVal(req.body.product);
   const userId = req.user._id;

   const products = await ProductModel.find({ _id: { $in: product } });
   const pots = await PotModel.find({ _id: { $in: pot } });
   const newData = combineData(products, pots, req.body.product);

   // 2. create the checkout session
   const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      success_url: `${req.protocol}://${req.get("host")}/?alert=booking`,
      cancel_url: `${req.protocol}://${req.get("host")}/products/`,
      customer_email: req.user.email,
      client_reference_id: userId,
      line_items: newData,
   });

  res.status(200).json({
    status: "success",
    url: session.url,
  });
});

I'm build an Ecommerce website, when user makes a payment I want to send the product id's stored in my mongodb database as metadata in stripe. But i'm getting an error how to solve this.

Error:parameter_unknown - line_items[0][metadata] Received unknown parameter: line_items[0][metadata]

Stripe is rejecting the mongodb id's has metadata

"metadata": { "id": "61e40a5a7d83539092e7a92f" }

NOTE: I'm sending all the successfull data like price, name,images amount,quanity in the above combineData function.

  1. I have tested the above code without metadata key. It works fine my payment is registered and webhook event is registered in stripe.
  2. When i use metadata keyword the above error occurs in stripe.

You need to create product + price first.

After informing stripe of the line items, the session token will be returned to client side, and users will then be redirected to stripe's payment page.

Stripe will be able to know what items (eg image, product name, product description) to display to the user, through the line items you submitted while creating the session.

If you just pass a MongoDB _id, stripe will not know what items to display since they have no info of the product.

  const session = await stripe.checkout.sessions.create({
    customer: customerId,
    billing_address_collection: 'auto',
    payment_method_types: ['card'],
    line_items: [
      {
        price: STRIPE_PRODUCT_PRICE, //price of created product
        // For metered billing, do not pass quantity
        quantity: 1,
      },
    ],
    // success_url: `${YOUR_DOMAIN}?success=true&session_id={CHECKOUT_SESSION_ID}`,
    // cancel_url: `${YOUR_DOMAIN}?canceled=true`,
  });

Example of how strip product and price id looks like. A single product can have many different prices.

STRIPE_PRODUCT=prod_I7a38cue83jd
STRIPE_PRICE=price_1HXL0wBXeaFPR83jhdue883

These references will be useful to you.

Creating a product: https://stripe.com/docs/api/products/create

Creating a price: https://stripe.com/docs/api/prices/create

I will normally store the product id and price id as stripe_product_id and stripe_product_price in the local MongoDB database so you can use during checkout.

So after you receive the order, you can create a local order first, with the products and quantity, then...

  const line_items = ordered_products.map(product => ({ price: product.stripe_product_price, quantity: product.quantity }))

  const session = await stripe.checkout.sessions.create({
      ....
      line_items,
      ...
  })

Advanced method - creating product and price on the go.

This is more tedious because you need to do more checks.

You can refer to creating line_items in the link below from stripe docs.

https://stripe.com/docs/api/checkout/sessions/object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM