如何在 Stripe webhook 中获取产品 ID

Oma*_*kry 10 javascript node.js express sequelize.js stripe-payments

当 checkout.session.completed 发生时,我使用 stripe webhook 将购买的产品添加到我的 sql 数据库中,这是我的代码:

router.post('/webhook', bodyParser.raw({ type: 'application/json' }), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;

try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
    return response.status(400).send(`Webhook Error: ${err.message}`);
}

// Handle the checkout.session.completed event
if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
//here i want to increment the product's buy counter by 1 in the database but stripe only gives name and price, which are not unique, so i need the product id

}

// Return a response to acknowledge receipt of the event
response.json({ received: true });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用 Sequelize,所以当 checkout.session.completed 发生时我需要执行类似的操作:

products.findOne({
   where: product_id: the purchased product id
}).then(product => {
   product.update({ buy_counter: product.buy_counter++})
}
Run Code Online (Sandbox Code Playgroud)

我可以通过任何方式在 Stripe 会话中找到产品的产品 ID

小智 12

在给定的结帐会话期间购买的产品可在该会话的line_items属性中找到:

https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-line_items

请注意,line_items默认情况下不包含它们,您需要在单独的请求中检索结账会话,并指定您希望将它们line_items包含在响应中。您可以在 Stripe 文档中找到这样的示例:

https://stripe.com/docs/expand#includable-properties

例如:

      // Handle the checkout.session.completed event
      if (event.type === "checkout.session.completed") {
        const session = event.data.object;
        // Note that you'll need to add an async prefix to this route handler
        const { line_items } = await stripe.checkout.sessions.retrieve(
          session.id,
          {
            expand: ["line_items"],
          }
        );

        //here i want to increment the product's buy counter by 1 in the database but stripe only gives name and price, which are not unique, so i need the product id
      }
Run Code Online (Sandbox Code Playgroud)


小智 8

您需要做的是在创建会话时添加元数据对象,如下所示

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    metadata: {
        order_id: parsedOrder._id,
    },
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            
            name: 'Stubborn Attachments',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: _orders_total_value * 100,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success`,  // can send in the id of the order if already created with the property of the payment pending
    cancel_url: `${YOUR_DOMAIN}/cancel`, 
  });
Run Code Online (Sandbox Code Playgroud)

您应该能够在 webhook 会话对象中接收此元数据对象


    id: 'cs_test_a1e81BPpUyROiKasfagWeqWrwEwWitAggwreSW6zjtoT6PMtbHaoMZ985TLi',
    object: 'checkout.session',
    allow_promotion_codes: null,
    amount_subtotal: 4000,
    amount_total: 4000,
    billing_address_collection: null,
    cancel_url: 'http://localhost:4200/cancel',
    client_reference_id: null,
    currency: 'usd',
    customer: 'cus_JQAHHil3j2iEbc',
    customer_details: { email: 'customeremail@email.com', tax_exempt: 'none', tax_ids: [] },
    customer_email: null,
    livemode: false,
    locale: null,
    metadata: { order_id: '60910a8b62b44e8de4fe0adb' },
    mode: 'payment',
    payment_intent: 'pi_1InJwNDCa2d3q3OjcblBYNql',
    payment_method_options: {},
    payment_method_types: [ 'card' ],
    payment_status: 'paid',
    setup_intent: null,
    shipping: null,
    shipping_address_collection: null,
    submit_type: null,
    subscription: null,
    success_url: 'http://localhost:4200/success',
    total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 0 }

您可以将 order_id 替换为您的 Product_id,或者您可以在元数据中添加任何其他有用的信息。