The error happens at if cart[1] The cart[1] is underlined and I can't deploy the code to Vercel.
Thought it was a stripe problem but I thoroughly checked stripes API and this code make as much sense as I can think of.
here's is the full file. its a.ts extension
import { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2020-03-02",
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
try {
const cartItems = req.body;
const line_items = validateCartItems(cartItems);
const subscriptionInCart = isSubscriptionInCart(cartItems);
const params: Stripe.Checkout.SessionCreateParams = {
mode: subscriptionInCart ? "subscription" : "payment",
payment_method_types: ["card"],
billing_address_collection: "auto",
shipping_address_collection: {
allowed_countries: ["US", "CA"],
},
line_items,
success_url: `${req.headers.origin}/result?session_id=. {CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/use-shopping-cart`,
};
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params);
res.status(200).json(checkoutSession);
} catch (err: any) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}
const validateCartItems = (cartDetails: any) => {
const validatedItems = [];
for (const sku in cartDetails) {
const product = cartDetails[sku];
const item = {
price: product.sku,
quantity: product.quantity,
};
validatedItems.push(item);
}
return validatedItems;
};
const isSubscriptionInCart = (cartDetails: any) => {
let subscriptionFound = false;
for (const cartItem of Object.entries(cartDetails)) {
if (cartItem[1].recurring) {
subscriptionFound = true;
}
}
return subscriptionFound;
};
As @juliomalves mentioned, your cartDetails
is correctly identifying a type error.
You need to specify a type for cartDetails
so that cartItem[1].recurring
is expected to be defined in a way that matches with your use of it.
Something like const isSubscriptionInCart = (cartDetails: Array<{recurring: boolean}>) => {...}
or better yet defining your own type CartItem
and using Array<CartItem>
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.