NEXT JS:我试图将状态变量“cart”的内容放入 STRIPE api 的 POST 请求正文中。 购物车的格式为 [{id: 1, amount: 1}, {id: , amount: }.......]
我尝试将项目直接放入 api 处理程序 (list_items) 中,效果很好。但我无法让我的“购物车”变量显示在那里,所以我想我必须将这些项目包含在 POST 请求本身中。已尝试让它运行(包括那里的对象和 JSON.stringify 作为“line_items”变量的属性,但无济于事。 也许有人可以帮助我?
API 处理程序:
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.send({
error: 'Method need to be POST',
});
}
const domainURL = 'http://localhost:3000';
// const { quantity, mode, productKey } = req.body;
const pmTypes = ['card'];
const session = await stripe.checkout.sessions.create({
payment_method_types: pmTypes,
mode: 'payment',
locale: 'en',
line_items: the_variable????,
success_url: `${domainURL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/cart`,
});
res.send({
sessionId: session.id,
});
}
POST 请求:
const stripeLoader = loadStripe(props.pk);
const redirectToCheckout = async () => {
const stripeClient = await stripeLoader;
const { sessionId } = await fetch('api/checkout_sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body : {????}
}).then((res) => res.json());
stripeClient.redirectToCheckout({ sessionId });
};
您可以使用任何您喜欢的结构在客户端和后端之间进行通信,但是您向 Stripe 发出的用于创建会话的 API 请求必须符合
line_items
API 参数预期形状 (docs)。
您可以使用 price_data
对每个项目
即时定义定价:
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'T-shirt',
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
});
或者您可以使用预定义价格:
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{
price: 'price_123',
quantity: 1,
},{
price: 'price_456',
quantity: 3,
}],
mode: 'payment',
success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'https://example.com/cancel',
});
我弄清楚了如何发出 POST 请求。身体必须看起来像这样:
body: JSON.stringify({
lineItems: props.cart.map((singleItem) => {
return {
price: <the_stripe_price_key_for_the_given_product>,
quantity: <the_amount>,
};
}),
})
在 API 处理程序中包含以下行:
const { lineItems } = req.body;
并设置 line_items: lineItems
因此,正如诺兰指出的那样,line_items 将接受一个对象数组(在我的例子中是通过映射“购物车”状态变量生成的)。
我做了一些不同的事情来将多个购物车项目动态地添加到我的 API 中。 这是我的前端。
export default function PreviewPage() {
// this is just example data you can add to this list
//how you would like to.
const [formData, setFormData] = useState({
codesToSend:[
{ price: 'price_1iasdhfwie8', quantity: 1 },
{ price: 'price_i383829wdff', quantity: 1 },
]
});
const submitHandler = async(e) => {
e.preventDefault();
const response = await fetch('/api/checkout_sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
formData
}),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
console.log(result)
// Redirect the user to the Stripe checkout session URL
window.location.href = result.url;
};
if (req.method === 'POST') {
const { formData } = await req.body;
console.log(formData)
const codesToSend= formData.codesToSend
try {
const session = await stripe.checkout.sessions.create({
line_items:
codesToSend,
mode: 'payment',
success_url: `${req.headers.origin}/?success=true`,
cancel_url: `${req.headers.origin}/?canceled=true`,
automatic_tax: { enabled: true },
});
// console.log(session.url)
res.status(200).json({ url: session.url });
} catch (err) {
res.status(err.statusCode || 500).json(err.message);
}
}
else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}