这是前端代码:
const createOrder = () => {
// Order is created on the server and the order id is returned
return fetch(`${serverUrl}/api/orders`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
// use the "body" param to optionally pass additional order information
// like product skus and quantities
body: JSON.stringify({
cart: [
{
id:'woodcandysofa',
name:'Wood Candy Sofa',
quantity: 1,
price: 399
},
],
}),
})
.then((response) => response.json())
.then((order) => order.id);
};
这是后端:
module.exports.createOrder = async (cart) => {
// use the cart information passed from the front-end to calculate the purchase unit details
console.log(
"shopping cart information passed from the frontend createOrder() callback:",
cart,
);
const totalPrice = cart.reduce ((prev, curr) => prev + curr.price, 0);
const accessToken = await generateAccessToken();
const url = `${base}/v2/checkout/orders`;
const payload = {
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "EUR",
breakdown: {
item_total: totalPrice
},
value: totalPrice
},
items: cart.map (item => ({
name: item.name,
quantity: item.quantity,
unit_amount: { currency_code: 'EUR', value: item.price * item.quantity}
}))
},
],
}
这是我在后端收到的错误:
_Response [Response] { [Symbol(realm)]: null, [Symbol(state)]: { aborted: false, rangeRequested: false, timingAllowPassed: true, requestIncludesCredentials: true, type: 'default', status: 400, timingInfo: { startTime: 11720.420841999352, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: 11720.420841999352, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null }, cacheState: '', statusText: 'Bad Request',
如果我不传递任何项目而只传递金额(货币代码和值),那么它就可以正常工作。但我需要有关到底购买了什么的信息。
有什么想法吗?感谢您的阅读。
尝试集成 PayPal v2 并提供 items 数组。没有 items 数组,它可以工作 - 有了它,它就会失败。
这是崩溃。正确的语法是:
breakdown: {
item_total: {value: totalPrice, currency_code:'EUR'}
}