Hello guys I am trying to send the shipping address to api/checkout. I tried sending the body as an object and take cart details and shipping address as object properties, but that did not work. So I am am asking is there any way to send cart details and shipping address in body?
here is route.js:
大家好,我正试着把送货地址发送到API/Checkout。我尝试将身体作为对象发送,并将购物车详细信息和送货地址作为对象属性,但这不起作用。所以我在问,有没有办法在正文中发送购物车的详细信息和发货地址?以下是route.js:
import { NextResponse } from "next/server";
import { validateCartItems } from "use-shopping-cart/utilities";
import { inventory } from "@/config/inventory";
import { stripe } from "@/lib/stripe";
export async function POST(request) {
const cartDetails = await request.json();
const lineItems = validateCartItems(inventory, cartDetails);
const origin = request.headers.get("origin");
const session = await stripe.checkout.sessions.create({
submit_type: "pay",
mode: "payment",
payment_method_types: ["card"],
line_items: lineItems,
shipping_address_collection: {
allowed_countries: ["US"],
},
shipping_options: [
{
shipping_rate: "shr_1Nlx6dJWKRwaU5FYLj34H9wO",
},
],
billing_address_collection: "auto",
success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${origin}/cart`,
});
return NextResponse.json(session);
}
page.jsx: (its a snippet)
Jsx:(这是一个代码片段)
const {
cartDetails,
incrementItem,
decrementItem,
removeItem,
formattedTotalPrice,
totalPrice,
cartCount,
redirectToCheckout,
} = useShoppingCart();
const requestBody = {
cartDetails: cartDetails,
shippingAddress: {
name: "John Doe",
street: "123 Main St",
city: "Example City",
},
};
async function onCheckout() {
setLoading(true);
const response = await fetch("/api/checkout", {
method: "POST",
body: JSON.stringify(cartDetails),
});
const data = await response.json();
const result = await redirectToCheckout(data.id);
if (result?.error) {
console.error(result);
}
setLoading(false);
}
Now this code works already and takes me to stripe checkout page. I just want to send the shipping address as well. Thank you in advance!
现在,这段代码已经开始工作,并将我带到Stripe Check Out页面。我只想把送货地址也寄给你。提前谢谢您!
更多回答
优秀答案推荐
To be able to assemble the body as JSON on the API side, you need to set the Content-Type
header accordingly:
为了能够在API端将Body组装为JSON,您需要相应地设置Content-Type头部:
const response = await fetch("/api/checkout", {
method: "POST",
body: JSON.stringify(cartDetails),
headers: {
"Content-Type": "application/json",
},
});
更多回答
我是一名优秀的程序员,十分优秀!