【问题标题】:How can I get the product ID in Stripe webhook如何在 Stripe webhook 中获取产品 ID
【发布时间】:2020-12-12 03:00:26
【问题描述】:

当 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 });
});

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

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

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

【问题讨论】:

    标签: javascript node.js express sequelize.js stripe-payments


    【解决方案1】:

    在特定结帐会话期间购买的产品可在会话的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
          }
    

    【讨论】:

      【解决方案2】:

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

        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`, 
        });
      

      您应该能够在 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,或者您可以在元数据中添加任何其他有用的信息。

      【讨论】:

        猜你喜欢
        • 2015-06-16
        • 2021-01-09
        • 2022-12-28
        • 1970-01-01
        • 1970-01-01
        • 2021-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        相关资源
        最近更新 更多