I am trying to push the stripe checkout line_items price data to firestore by creating a webhook functions using react node js as the below code shown.
exports.stripeWebhook=functions.https.onRequest(async (req, res)=>{
const stripe = require("stripe")(functions.config().stripe.token);
let event;
try {
const whSec=functions.config().stripe.payments_webhook_secret;
event =stripe.webhooks.constructEvent(
req.rawBody,
req.headers["stripe-signature"],
whSec,
);
} catch (err) {
console.error("Webhook signature verification failed.");
return res.sendStatus(400);
}
const dataObject=event.data.object;
const session = await stripe.checkout.sessions.retrieve(dataObject.id, {
expand: ['line_items']
});
await admin.firestore().collection("customer").doc(String(dataObject.customer_email)).collection("order").doc().set({
checkoutSessionId:dataObject.id,
paymentStatus: dataObject.payment_status,
shppingInfo:dataObject.shipping,
amountTotal:dataObject.amount_total/100,
customerId:dataObject.customer,
CustomerEmail:dataObject.customer_email,
orderItems:session.line_items.price_data,
});
return res.sendStatus(200);
});
The function works fine except orderItems:session.line_items.price_data, it shows an error as an undefined firestore value. if I change to orderItems:session.line_items, it has no error, but the line_items info shown in firestore (screen shot below is not what I want, I just want the line_items.price_data which include just item title, price and images.
My question is how to get each item price_data from line_items?
You could try using the listLineItems
method instead, and expand the product object inside data.price.product
(according to the guide for expanding nested objects in lists).
const lineItems = await stripe.checkout.sessions.listLineItems(id, {expand: ['data.price.product']})
As you are currently retrieving the Session object with the expanded line_items
data, this data won't include the product's name, images, description, etc. It looks like the problem is caused by these API calls, as opposed to something in your Firebase function or Firestore.
We can see that the product data from list_items.data.price.product
is shown as expandable, which confirms it needs to be expanded. It also seems that there is no price_data
field (but instead only price
) nor product_data
(but instead product
) within the responses. These specific fields are apparently available only when creating Sessions.
You would end up with something like:
await admin.firestore().collection("customer").doc(String(dataObject.customer_email)).collection("order").doc().set({
//...
orderItems: lineItems.data[0].price //includes product details from nested expand
});
Since line items data
is an array containing each item, you would need to build the array to save in Firestore as your use case requires. Let me know if this was helpful.