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

huangapple go评论129阅读模式
英文:

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

问题

我正在使用NextJs、Sanity作为CMS和Stripe构建电子商务网站。

问题出在创建结账会话时,Stripe会转换我的CMS数据,然后如果我通过Webhook成功检索数据,我将无法获取相同的产品ID,而是会得到Stripe生成的新ID而不是来自我的CMS的ID。

这是创建会话时的代码示例,请注意我在使用use-shopping-cart来处理产品购物车(在发送后验证数据,还将数组转换为Stripe接受的格式):

/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, {
  apiVersion: "2020-03-02",
});

export default async function handler(req, res) {
  if (req.method === "POST") {
    try {
      // 验证从客户端发送的购物车详细信息。
      const cartItems = req.body;

      // 使用Sanity客户端执行merchQuery。
      let sanityData = await client.fetch(merchQuery);

      // 然后根据Sanity的数据验证POST请求。
      const line_items = validateCartItems(sanityData, cartItems);

      // 从请求参数创建结账会话。
      const params = {
        submit_type: "pay",
        mode: "payment",
        payment_method_types: ["card"],
        billing_address_collection: "auto",
        shipping_address_collection: {
          allowed_countries: ["US"],
        },
        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");
  }
}

如何获取原始ID以更改CMS中这些产品的状态?

我已经处理了这个问题几天了,我可以从Stripe创建的Webhook API中获取成功的结果,但我只能获得Stripe转换后的“line_items”详细信息。

我的思路是:

购物车包含产品(ID、详细信息等) --> 处理结账 --> 创建会话 --> 如果成功,从Stripe应用Webhook,使用产品ID暂停或删除CMS中的这些产品。

我会非常感谢一些帮助,谢谢。

英文:

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

答案1

得分: 0

创建结帐会话时,您可以使用metadata参数来存储所购买产品的原始ID。然后,在收到checkout.session.completed事件时,您可以检查有效载荷中的metadata,以获取ID并相应地更新您的数据库。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月9日 21:44:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定