Stripe sends events for a number of events. The issue I had was I needed to know which products were purchased when consuming those checkout.session.completed
events.
After validating the session with secret keys etc, we can get the Stripe event details.
These details don’t come with product info. We need to expand line_items
in order to see what was bought.
const { line_items } = await stripeInstance.checkout.sessions.retrieve(
sessionId,
{
expand: ["line_items"],
}
);
Once we have the line items we can dig into the data array, loop over the items and look for our product. We get description
, amount_total
and price which has our product
. This is the ID I need to confirm.
// simpleExample
try {
const validProducts = ["prod_JxfZfasrewgvdfse", "prod_fakeppp"];
for (const item of line_items.data) {
if (validProducts.includes(item.price.product)) {
return {
email: customer.email,
name: customer.name,
amount: amount_total,
product: {
productId: item.price.product,
productName: item.description,
},
};
}
}
...
} catch (error) {
...
}
Example of line item data.
line_items: {
object: "list",
data: [
{
id: "li_1QC...",
object: "item",
...
amount_total: 24491,
description: "Chocolate Peanuts",
price: {
id: "peanut-product",
...
product: "prod_JxfZfasrewgvdfse",
...
},
quantity: 1,
},
],
has_more: false,
url: "/v1/checkout/sessions/cs_test_a...",
},